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