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