Bug 14570: (QA follow-up) Fix tests
[koha.git] / t / db_dependent / Koha / Patrons.t
1 #!/usr/bin/perl
2
3 # Copyright 2015 Koha Development team
4 #
5 # This file is part of Koha
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use Test::More tests => 40;
23 use Test::Warn;
24 use Test::Exception;
25 use Test::MockModule;
26 use Time::Fake;
27 use DateTime;
28 use JSON;
29 use Data::Dumper;
30
31 use C4::Circulation;
32 use C4::Biblio;
33 use C4::Auth qw(checkpw_hash);
34
35 use Koha::ActionLogs;
36 use Koha::Holds;
37 use Koha::Old::Holds;
38 use Koha::Patrons;
39 use Koha::Patron::Categories;
40 use Koha::Patron::Relationship;
41 use Koha::Database;
42 use Koha::DateUtils;
43 use Koha::Virtualshelves;
44
45 use t::lib::TestBuilder;
46 use t::lib::Mocks;
47
48 my $schema = Koha::Database->new->schema;
49 $schema->storage->txn_begin;
50
51 my $builder       = t::lib::TestBuilder->new;
52 my $library = $builder->build({source => 'Branch' });
53 my $category = $builder->build({source => 'Category' });
54 my $nb_of_patrons = Koha::Patrons->search->count;
55 my $new_patron_1  = Koha::Patron->new(
56     {   cardnumber => 'test_cn_1',
57         branchcode => $library->{branchcode},
58         categorycode => $category->{categorycode},
59         surname => 'surname for patron1',
60         firstname => 'firstname for patron1',
61         userid => 'a_nonexistent_userid_1',
62         flags => 1, # Is superlibrarian
63     }
64 )->store;
65 my $new_patron_2  = Koha::Patron->new(
66     {   cardnumber => 'test_cn_2',
67         branchcode => $library->{branchcode},
68         categorycode => $category->{categorycode},
69         surname => 'surname for patron2',
70         firstname => 'firstname for patron2',
71         userid => 'a_nonexistent_userid_2',
72     }
73 )->store;
74
75 t::lib::Mocks::mock_userenv({ patron => $new_patron_1 });
76
77 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
78
79 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
80 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
81
82 subtest 'library' => sub {
83     plan tests => 2;
84     is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
85     is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
86 };
87
88 subtest 'guarantees' => sub {
89     plan tests => 13;
90
91     t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test|test2' );
92
93     my $guarantees = $new_patron_1->guarantee_relationships;
94     is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
95     is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee relationships' );
96     my @guarantees = $new_patron_1->guarantee_relationships;
97     is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantee_relationships should return an array in a list context' );
98     is( scalar(@guarantees), 0, 'new_patron_1 should have 0 guarantee' );
99
100     my $guarantee_1 = $builder->build({ source => 'Borrower' });
101     my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
102     my $guarantee_2 = $builder->build({ source => 'Borrower' });
103     my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
104
105     $guarantees = $new_patron_1->guarantee_relationships;
106     is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantee_relationships should return a Koha::Patrons result set in a scalar context' );
107     is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
108     @guarantees = $new_patron_1->guarantee_relationships;
109     is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantee_relationships should return an array in a list context' );
110     is( scalar(@guarantees), 2, 'new_patron_1 should have 2 guarantees' );
111     $_->delete for @guarantees;
112
113     #Test return order of guarantees BZ 18635
114     my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
115     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
116
117     my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
118
119     my $order_guarantee1 = $builder->build_object(
120         {
121             class => 'Koha::Patrons',
122             value => {
123                 surname     => 'Zebra',
124             }
125         }
126     )->borrowernumber;
127     $builder->build_object(
128         {
129             class => 'Koha::Patron::Relationships',
130             value => {
131                 guarantor_id  => $guarantor->id,
132                 guarantee_id => $order_guarantee1,
133                 relationship => 'test',
134             }
135         }
136     );
137
138     my $order_guarantee2 = $builder->build_object(
139         {
140             class => 'Koha::Patrons',
141             value => {
142                 surname     => 'Yak',
143             }
144         }
145     )->borrowernumber;
146     $builder->build_object(
147         {
148             class => 'Koha::Patron::Relationships',
149             value => {
150                 guarantor_id  => $guarantor->id,
151                 guarantee_id => $order_guarantee2,
152                 relationship => 'test',
153             }
154         }
155     );
156
157     my $order_guarantee3 = $builder->build_object(
158         {
159             class => 'Koha::Patrons',
160             value => {
161                 surname     => 'Xerus',
162                 firstname   => 'Walrus',
163             }
164         }
165     )->borrowernumber;
166     $builder->build_object(
167         {
168             class => 'Koha::Patron::Relationships',
169             value => {
170                 guarantor_id  => $guarantor->id,
171                 guarantee_id => $order_guarantee3,
172                 relationship => 'test',
173             }
174         }
175     );
176
177     my $order_guarantee4 = $builder->build_object(
178         {
179             class => 'Koha::Patrons',
180             value => {
181                 surname     => 'Xerus',
182                 firstname   => 'Vulture',
183                 guarantorid => $guarantor->borrowernumber
184             }
185         }
186     )->borrowernumber;
187     $builder->build_object(
188         {
189             class => 'Koha::Patron::Relationships',
190             value => {
191                 guarantor_id  => $guarantor->id,
192                 guarantee_id => $order_guarantee4,
193                 relationship => 'test',
194             }
195         }
196     );
197
198     my $order_guarantee5 = $builder->build_object(
199         {
200             class => 'Koha::Patrons',
201             value => {
202                 surname     => 'Xerus',
203                 firstname   => 'Unicorn',
204                 guarantorid => $guarantor->borrowernumber
205             }
206         }
207     )->borrowernumber;
208     my $r = $builder->build_object(
209         {
210             class => 'Koha::Patron::Relationships',
211             value => {
212                 guarantor_id  => $guarantor->id,
213                 guarantee_id => $order_guarantee5,
214                 relationship => 'test',
215             }
216         }
217     );
218
219     $guarantees = $guarantor->guarantee_relationships->guarantees;
220
221     is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
222     is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
223     is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
224     is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
225     is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
226 };
227
228 subtest 'category' => sub {
229     plan tests => 2;
230     my $patron_category = $new_patron_1->category;
231     is( ref( $patron_category), 'Koha::Patron::Category', );
232     is( $patron_category->categorycode, $category->{categorycode}, );
233 };
234
235 subtest 'siblings' => sub {
236     plan tests => 7;
237     my $siblings = $new_patron_1->siblings;
238     is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
239     my $guarantee_1 = $builder->build( { source => 'Borrower' } );
240     my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
241     my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
242     $siblings = $retrieved_guarantee_1->siblings;
243     is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
244     my @siblings = $retrieved_guarantee_1->siblings;
245     is( ref( \@siblings ), 'ARRAY', 'Koha::Patron->siblings should return an array in a list context' );
246     is( $siblings->count,  0,       'guarantee_1 should not have siblings yet' );
247     my $guarantee_2 = $builder->build( { source => 'Borrower' } );
248     my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
249     my $guarantee_3 = $builder->build( { source => 'Borrower' } );
250     my $relationship_3 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_3->{borrowernumber}, relationship => 'test' } )->store();
251     $siblings = $retrieved_guarantee_1->siblings;
252     is( $siblings->count,               2,                               'guarantee_1 should have 2 siblings' );
253     is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
254     is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
255     $_->delete for $retrieved_guarantee_1->siblings;
256     $retrieved_guarantee_1->delete;
257 };
258
259 subtest 'has_overdues' => sub {
260     plan tests => 3;
261
262     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
263     my $item_1 = $builder->build(
264         {   source => 'Item',
265             value  => {
266                 homebranch    => $library->{branchcode},
267                 holdingbranch => $library->{branchcode},
268                 notforloan    => 0,
269                 itemlost      => 0,
270                 withdrawn     => 0,
271                 biblionumber  => $biblioitem_1->{biblionumber}
272             }
273         }
274     );
275     my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
276     is( $retrieved_patron->has_overdues, 0, );
277
278     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
279     my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
280     is( $retrieved_patron->has_overdues, 0, );
281     $issue->delete();
282     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
283     $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
284     $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
285     is( $retrieved_patron->has_overdues, 1, );
286     $issue->delete();
287 };
288
289 subtest 'is_expired' => sub {
290     plan tests => 4;
291     my $patron = $builder->build({ source => 'Borrower' });
292     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
293     $patron->dateexpiry( undef )->store->discard_changes;
294     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
295     $patron->dateexpiry( dt_from_string )->store->discard_changes;
296     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
297     $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
298     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
299     $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
300     is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
301
302     $patron->delete;
303 };
304
305 subtest 'is_going_to_expire' => sub {
306     plan tests => 8;
307     my $patron = $builder->build({ source => 'Borrower' });
308     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
309     $patron->dateexpiry( undef )->store->discard_changes;
310     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
311
312     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
313     $patron->dateexpiry( dt_from_string )->store->discard_changes;
314     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
315
316     $patron->dateexpiry( dt_from_string )->store->discard_changes;
317     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
318
319     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
320     $patron->dateexpiry( dt_from_string->add( days => 11 ) )->store->discard_changes;
321     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 11 days ahead and pref is 10');
322
323     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
324     $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
325     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 10 days ahead and pref is 0');
326
327     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
328     $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
329     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 10 days ahead and pref is 10');
330     $patron->delete;
331
332     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
333     $patron->dateexpiry( dt_from_string->add( days => 20 ) )->store->discard_changes;
334     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 20 days ahead and pref is 10');
335
336     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
337     $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
338     is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
339
340     $patron->delete;
341 };
342
343
344 subtest 'renew_account' => sub {
345     plan tests => 48;
346
347     for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
348         my $dt = dt_from_string( $date, 'iso' );
349         Time::Fake->offset( $dt->epoch );
350         my $a_month_ago                = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
351         my $a_year_later               = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
352         my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
353         my $a_month_later              = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
354         my $a_year_later_plus_a_month  = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
355         my $patron_category = $builder->build(
356             {   source => 'Category',
357                 value  => {
358                     enrolmentperiod     => 12,
359                     enrolmentperioddate => undef,
360                 }
361             }
362         );
363         my $patron = $builder->build(
364             {   source => 'Borrower',
365                 value  => {
366                     dateexpiry   => $a_month_ago,
367                     categorycode => $patron_category->{categorycode},
368                     date_renewed => undef, # Force builder to not populate the column for new patron
369                 }
370             }
371         );
372         my $patron_2 = $builder->build(
373             {  source => 'Borrower',
374                value  => {
375                    dateexpiry => $a_month_ago,
376                    categorycode => $patron_category->{categorycode},
377                 }
378             }
379         );
380         my $patron_3 = $builder->build(
381             {  source => 'Borrower',
382                value  => {
383                    dateexpiry => $a_month_later,
384                    categorycode => $patron_category->{categorycode},
385                }
386             }
387         );
388         my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
389         my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
390         my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
391
392         is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
393
394         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
395         t::lib::Mocks::mock_preference( 'BorrowersLog',              1 );
396         my $expiry_date = $retrieved_patron->renew_account;
397         is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
398         my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
399         is( dt_from_string($retrieved_expiry_date), $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
400         my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
401         is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
402
403         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
404         t::lib::Mocks::mock_preference( 'BorrowersLog',              0 );
405         $expiry_date = $retrieved_patron->renew_account;
406         is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
407         $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
408         is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
409         $retrieved_expiry_date = $retrieved_patron->dateexpiry;
410         is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
411         $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
412         is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
413
414         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
415         $expiry_date = $retrieved_patron_2->renew_account;
416         is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
417         $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
418         is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
419
420         $expiry_date = $retrieved_patron_3->renew_account;
421         is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
422         $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
423         is( dt_from_string($retrieved_expiry_date), $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
424
425         $retrieved_patron->delete;
426         $retrieved_patron_2->delete;
427         $retrieved_patron_3->delete;
428     }
429     Time::Fake->reset;
430 };
431
432 subtest "move_to_deleted" => sub {
433     plan tests => 5;
434     my $originally_updated_on = '2016-01-01 12:12:12';
435     my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
436     my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
437     is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
438       ;    # FIXME This should be Koha::Deleted::Patron
439     my $deleted_patron = $schema->resultset('Deletedborrower')
440         ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
441         ->next;
442     ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
443     ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
444     isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
445     $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
446     is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
447     $retrieved_patron->delete( $patron->{borrowernumber} );    # Cleanup
448 };
449
450 subtest "delete" => sub {
451     plan tests => 6;
452     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
453     my $patron           = $builder->build( { source => 'Borrower' } );
454     my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
455     my $hold             = $builder->build(
456         {   source => 'Reserve',
457             value  => { borrowernumber => $patron->{borrowernumber} }
458         }
459     );
460     my $list = $builder->build(
461         {   source => 'Virtualshelve',
462             value  => { owner => $patron->{borrowernumber} }
463         }
464     );
465
466     my $deleted = $retrieved_patron->delete;
467     is( $deleted, 1, 'Koha::Patron->delete should return 1 if the patron has been correctly deleted' );
468
469     is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
470
471     is (Koha::Old::Holds->search( { reserve_id => $hold->{ reserve_id } } )->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| );
472
473     is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have cancelled patron's holds 2| );
474
475     is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
476
477     my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
478     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
479 };
480
481 subtest 'Koha::Patrons->delete' => sub {
482     plan tests => 4;
483
484     my $mod_patron = Test::MockModule->new( 'Koha::Patron' );
485     my $moved_to_deleted = 0;
486     $mod_patron->mock( 'move_to_deleted', sub { $moved_to_deleted++; } );
487
488     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
489     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
490     my $id1 = $patron1->borrowernumber;
491     my $set = Koha::Patrons->search({ borrowernumber => { '>=' => $id1 }});
492     is( $set->count, 2, 'Two patrons found as expected' );
493     is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
494     is( $moved_to_deleted, 2, 'Patrons moved to deletedborrowers' );
495
496     # Add again, test if we can raise an exception
497     $mod_patron->mock( 'delete', sub { return -1; } );
498     $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
499     $id1 = $patron1->borrowernumber;
500     $set = Koha::Patrons->search({ borrowernumber => { '>=' => $id1 }});
501     throws_ok { $set->delete } 'Koha::Exceptions::Patron::FailedDelete',
502         'Exception raised for deleting patron';
503 };
504
505 subtest 'add_enrolment_fee_if_needed' => sub {
506     plan tests => 4;
507
508     my $enrolmentfees = { K  => 5, J => 10, YA => 20 };
509     foreach( keys %{$enrolmentfees} ) {
510         ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
511     }
512     my $enrolmentfee_K  = $enrolmentfees->{K};
513     my $enrolmentfee_J  = $enrolmentfees->{J};
514     my $enrolmentfee_YA = $enrolmentfees->{YA};
515
516     my %borrower_data = (
517         firstname    => 'my firstname',
518         surname      => 'my surname',
519         categorycode => 'K',
520         branchcode   => $library->{branchcode},
521     );
522
523     my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
524     $borrower_data{borrowernumber} = $borrowernumber;
525
526     my $patron = Koha::Patrons->find( $borrowernumber );
527     my $total = $patron->account->balance;
528     is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
529
530     t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
531     $borrower_data{categorycode} = 'J';
532     $patron->set(\%borrower_data)->store;
533     $total = $patron->account->balance;
534     is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
535
536     $borrower_data{categorycode} = 'K';
537     $patron->set(\%borrower_data)->store;
538     t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
539
540     $borrower_data{categorycode} = 'J';
541     $patron->set(\%borrower_data)->store;
542     $total = $patron->account->balance;
543     is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
544
545     # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
546     $patron->categorycode('YA')->store;
547     $total = $patron->account->balance;
548     is( int($total),
549         int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
550         "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
551     );
552
553     $patron->delete;
554 };
555
556 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
557     plan tests => 17;
558
559     my $library = $builder->build( { source => 'Branch' } );
560     my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
561     my $item_1 = $builder->build(
562         {
563             source => 'Item',
564             value  => {
565                 homebranch    => $library->{branchcode},
566                 holdingbranch => $library->{branchcode},
567                 biblionumber  => $biblionumber_1,
568                 itemlost      => 0,
569                 withdrawn     => 0,
570             }
571         }
572     );
573     my $item_2 = $builder->build(
574         {
575             source => 'Item',
576             value  => {
577                 homebranch    => $library->{branchcode},
578                 holdingbranch => $library->{branchcode},
579                 biblionumber  => $biblionumber_1,
580                 itemlost      => 0,
581                 withdrawn     => 0,
582             }
583         }
584     );
585     my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
586     my $item_3 = $builder->build(
587         {
588             source => 'Item',
589             value  => {
590                 homebranch    => $library->{branchcode},
591                 holdingbranch => $library->{branchcode},
592                 biblionumber  => $biblionumber_2,
593                 itemlost      => 0,
594                 withdrawn     => 0,
595             }
596         }
597     );
598     my $patron = $builder->build(
599         {
600             source => 'Borrower',
601             value  => { branchcode => $library->{branchcode} }
602         }
603     );
604
605     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
606     my $checkouts = $patron->checkouts;
607     is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
608     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
609     my $pending_checkouts = $patron->pending_checkouts;
610     is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
611     is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
612     my $old_checkouts = $patron->old_checkouts;
613     is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
614     is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
615
616     # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
617     $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
618
619     t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
620
621     AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
622     AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
623     AddIssue( $patron, $item_3->{barcode} );
624
625     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
626     $checkouts = $patron->checkouts;
627     is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
628     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
629     $pending_checkouts = $patron->pending_checkouts;
630     is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
631     is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
632
633     my $first_checkout = $pending_checkouts->next;
634     is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
635
636     my $overdues = $patron->get_overdues;
637     is( $overdues->count, 2, 'Patron should have 2 overdues');
638     is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
639     is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
640     is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
641
642
643     C4::Circulation::AddReturn( $item_1->{barcode} );
644     C4::Circulation::AddReturn( $item_2->{barcode} );
645     $old_checkouts = $patron->old_checkouts;
646     is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
647     is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
648
649     # Clean stuffs
650     Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
651     $patron->delete;
652 };
653
654 subtest 'get_routing_lists' => sub {
655     plan tests => 5;
656
657     my $biblio = Koha::Biblio->new()->store();
658     my $subscription = Koha::Subscription->new({
659         biblionumber => $biblio->biblionumber,
660         }
661     )->store;
662
663     my $patron = $builder->build( { source => 'Borrower' } );
664     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
665
666     is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
667
668     my $routinglist_count = Koha::Subscription::Routinglists->count;
669     my $routinglist = Koha::Subscription::Routinglist->new({
670         borrowernumber   => $patron->borrowernumber,
671         ranking          => 5,
672         subscriptionid   => $subscription->subscriptionid
673     })->store;
674
675     is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
676
677     my $routinglists = $patron->get_routing_lists;
678     is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
679     is( ref($routinglists),   'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
680
681     my $subscription2 = Koha::Subscription->new({
682         biblionumber => $biblio->biblionumber,
683         }
684     )->store;
685     my $routinglist2 = Koha::Subscription::Routinglist->new({
686         borrowernumber   => $patron->borrowernumber,
687         ranking          => 1,
688         subscriptionid   => $subscription2->subscriptionid
689     })->store;
690
691     is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
692
693     $patron->delete; # Clean up for later tests
694
695 };
696
697 subtest 'get_age' => sub {
698     plan tests => 7;
699
700     my $patron = $builder->build( { source => 'Borrower' } );
701     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
702
703     my $today = dt_from_string;
704
705     $patron->dateofbirth( undef );
706     is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
707     $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1, end_of_month => 'limit'  ) );
708     is( $patron->get_age, 12, 'Patron should be 12' );
709     $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 1, end_of_month => 'limit'  ) );
710     is( $patron->get_age, 17, 'Patron should be 17, happy birthday tomorrow!' );
711     $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 0, end_of_month => 'limit'  ) );
712     is( $patron->get_age, 18, 'Patron should be 18' );
713     $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -31, end_of_month => 'limit'  ) );
714     is( $patron->get_age, 19, 'Patron should be 19' );
715     $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -30, end_of_month => 'limit'  ) );
716     is( $patron->get_age, 19, 'Patron should be 19 again' );
717     $patron->dateofbirth( $today->clone->add( years => 0,   months => -1, days => -1, end_of_month => 'limit'  ) );
718     is( $patron->get_age, 0, 'Patron is a newborn child' );
719
720     $patron->delete;
721 };
722
723 subtest 'is_valid_age' => sub {
724     plan tests => 10;
725
726     my $today = dt_from_string;
727
728     my $category = $builder->build({
729         source => 'Category',
730         value => {
731             categorycode        => 'AGE_5_10',
732             dateofbirthrequired => 5,
733             upperagelimit       => 10
734         }
735     });
736     $category = Koha::Patron::Categories->find( $category->{categorycode} );
737
738     my $patron = $builder->build({
739         source => 'Borrower',
740         value => {
741             categorycode        => 'AGE_5_10'
742         }
743     });
744     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
745
746
747     $patron->dateofbirth( undef );
748     is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
749
750     $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1 ) );
751     is( $patron->is_valid_age, 0, 'Patron is 12, so the age is above allowed range 5-10 years');
752
753     $patron->dateofbirth( $today->clone->add( years => -3, months => -6, days => -1 ) );
754     is( $patron->is_valid_age, 0, 'Patron is 3, so the age is below allowed range 5-10 years');
755
756     $patron->dateofbirth( $today->clone->add( years => -7, months => -6, days => -1 ) );
757     is( $patron->is_valid_age, 1, 'Patron is 7, so the age perfectly suits allowed range 5-10 years');
758
759     $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => 0 ) );
760     is( $patron->is_valid_age, 1, 'Patron celebrates the 5th birthday today, so the age is allowed for this category');
761
762     $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => 1 ) );
763     is( $patron->is_valid_age, 0, 'Patron will celebrate the 5th birthday tomorrow, so the age is NOT allowed for this category');
764
765     $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => -1 ) );
766     is( $patron->is_valid_age, 1, 'Patron celebrated the 5th birthday yesterday, so the age is allowed for this category');
767
768     $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => 0 ) );
769     is( $patron->is_valid_age, 0, 'Patron celebrate the 11th birthday today, so the age is NOT allowed for this category');
770
771     $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => 1 ) );
772     is( $patron->is_valid_age, 1, 'Patron will celebrate the 11th birthday tomorrow, so the age is allowed for this category');
773
774     $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => -1 ) );
775     is( $patron->is_valid_age, 0, 'Patron celebrated the 11th birthday yesterday, so the age is NOT allowed for this category');
776
777     $patron->delete;
778     $category->delete;
779 };
780
781 subtest 'account' => sub {
782     plan tests => 1;
783
784     my $patron = $builder->build({source => 'Borrower'});
785
786     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
787     my $account = $patron->account;
788     is( ref($account),   'Koha::Account', 'account should return a Koha::Account object' );
789
790     $patron->delete;
791 };
792
793 subtest 'search_upcoming_membership_expires' => sub {
794     plan tests => 9;
795
796     my $expiry_days = 15;
797     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
798     my $nb_of_days_before = 1;
799     my $nb_of_days_after = 2;
800
801     my $builder = t::lib::TestBuilder->new();
802
803     my $library = $builder->build({ source => 'Branch' });
804
805     # before we add borrowers to this branch, add the expires we have now
806     # note that this pertains to the current mocked setting of the pref
807     # for this reason we add the new branchcode to most of the tests
808     my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
809
810     my $patron_1 = $builder->build({
811         source => 'Borrower',
812         value  => {
813             branchcode              => $library->{branchcode},
814             dateexpiry              => dt_from_string->add( days => $expiry_days )
815         },
816     });
817
818     my $patron_2 = $builder->build({
819         source => 'Borrower',
820         value  => {
821             branchcode              => $library->{branchcode},
822             dateexpiry              => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
823         },
824     });
825
826     my $patron_3 = $builder->build({
827         source => 'Borrower',
828         value  => {
829             branchcode              => $library->{branchcode},
830             dateexpiry              => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
831         },
832     });
833
834     # Test without extra parameters
835     my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
836     is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
837
838     # Test with branch
839     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
840     is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
841     my $expired = $upcoming_mem_expires->next;
842     is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
843     is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
844     is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
845
846     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
847     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
848     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
849
850     # Test MembershipExpiryDaysNotice == undef
851     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
852     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
853     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
854
855     # Test the before parameter
856     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
857     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
858     is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
859     # Test after parameter also
860     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
861     is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
862     Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
863 };
864
865 subtest 'holds and old_holds' => sub {
866     plan tests => 6;
867
868     my $library = $builder->build( { source => 'Branch' } );
869     my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
870     my $item_1 = $builder->build(
871         {
872             source => 'Item',
873             value  => {
874                 homebranch    => $library->{branchcode},
875                 holdingbranch => $library->{branchcode},
876                 biblionumber  => $biblionumber_1
877             }
878         }
879     );
880     my $item_2 = $builder->build(
881         {
882             source => 'Item',
883             value  => {
884                 homebranch    => $library->{branchcode},
885                 holdingbranch => $library->{branchcode},
886                 biblionumber  => $biblionumber_1
887             }
888         }
889     );
890     my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
891     my $item_3 = $builder->build(
892         {
893             source => 'Item',
894             value  => {
895                 homebranch    => $library->{branchcode},
896                 holdingbranch => $library->{branchcode},
897                 biblionumber  => $biblionumber_2
898             }
899         }
900     );
901     my $patron = $builder->build(
902         {
903             source => 'Borrower',
904             value  => { branchcode => $library->{branchcode} }
905         }
906     );
907
908     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
909     my $holds = $patron->holds;
910     is( ref($holds), 'Koha::Holds',
911         'Koha::Patron->holds should return a Koha::Holds objects' );
912     is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
913
914     C4::Reserves::AddReserve( $library->{branchcode},
915         $patron->borrowernumber, $biblionumber_1 );
916     # In the future
917     C4::Reserves::AddReserve( $library->{branchcode},
918         $patron->borrowernumber, $biblionumber_2, undef, undef, dt_from_string->add( days => 2 ) );
919
920     $holds = $patron->holds;
921     is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
922
923     my $old_holds = $patron->old_holds;
924     is( ref($old_holds), 'Koha::Old::Holds',
925         'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
926     is( $old_holds->count, 0, 'There should not be any old holds yet');
927
928     my $hold = $holds->next;
929     $hold->cancel;
930
931     $old_holds = $patron->old_holds;
932     is( $old_holds->count, 1, 'There should  be 1 old (cancelled) hold');
933
934     $old_holds->delete;
935     $holds->delete;
936     $patron->delete;
937 };
938
939 subtest 'notice_email_address' => sub {
940     plan tests => 2;
941
942     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
943
944     t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
945     is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
946
947     t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
948     is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
949
950     $patron->delete;
951 };
952
953 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
954     plan tests => 4;
955
956     # TODO create a subroutine in t::lib::Mocks
957     my $branch = $builder->build({ source => 'Branch' });
958     my $userenv_patron = $builder->build_object({
959         class  => 'Koha::Patrons',
960         value  => { branchcode => $branch->{branchcode}, flags => 0 },
961     });
962     t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
963
964     my $anonymous = $builder->build( { source => 'Borrower', }, );
965
966     t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
967
968     subtest 'patron privacy is 1 (default)' => sub {
969         plan tests => 9;
970
971         t::lib::Mocks::mock_preference('IndependentBranches', 0);
972         my $patron = $builder->build(
973             {   source => 'Borrower',
974                 value  => { privacy => 1, }
975             }
976         );
977         my $item_1 = $builder->build(
978             {   source => 'Item',
979                 value  => {
980                     itemlost  => 0,
981                     withdrawn => 0,
982                 },
983             }
984         );
985         my $issue_1 = $builder->build(
986             {   source => 'Issue',
987                 value  => {
988                     borrowernumber => $patron->{borrowernumber},
989                     itemnumber     => $item_1->{itemnumber},
990                 },
991             }
992         );
993         my $item_2 = $builder->build(
994             {   source => 'Item',
995                 value  => {
996                     itemlost  => 0,
997                     withdrawn => 0,
998                 },
999             }
1000         );
1001         my $issue_2 = $builder->build(
1002             {   source => 'Issue',
1003                 value  => {
1004                     borrowernumber => $patron->{borrowernumber},
1005                     itemnumber     => $item_2->{itemnumber},
1006                 },
1007             }
1008         );
1009
1010         my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1011         my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, dt_from_string('2011-11-11') );
1012         is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
1013
1014         my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
1015         is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
1016
1017         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
1018         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1019
1020         $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1021         is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
1022
1023         my $dbh = C4::Context->dbh;
1024         my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
1025         $sth->execute($item_1->{itemnumber});
1026         my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1027         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
1028         $sth->execute($item_2->{itemnumber});
1029         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1030         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
1031
1032         $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
1033         $sth->execute($item_2->{itemnumber});
1034         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1035         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
1036
1037         my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
1038         $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
1039         $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
1040         $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
1041         $sth->execute($item_1->{itemnumber});
1042         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1043         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
1044         $sth->execute($item_2->{itemnumber});
1045         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1046         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
1047
1048         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1049     };
1050
1051     subtest 'patron privacy is 0 (forever)' => sub {
1052         plan tests => 2;
1053
1054         t::lib::Mocks::mock_preference('IndependentBranches', 0);
1055         my $patron = $builder->build(
1056             {   source => 'Borrower',
1057                 value  => { privacy => 0, }
1058             }
1059         );
1060         my $item = $builder->build(
1061             {   source => 'Item',
1062                 value  => {
1063                     itemlost  => 0,
1064                     withdrawn => 0,
1065                 },
1066             }
1067         );
1068         my $issue = $builder->build(
1069             {   source => 'Issue',
1070                 value  => {
1071                     borrowernumber => $patron->{borrowernumber},
1072                     itemnumber     => $item->{itemnumber},
1073                 },
1074             }
1075         );
1076
1077         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1078         is( $returned, 1, 'The item should have been returned' );
1079
1080         my $dbh = C4::Context->dbh;
1081         my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1082             SELECT borrowernumber FROM old_issues where itemnumber = ?
1083         |, undef, $item->{itemnumber});
1084         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1085         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1086     };
1087
1088     t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1089
1090     subtest 'AnonymousPatron is not defined' => sub {
1091         plan tests => 3;
1092
1093         t::lib::Mocks::mock_preference('IndependentBranches', 0);
1094         my $patron = $builder->build(
1095             {   source => 'Borrower',
1096                 value  => { privacy => 1, }
1097             }
1098         );
1099         my $item = $builder->build(
1100             {   source => 'Item',
1101                 value  => {
1102                     itemlost  => 0,
1103                     withdrawn => 0,
1104                 },
1105             }
1106         );
1107         my $issue = $builder->build(
1108             {   source => 'Issue',
1109                 value  => {
1110                     borrowernumber => $patron->{borrowernumber},
1111                     itemnumber     => $item->{itemnumber},
1112                 },
1113             }
1114         );
1115
1116         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1117         is( $returned, 1, 'The item should have been returned' );
1118         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
1119         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1120
1121         my $dbh = C4::Context->dbh;
1122         my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1123             SELECT borrowernumber FROM old_issues where itemnumber = ?
1124         |, undef, $item->{itemnumber});
1125         is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
1126         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1127     };
1128
1129     subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1130         plan tests => 1;
1131         t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1132         my $patron = $builder->build(
1133             {   source => 'Borrower',
1134                 value  => { privacy => 1 }    # Another branchcode than the logged in librarian
1135             }
1136         );
1137         my $item = $builder->build(
1138             {   source => 'Item',
1139                 value  => {
1140                     itemlost  => 0,
1141                     withdrawn => 0,
1142                 },
1143             }
1144         );
1145         my $issue = $builder->build(
1146             {   source => 'Issue',
1147                 value  => {
1148                     borrowernumber => $patron->{borrowernumber},
1149                     itemnumber     => $item->{itemnumber},
1150                 },
1151             }
1152         );
1153
1154         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1155         is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1156         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1157     };
1158
1159     Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1160     $userenv_patron->delete;
1161
1162     # Reset IndependentBranches for further tests
1163     t::lib::Mocks::mock_preference('IndependentBranches', 0);
1164 };
1165
1166 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1167     plan tests => 3;
1168
1169     # group1
1170     #   + library_11
1171     #   + library_12
1172     # group2
1173     #   + library21
1174     $nb_of_patrons = Koha::Patrons->search->count;
1175     my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1176     my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1177     my $library_11 = $builder->build( { source => 'Branch' } );
1178     my $library_12 = $builder->build( { source => 'Branch' } );
1179     my $library_21 = $builder->build( { source => 'Branch' } );
1180     $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1181     $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1182     $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1183     Koha::Library::Group->new(
1184         { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1185     Koha::Library::Group->new(
1186         { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1187     Koha::Library::Group->new(
1188         { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1189
1190     my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1191     # 2 patrons from library_11 (group1)
1192     # patron_11_1 see patron's infos from outside its group
1193     # Setting flags => undef to not be considered as superlibrarian
1194     my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1195     $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1196     $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1197     $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1198     # patron_11_2 can only see patron's info from its group
1199     my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1200     $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1201     $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1202     # 1 patron from library_12 (group1)
1203     my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1204     $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1205     # 1 patron from library_21 (group2) can only see patron's info from its group
1206     my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1207     $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1208     $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1209
1210     # Pfiou, we can start now!
1211     subtest 'libraries_where_can_see_patrons' => sub {
1212         plan tests => 3;
1213
1214         my @branchcodes;
1215
1216         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1217         @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1218         is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1219
1220         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1221         @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1222         is_deeply( \@branchcodes, [ sort ( $library_11->branchcode, $library_12->branchcode ) ], q|patron_11_2 has not view_borrower_infos_from_any_libraries => Can only see patron's from its group| );
1223
1224         t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1225         @branchcodes = $patron_21->libraries_where_can_see_patrons;
1226         is_deeply( \@branchcodes, [$library_21->branchcode], q|patron_21 has not view_borrower_infos_from_any_libraries => Can only see patron's from its group| );
1227     };
1228     subtest 'can_see_patron_infos' => sub {
1229         plan tests => 6;
1230
1231         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1232         is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1233         is( $patron_11_1->can_see_patron_infos( $patron_12 ),   1, q|patron_11_1 can see patron_12, from its group| );
1234         is( $patron_11_1->can_see_patron_infos( $patron_21 ),   1, q|patron_11_1 can see patron_11_2, from another group| );
1235
1236         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1237         is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1238         is( $patron_11_2->can_see_patron_infos( $patron_12 ),   1, q|patron_11_2 can see patron_12, from its group| );
1239         is( $patron_11_2->can_see_patron_infos( $patron_21 ),   0, q|patron_11_2 can NOT see patron_21, from another group| );
1240     };
1241     subtest 'search_limited' => sub {
1242         plan tests => 6;
1243
1244         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1245         my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1246         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1247         is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1248
1249         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1250         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1251         is( Koha::Patrons->search_limited->count, 3, 'patron_12_1 is not allowed to see patrons from other groups, only patron_11_1, patron_11_2 and patron_12' );
1252
1253         t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1254         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1255         is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1256     };
1257     $patron_11_1->delete;
1258     $patron_11_2->delete;
1259     $patron_12->delete;
1260     $patron_21->delete;
1261 };
1262
1263 subtest 'account_locked' => sub {
1264     plan tests => 13;
1265     my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1266     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1267     for my $value ( undef, '', 0 ) {
1268         t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1269         $patron->login_attempts(0)->store;
1270         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1271         $patron->login_attempts(1)->store;
1272         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1273         $patron->login_attempts(-1)->store;
1274         is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1275     }
1276
1277     t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1278     $patron->login_attempts(2)->store;
1279     is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1280     $patron->login_attempts(3)->store;
1281     is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1282     $patron->login_attempts(4)->store;
1283     is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1284     $patron->login_attempts(-1)->store;
1285     is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1286
1287     $patron->delete;
1288 };
1289
1290 subtest 'is_child | is_adult' => sub {
1291     plan tests => 8;
1292     my $category = $builder->build_object(
1293         {
1294             class => 'Koha::Patron::Categories',
1295             value => { category_type => 'A' }
1296         }
1297     );
1298     my $patron_adult = $builder->build_object(
1299         {
1300             class => 'Koha::Patrons',
1301             value => { categorycode => $category->categorycode }
1302         }
1303     );
1304     $category = $builder->build_object(
1305         {
1306             class => 'Koha::Patron::Categories',
1307             value => { category_type => 'I' }
1308         }
1309     );
1310     my $patron_adult_i = $builder->build_object(
1311         {
1312             class => 'Koha::Patrons',
1313             value => { categorycode => $category->categorycode }
1314         }
1315     );
1316     $category = $builder->build_object(
1317         {
1318             class => 'Koha::Patron::Categories',
1319             value => { category_type => 'C' }
1320         }
1321     );
1322     my $patron_child = $builder->build_object(
1323         {
1324             class => 'Koha::Patrons',
1325             value => { categorycode => $category->categorycode }
1326         }
1327     );
1328     $category = $builder->build_object(
1329         {
1330             class => 'Koha::Patron::Categories',
1331             value => { category_type => 'O' }
1332         }
1333     );
1334     my $patron_other = $builder->build_object(
1335         {
1336             class => 'Koha::Patrons',
1337             value => { categorycode => $category->categorycode }
1338         }
1339     );
1340     is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1341     is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1342     is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1343     is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1344
1345     is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1346     is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1347     is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1348     is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1349
1350     # Clean up
1351     $patron_adult->delete;
1352     $patron_adult_i->delete;
1353     $patron_child->delete;
1354     $patron_other->delete;
1355 };
1356
1357 subtest 'get_overdues' => sub {
1358     plan tests => 7;
1359
1360     my $library = $builder->build( { source => 'Branch' } );
1361     my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1362     my $item_1 = $builder->build(
1363         {
1364             source => 'Item',
1365             value  => {
1366                 homebranch    => $library->{branchcode},
1367                 holdingbranch => $library->{branchcode},
1368                 biblionumber  => $biblionumber_1
1369             }
1370         }
1371     );
1372     my $item_2 = $builder->build(
1373         {
1374             source => 'Item',
1375             value  => {
1376                 homebranch    => $library->{branchcode},
1377                 holdingbranch => $library->{branchcode},
1378                 biblionumber  => $biblionumber_1
1379             }
1380         }
1381     );
1382     my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1383     my $item_3 = $builder->build(
1384         {
1385             source => 'Item',
1386             value  => {
1387                 homebranch    => $library->{branchcode},
1388                 holdingbranch => $library->{branchcode},
1389                 biblionumber  => $biblionumber_2
1390             }
1391         }
1392     );
1393     my $patron = $builder->build(
1394         {
1395             source => 'Borrower',
1396             value  => { branchcode => $library->{branchcode} }
1397         }
1398     );
1399
1400     t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1401
1402     AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1403     AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1404     AddIssue( $patron, $item_3->{barcode} );
1405
1406     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1407     my $overdues = $patron->get_overdues;
1408     is( $overdues->count, 2, 'Patron should have 2 overdues');
1409     is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1410     is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1411
1412     my $o = $overdues->reset->next;
1413     my $unblessed_overdue = $o->unblessed_all_relateds;
1414     is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1415     is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1416     is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1417     is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1418
1419     # Clean stuffs
1420     $patron->checkouts->delete;
1421     $patron->delete;
1422 };
1423
1424 subtest 'userid_is_valid' => sub {
1425     plan tests => 9;
1426
1427     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1428     my $patron_category = $builder->build_object(
1429         {
1430             class => 'Koha::Patron::Categories',
1431             value => { category_type => 'P', enrolmentfee => 0 }
1432         }
1433     );
1434     my %data = (
1435         cardnumber   => "123456789",
1436         firstname    => "Tomasito",
1437         surname      => "None",
1438         categorycode => $patron_category->categorycode,
1439         branchcode   => $library->branchcode,
1440     );
1441
1442     my $expected_userid_patron_1 = 'tomasito.none';
1443     my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1444     my $patron_1       = Koha::Patrons->find($borrowernumber);
1445     is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1446     is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1447
1448     $patron_1->userid( 'tomasito.non' );
1449     is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1450         1, 'recently created userid -> unique (borrowernumber passed)' );
1451
1452     $patron_1->userid( 'tomasitoxxx' );
1453     is( $patron_1->has_valid_userid,
1454         1, 'non-existent userid -> unique (borrowernumber passed)' );
1455     $patron_1->discard_changes; # We compare with the original userid later
1456
1457     my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1458     is( $patron_not_in_storage->has_valid_userid,
1459         0, 'userid exists for another patron, patron is not in storage yet' );
1460
1461     $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1462     is( $patron_not_in_storage->has_valid_userid,
1463         1, 'non-existent userid, patron is not in storage yet' );
1464
1465     # Regression tests for BZ12226
1466     my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1467     is( $db_patron->has_valid_userid,
1468         0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1469
1470     # Add a new borrower with the same userid but different cardnumber
1471     $data{cardnumber} = "987654321";
1472     my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1473     my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1474     $patron_2->userid($patron_1->userid);
1475     is( $patron_2->has_valid_userid,
1476         0, 'The userid is already in used, it cannot be used for another patron' );
1477
1478     my $new_userid = 'a_user_id';
1479     $data{cardnumber} = "234567890";
1480     $data{userid}     = 'a_user_id';
1481     $borrowernumber   = Koha::Patron->new(\%data)->store->borrowernumber;
1482     my $patron_3 = Koha::Patrons->find($borrowernumber);
1483     is( $patron_3->userid, $new_userid,
1484         'Koha::Patron->store should insert the given userid' );
1485
1486     # Cleanup
1487     $patron_1->delete;
1488     $patron_2->delete;
1489     $patron_3->delete;
1490 };
1491
1492 subtest 'generate_userid' => sub {
1493     plan tests => 7;
1494
1495     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1496     my $patron_category = $builder->build_object(
1497         {
1498             class => 'Koha::Patron::Categories',
1499             value => { category_type => 'P', enrolmentfee => 0 }
1500         }
1501     );
1502     my %data = (
1503         cardnumber   => "123456789",
1504         firstname    => "Tomasito",
1505         surname      => "None",
1506         categorycode => $patron_category->categorycode,
1507         branchcode   => $library->branchcode,
1508     );
1509
1510     my $expected_userid_patron_1 = 'tomasito.none';
1511     my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1512     $new_patron->generate_userid;
1513     my $userid = $new_patron->userid;
1514     is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1515     my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1516     my $patron_1 = Koha::Patrons->find($borrowernumber);
1517     is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1518
1519     $new_patron->generate_userid;
1520     $userid = $new_patron->userid;
1521     is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1522     $data{cardnumber} = '987654321';
1523     my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1524     my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1525     isnt( $patron_2->userid, 'tomasito',
1526         "Patron with duplicate userid has new userid generated" );
1527     is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1528         "Patron with duplicate userid has new userid generated (1 is appened" );
1529
1530     $new_patron->generate_userid;
1531     $userid = $new_patron->userid;
1532     is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1533
1534     $patron_1 = Koha::Patrons->find($borrowernumber);
1535     $patron_1->userid(undef);
1536     $patron_1->generate_userid;
1537     $userid = $patron_1->userid;
1538     is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1539
1540     # Cleanup
1541     $patron_1->delete;
1542     $patron_2->delete;
1543 };
1544
1545 subtest 'attributes' => sub {
1546     plan tests => 2;
1547
1548     my $library1 = Koha::Library->new({
1549         branchcode => 'LIBPATRON',
1550         branchname => 'Library of testing patron',
1551     })->store;
1552
1553     my $library2 = Koha::Library->new({
1554         branchcode => 'LIBATTR',
1555         branchname => 'Library for testing attribute',
1556     })->store;
1557
1558     my $category = Koha::Patron::Category->new({
1559         categorycode => 'CAT1',
1560         description => 'Category 1',
1561     })->store;
1562
1563     my $patron = Koha::Patron->new({
1564         firstname => 'Patron',
1565         surname => 'with attributes',
1566         branchcode => 'LIBPATRON',
1567         categorycode => 'CAT1',
1568     })->store;
1569
1570     my $attribute_type1 = Koha::Patron::Attribute::Type->new({
1571         code => 'CODE_A',
1572         description => 'Code A desciption',
1573     })->store;
1574
1575     my $attribute_type2 = Koha::Patron::Attribute::Type->new({
1576         code => 'CODE_B',
1577         description => 'Code A desciption',
1578     })->store;
1579
1580     $attribute_type2->library_limits ( [ $library2->branchcode ] );
1581
1582     Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type1->code, attribute => 'value 1' } )->store();
1583     Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type2->code, attribute => 'value 2' } )->store();
1584
1585     is( $patron->attributes->count, 1, 'There should be one attribute');
1586
1587     $attribute_type2->library_limits ( [ $library1->branchcode ] );
1588
1589     is( $patron->attributes->count, 2, 'There should be 2 attributes');
1590
1591     $patron->delete;
1592 };
1593
1594 $nb_of_patrons = Koha::Patrons->search->count;
1595 $retrieved_patron_1->delete;
1596 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1597
1598 subtest 'BorrowersLog tests' => sub {
1599     plan tests => 4;
1600
1601     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1602     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1603
1604     my $cardnumber = $patron->cardnumber;
1605     $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1606     $patron->store;
1607
1608     my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1609     my $log_info = from_json( $logs[0]->info );
1610     is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1611     is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1612     is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1613
1614     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1615     $patron->track_login();
1616     @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1617     is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1618 };
1619
1620 $schema->storage->txn_rollback;
1621
1622 subtest 'Test Koha::Patrons::merge' => sub {
1623     plan tests => 110;
1624
1625     my $schema = Koha::Database->new()->schema();
1626
1627     my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1628
1629     $schema->storage->txn_begin;
1630
1631     my $keeper  = $builder->build_object({ class => 'Koha::Patrons' });
1632     my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1633     my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1634
1635     while (my ($r, $field) = each(%$resultsets)) {
1636         $builder->build({ source => $r, value => { $field => $keeper->id } });
1637         $builder->build({ source => $r, value => { $field => $loser_1 } });
1638         $builder->build({ source => $r, value => { $field => $loser_2 } });
1639
1640         my $keeper_rs =
1641           $schema->resultset($r)->search( { $field => $keeper->id } );
1642         is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1643
1644         my $loser_1_rs =
1645           $schema->resultset($r)->search( { $field => $loser_1 } );
1646         is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1647
1648         my $loser_2_rs =
1649           $schema->resultset($r)->search( { $field => $loser_2 } );
1650         is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1651     }
1652
1653     my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1654
1655     while (my ($r, $field) = each(%$resultsets)) {
1656         my $keeper_rs =
1657           $schema->resultset($r)->search( {$field => $keeper->id } );
1658         is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1659     }
1660
1661     is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1662     is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1663
1664     $schema->storage->txn_rollback;
1665 };
1666
1667 subtest '->store' => sub {
1668     plan tests => 6;
1669     my $schema = Koha::Database->new->schema;
1670     $schema->storage->txn_begin;
1671
1672     my $print_error = $schema->storage->dbh->{PrintError};
1673     $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1674
1675     my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1676     my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1677
1678     throws_ok
1679         { $patron_2->userid($patron_1->userid)->store; }
1680         'Koha::Exceptions::Object::DuplicateID',
1681         'Koha::Patron->store raises an exception on duplicate ID';
1682
1683     # Test password
1684     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1685     my $password = 'password';
1686     $patron_1->set_password({ password => $password });
1687     like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1688     my $digest = $patron_1->password;
1689     $patron_1->surname('xxx')->store;
1690     is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1691
1692     # Test uppercasesurname
1693     t::lib::Mocks::mock_preference( 'uppercasesurname', 1 );
1694     my $surname = lc $patron_1->surname;
1695     $patron_1->surname($surname)->store;
1696     isnt( $patron_1->surname, $surname,
1697         'Surname converts to uppercase on store.');
1698     t::lib::Mocks::mock_preference( 'uppercasesurname', 0 );
1699     $patron_1->surname($surname)->store;
1700     is( $patron_1->surname, $surname,
1701         'Surname remains unchanged on store.');
1702
1703     $schema->storage->dbh->{PrintError} = $print_error;
1704     $schema->storage->txn_rollback;
1705
1706     subtest 'skip updated_on for BorrowersLog' => sub {
1707         plan tests => 1;
1708         $schema->storage->txn_begin;
1709         t::lib::Mocks::mock_preference('BorrowersLog', 1);
1710         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1711         $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1712         my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1713         is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1714         $schema->storage->txn_rollback;
1715     };
1716 };
1717
1718 subtest '->set_password' => sub {
1719
1720     plan tests => 14;
1721
1722     $schema->storage->txn_begin;
1723
1724     my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1725
1726     # Disable logging password changes for this tests
1727     t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1728
1729     # Password-length tests
1730     t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1731     throws_ok { $patron->set_password({ password => 'ab' }); }
1732         'Koha::Exceptions::Password::TooShort',
1733         'minPasswordLength is undef, fall back to 3, fail test';
1734     is( "$@",
1735         'Password length (2) is shorter than required (3)',
1736         'Exception parameters passed correctly'
1737     );
1738
1739     t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1740     throws_ok { $patron->set_password({ password => 'ab' }); }
1741         'Koha::Exceptions::Password::TooShort',
1742         'minPasswordLength is 2, fall back to 3, fail test';
1743
1744     t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1745     throws_ok { $patron->set_password({ password => 'abcb' }); }
1746         'Koha::Exceptions::Password::TooShort',
1747         'minPasswordLength is 5, fail test';
1748
1749     # Trailing spaces tests
1750     throws_ok { $patron->set_password({ password => 'abcD12d   ' }); }
1751         'Koha::Exceptions::Password::WhitespaceCharacters',
1752         'Password contains trailing spaces, exception is thrown';
1753
1754     # Require strong password tests
1755     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1756     throws_ok { $patron->set_password({ password => 'abcd   a' }); }
1757         'Koha::Exceptions::Password::TooWeak',
1758         'Password is too weak, exception is thrown';
1759
1760     # Refresh patron from DB, just to make sure
1761     $patron->discard_changes;
1762     is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1763
1764     $patron->set_password({ password => 'abcD12 34' });
1765     $patron->discard_changes;
1766
1767     is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1768
1769     lives_ok { $patron->set_password({ password => 'abcd   a', skip_validation => 1 }) }
1770         'Password is weak, but skip_validation was passed, so no exception thrown';
1771
1772     # Completeness
1773     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1774     $patron->login_attempts(3)->store;
1775     my $old_digest = $patron->password;
1776     $patron->set_password({ password => 'abcd   a' });
1777     $patron->discard_changes;
1778
1779     isnt( $patron->password, $old_digest, 'Password has been updated' );
1780     ok( checkpw_hash('abcd   a', $patron->password), 'Password hash is correct' );
1781     is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1782
1783     my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1784     is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1785
1786     # Enable logging password changes
1787     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1788     $patron->set_password({ password => 'abcd   b' });
1789
1790     $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1791     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1792
1793     $schema->storage->txn_rollback;
1794 };
1795
1796 $schema->storage->txn_begin;
1797 subtest 'search_unsubscribed' => sub {
1798     plan tests => 4;
1799
1800     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1801     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
1802     is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
1803
1804     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1805     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1806
1807     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
1808     Koha::Patron::Consents->delete; # for correct counts
1809     Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING',  refused_on => dt_from_string })->store;
1810     is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
1811
1812     # Add another refusal but shift the period
1813     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
1814     Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING',  refused_on => dt_from_string->subtract(days=>2) })->store;
1815     is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
1816
1817     # Try another (special) attempts setting
1818     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
1819     # Lockout is now disabled
1820     # Patron2 still matches: refused earlier, not locked
1821     is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
1822 };
1823
1824 subtest 'search_anonymize_candidates' => sub {
1825     plan tests => 5;
1826     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1827     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1828     $patron1->anonymized(0);
1829     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1830     $patron2->anonymized(0);
1831     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1832
1833     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
1834     is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
1835
1836     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
1837     my $cnt = Koha::Patrons->search_anonymize_candidates->count;
1838     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1839     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1840     is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
1841
1842     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
1843     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1844     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1845     $cnt = Koha::Patrons->search_anonymize_candidates->count;
1846     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1847     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1848     is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
1849
1850     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
1851     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1852     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1853     $cnt = Koha::Patrons->search_anonymize_candidates->count;
1854     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1855     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1856     is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
1857
1858     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1859     $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1860     $patron1->login_attempts(0)->store;
1861     $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1862     $patron2->login_attempts(0)->store;
1863     $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
1864     $patron1->login_attempts(3)->store;
1865     is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1866         $cnt+1, 'Locked flag' );
1867 };
1868
1869 subtest 'search_anonymized' => sub {
1870     plan tests => 3;
1871     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1872
1873     t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
1874     is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
1875
1876     t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
1877     $patron1->dateexpiry( dt_from_string );
1878     $patron1->anonymized(0)->store;
1879     my $cnt = Koha::Patrons->search_anonymized->count;
1880     $patron1->anonymized(1)->store;
1881     is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
1882     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1883     is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
1884 };
1885
1886 subtest 'lock' => sub {
1887     plan tests => 8;
1888
1889     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1890     my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1891     my $hold = $builder->build_object({
1892         class => 'Koha::Holds',
1893         value => { borrowernumber => $patron1->borrowernumber },
1894     });
1895
1896     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1897     my $expiry = dt_from_string->add(days => 1);
1898     $patron1->dateexpiry( $expiry );
1899     $patron1->lock;
1900     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1901     is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
1902     is( $patron1->holds->count, 1, 'No holds removed' );
1903
1904     $patron1->lock({ expire => 1, remove => 1});
1905     isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
1906     is( $patron1->holds->count, 0, 'Holds removed' );
1907
1908     # Disable lockout feature
1909     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1910     $patron1->login_attempts(0);
1911     $patron1->dateexpiry( $expiry );
1912     $patron1->store;
1913     $patron1->lock;
1914     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1915
1916     # Trivial wrapper test (Koha::Patrons->lock)
1917     $patron1->login_attempts(0)->store;
1918     Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
1919     $patron1->discard_changes; # refresh
1920     $patron2->discard_changes;
1921     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
1922     is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
1923 };
1924
1925 subtest 'anonymize' => sub {
1926     plan tests => 10;
1927
1928     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1929     my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1930
1931     # First try patron with issues
1932     my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
1933     warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
1934     $issue->delete;
1935
1936     t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
1937     my $surname = $patron1->surname; # expect change, no clear
1938     my $branchcode = $patron1->branchcode; # expect skip
1939     $patron1->anonymize;
1940     is($patron1->anonymized, 1, 'Check flag' );
1941
1942     is( $patron1->dateofbirth, undef, 'Birth date cleared' );
1943     is( $patron1->firstname, undef, 'First name cleared' );
1944     isnt( $patron1->surname, $surname, 'Surname changed' );
1945     ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
1946     is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
1947     is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
1948
1949     # Test wrapper in Koha::Patrons
1950     $patron1->surname($surname)->store; # restore
1951     my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
1952     $patron1->discard_changes; # refresh
1953     isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
1954     $patron2->discard_changes; # refresh
1955     is( $patron2->firstname, undef, 'First name patron2 cleared' );
1956 };
1957 $schema->storage->txn_rollback;