Bug 23199: Added tests for Koha::Patron
[koha.git] / t / db_dependent / Koha / Patrons.t
1 #!/usr/bin/perl
2
3 # Copyright 2015 Koha Development team
4 #
5 # This file is part of Koha
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use Test::More tests => 40;
23 use Test::Warn;
24 use Test::Exception;
25 use Test::MockModule;
26 use Time::Fake;
27 use DateTime;
28 use JSON;
29
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 'is_valid_age' => sub {
643     plan tests => 10;
644
645     my $today = dt_from_string;
646
647     my $category = $builder->build({
648         source => 'Category',
649         value => {
650             categorycode        => 'AGE_5_10',
651             dateofbirthrequired => 5,
652             upperagelimit       => 10
653         }
654     });
655     $category = Koha::Patron::Categories->find( $category->{categorycode} );
656
657     my $patron = $builder->build({
658         source => 'Borrower',
659         value => {
660             categorycode        => 'AGE_5_10'
661         }
662     });
663     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
664
665
666     $patron->dateofbirth( undef );
667     is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
668
669     $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1 ) );
670     is( $patron->is_valid_age, 0, 'Patron is 12, so the age is above allowed range 5-10 years');
671
672     $patron->dateofbirth( $today->clone->add( years => -3, months => -6, days => -1 ) );
673     is( $patron->is_valid_age, 0, 'Patron is 3, so the age is below allowed range 5-10 years');
674
675     $patron->dateofbirth( $today->clone->add( years => -7, months => -6, days => -1 ) );
676     is( $patron->is_valid_age, 1, 'Patron is 7, so the age perfectly suits allowed range 5-10 years');
677
678     $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => 0 ) );
679     is( $patron->is_valid_age, 1, 'Patron celebrates the 5th birthday today, so the age is allowed for this category');
680
681     $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => 1 ) );
682     is( $patron->is_valid_age, 0, 'Patron will celebrate the 5th birthday tomorrow, so the age is NOT allowed for this category');
683
684     $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => -1 ) );
685     is( $patron->is_valid_age, 1, 'Patron celebrated the 5th birthday yesterday, so the age is allowed for this category');
686
687     $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => 0 ) );
688     is( $patron->is_valid_age, 0, 'Patron celebrate the 11th birthday today, so the age is NOT allowed for this category');
689
690     $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => 1 ) );
691     is( $patron->is_valid_age, 1, 'Patron will celebrate the 11th birthday tomorrow, so the age is allowed for this category');
692
693     $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => -1 ) );
694     is( $patron->is_valid_age, 0, 'Patron celebrated the 11th birthday yesterday, so the age is NOT allowed for this category');
695
696     $patron->delete;
697     $category->delete;
698 };
699
700 subtest 'account' => sub {
701     plan tests => 1;
702
703     my $patron = $builder->build({source => 'Borrower'});
704
705     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
706     my $account = $patron->account;
707     is( ref($account),   'Koha::Account', 'account should return a Koha::Account object' );
708
709     $patron->delete;
710 };
711
712 subtest 'search_upcoming_membership_expires' => sub {
713     plan tests => 9;
714
715     my $expiry_days = 15;
716     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
717     my $nb_of_days_before = 1;
718     my $nb_of_days_after = 2;
719
720     my $builder = t::lib::TestBuilder->new();
721
722     my $library = $builder->build({ source => 'Branch' });
723
724     # before we add borrowers to this branch, add the expires we have now
725     # note that this pertains to the current mocked setting of the pref
726     # for this reason we add the new branchcode to most of the tests
727     my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
728
729     my $patron_1 = $builder->build({
730         source => 'Borrower',
731         value  => {
732             branchcode              => $library->{branchcode},
733             dateexpiry              => dt_from_string->add( days => $expiry_days )
734         },
735     });
736
737     my $patron_2 = $builder->build({
738         source => 'Borrower',
739         value  => {
740             branchcode              => $library->{branchcode},
741             dateexpiry              => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
742         },
743     });
744
745     my $patron_3 = $builder->build({
746         source => 'Borrower',
747         value  => {
748             branchcode              => $library->{branchcode},
749             dateexpiry              => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
750         },
751     });
752
753     # Test without extra parameters
754     my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
755     is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
756
757     # Test with branch
758     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
759     is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
760     my $expired = $upcoming_mem_expires->next;
761     is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
762     is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
763     is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
764
765     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
766     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
767     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
768
769     # Test MembershipExpiryDaysNotice == undef
770     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
771     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
772     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
773
774     # Test the before parameter
775     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
776     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
777     is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
778     # Test after parameter also
779     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
780     is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
781     Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
782 };
783
784 subtest 'holds and old_holds' => sub {
785     plan tests => 6;
786
787     my $library = $builder->build( { source => 'Branch' } );
788     my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
789     my $item_1 = $builder->build(
790         {
791             source => 'Item',
792             value  => {
793                 homebranch    => $library->{branchcode},
794                 holdingbranch => $library->{branchcode},
795                 biblionumber  => $biblionumber_1
796             }
797         }
798     );
799     my $item_2 = $builder->build(
800         {
801             source => 'Item',
802             value  => {
803                 homebranch    => $library->{branchcode},
804                 holdingbranch => $library->{branchcode},
805                 biblionumber  => $biblionumber_1
806             }
807         }
808     );
809     my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
810     my $item_3 = $builder->build(
811         {
812             source => 'Item',
813             value  => {
814                 homebranch    => $library->{branchcode},
815                 holdingbranch => $library->{branchcode},
816                 biblionumber  => $biblionumber_2
817             }
818         }
819     );
820     my $patron = $builder->build(
821         {
822             source => 'Borrower',
823             value  => { branchcode => $library->{branchcode} }
824         }
825     );
826
827     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
828     my $holds = $patron->holds;
829     is( ref($holds), 'Koha::Holds',
830         'Koha::Patron->holds should return a Koha::Holds objects' );
831     is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
832
833     C4::Reserves::AddReserve( $library->{branchcode},
834         $patron->borrowernumber, $biblionumber_1 );
835     # In the future
836     C4::Reserves::AddReserve( $library->{branchcode},
837         $patron->borrowernumber, $biblionumber_2, undef, undef, dt_from_string->add( days => 2 ) );
838
839     $holds = $patron->holds;
840     is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
841
842     my $old_holds = $patron->old_holds;
843     is( ref($old_holds), 'Koha::Old::Holds',
844         'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
845     is( $old_holds->count, 0, 'There should not be any old holds yet');
846
847     my $hold = $holds->next;
848     $hold->cancel;
849
850     $old_holds = $patron->old_holds;
851     is( $old_holds->count, 1, 'There should  be 1 old (cancelled) hold');
852
853     $old_holds->delete;
854     $holds->delete;
855     $patron->delete;
856 };
857
858 subtest 'notice_email_address' => sub {
859     plan tests => 2;
860
861     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
862
863     t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
864     is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
865
866     t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
867     is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
868
869     $patron->delete;
870 };
871
872 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
873     plan tests => 4;
874
875     # TODO create a subroutine in t::lib::Mocks
876     my $branch = $builder->build({ source => 'Branch' });
877     my $userenv_patron = $builder->build_object({
878         class  => 'Koha::Patrons',
879         value  => { branchcode => $branch->{branchcode}, flags => 0 },
880     });
881     t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
882
883     my $anonymous = $builder->build( { source => 'Borrower', }, );
884
885     t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
886
887     subtest 'patron privacy is 1 (default)' => sub {
888         plan tests => 9;
889
890         t::lib::Mocks::mock_preference('IndependentBranches', 0);
891         my $patron = $builder->build(
892             {   source => 'Borrower',
893                 value  => { privacy => 1, }
894             }
895         );
896         my $item_1 = $builder->build(
897             {   source => 'Item',
898                 value  => {
899                     itemlost  => 0,
900                     withdrawn => 0,
901                 },
902             }
903         );
904         my $issue_1 = $builder->build(
905             {   source => 'Issue',
906                 value  => {
907                     borrowernumber => $patron->{borrowernumber},
908                     itemnumber     => $item_1->{itemnumber},
909                 },
910             }
911         );
912         my $item_2 = $builder->build(
913             {   source => 'Item',
914                 value  => {
915                     itemlost  => 0,
916                     withdrawn => 0,
917                 },
918             }
919         );
920         my $issue_2 = $builder->build(
921             {   source => 'Issue',
922                 value  => {
923                     borrowernumber => $patron->{borrowernumber},
924                     itemnumber     => $item_2->{itemnumber},
925                 },
926             }
927         );
928
929         my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, dt_from_string('2010-10-10') );
930         my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, dt_from_string('2011-11-11') );
931         is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
932
933         my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
934         is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
935
936         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
937         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
938
939         $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
940         is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
941
942         my $dbh = C4::Context->dbh;
943         my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
944         $sth->execute($item_1->{itemnumber});
945         my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
946         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
947         $sth->execute($item_2->{itemnumber});
948         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
949         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
950
951         $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
952         $sth->execute($item_2->{itemnumber});
953         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
954         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
955
956         my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
957         $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
958         $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
959         $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
960         $sth->execute($item_1->{itemnumber});
961         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
962         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
963         $sth->execute($item_2->{itemnumber});
964         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
965         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
966
967         Koha::Patrons->find( $patron->{borrowernumber})->delete;
968     };
969
970     subtest 'patron privacy is 0 (forever)' => sub {
971         plan tests => 2;
972
973         t::lib::Mocks::mock_preference('IndependentBranches', 0);
974         my $patron = $builder->build(
975             {   source => 'Borrower',
976                 value  => { privacy => 0, }
977             }
978         );
979         my $item = $builder->build(
980             {   source => 'Item',
981                 value  => {
982                     itemlost  => 0,
983                     withdrawn => 0,
984                 },
985             }
986         );
987         my $issue = $builder->build(
988             {   source => 'Issue',
989                 value  => {
990                     borrowernumber => $patron->{borrowernumber},
991                     itemnumber     => $item->{itemnumber},
992                 },
993             }
994         );
995
996         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
997         is( $returned, 1, 'The item should have been returned' );
998
999         my $dbh = C4::Context->dbh;
1000         my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1001             SELECT borrowernumber FROM old_issues where itemnumber = ?
1002         |, undef, $item->{itemnumber});
1003         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1004         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1005     };
1006
1007     t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1008
1009     subtest 'AnonymousPatron is not defined' => sub {
1010         plan tests => 3;
1011
1012         t::lib::Mocks::mock_preference('IndependentBranches', 0);
1013         my $patron = $builder->build(
1014             {   source => 'Borrower',
1015                 value  => { privacy => 1, }
1016             }
1017         );
1018         my $item = $builder->build(
1019             {   source => 'Item',
1020                 value  => {
1021                     itemlost  => 0,
1022                     withdrawn => 0,
1023                 },
1024             }
1025         );
1026         my $issue = $builder->build(
1027             {   source => 'Issue',
1028                 value  => {
1029                     borrowernumber => $patron->{borrowernumber},
1030                     itemnumber     => $item->{itemnumber},
1031                 },
1032             }
1033         );
1034
1035         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1036         is( $returned, 1, 'The item should have been returned' );
1037         my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
1038         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1039
1040         my $dbh = C4::Context->dbh;
1041         my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1042             SELECT borrowernumber FROM old_issues where itemnumber = ?
1043         |, undef, $item->{itemnumber});
1044         is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
1045         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1046     };
1047
1048     subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1049         plan tests => 1;
1050         t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1051         my $patron = $builder->build(
1052             {   source => 'Borrower',
1053                 value  => { privacy => 1 }    # Another branchcode than the logged in librarian
1054             }
1055         );
1056         my $item = $builder->build(
1057             {   source => 'Item',
1058                 value  => {
1059                     itemlost  => 0,
1060                     withdrawn => 0,
1061                 },
1062             }
1063         );
1064         my $issue = $builder->build(
1065             {   source => 'Issue',
1066                 value  => {
1067                     borrowernumber => $patron->{borrowernumber},
1068                     itemnumber     => $item->{itemnumber},
1069                 },
1070             }
1071         );
1072
1073         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1074         is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1075         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1076     };
1077
1078     Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1079     $userenv_patron->delete;
1080
1081     # Reset IndependentBranches for further tests
1082     t::lib::Mocks::mock_preference('IndependentBranches', 0);
1083 };
1084
1085 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1086     plan tests => 3;
1087
1088     # group1
1089     #   + library_11
1090     #   + library_12
1091     # group2
1092     #   + library21
1093     $nb_of_patrons = Koha::Patrons->search->count;
1094     my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1095     my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1096     my $library_11 = $builder->build( { source => 'Branch' } );
1097     my $library_12 = $builder->build( { source => 'Branch' } );
1098     my $library_21 = $builder->build( { source => 'Branch' } );
1099     $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1100     $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1101     $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1102     Koha::Library::Group->new(
1103         { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1104     Koha::Library::Group->new(
1105         { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1106     Koha::Library::Group->new(
1107         { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1108
1109     my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1110     # 2 patrons from library_11 (group1)
1111     # patron_11_1 see patron's infos from outside its group
1112     # Setting flags => undef to not be considered as superlibrarian
1113     my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1114     $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1115     $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1116     $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1117     # patron_11_2 can only see patron's info from its group
1118     my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1119     $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1120     $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1121     # 1 patron from library_12 (group1)
1122     my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1123     $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1124     # 1 patron from library_21 (group2) can only see patron's info from its group
1125     my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1126     $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1127     $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1128
1129     # Pfiou, we can start now!
1130     subtest 'libraries_where_can_see_patrons' => sub {
1131         plan tests => 3;
1132
1133         my @branchcodes;
1134
1135         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1136         @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1137         is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1138
1139         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1140         @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1141         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| );
1142
1143         t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1144         @branchcodes = $patron_21->libraries_where_can_see_patrons;
1145         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| );
1146     };
1147     subtest 'can_see_patron_infos' => sub {
1148         plan tests => 6;
1149
1150         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1151         is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1152         is( $patron_11_1->can_see_patron_infos( $patron_12 ),   1, q|patron_11_1 can see patron_12, from its group| );
1153         is( $patron_11_1->can_see_patron_infos( $patron_21 ),   1, q|patron_11_1 can see patron_11_2, from another group| );
1154
1155         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1156         is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1157         is( $patron_11_2->can_see_patron_infos( $patron_12 ),   1, q|patron_11_2 can see patron_12, from its group| );
1158         is( $patron_11_2->can_see_patron_infos( $patron_21 ),   0, q|patron_11_2 can NOT see patron_21, from another group| );
1159     };
1160     subtest 'search_limited' => sub {
1161         plan tests => 6;
1162
1163         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1164         my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1165         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1166         is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1167
1168         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1169         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1170         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' );
1171
1172         t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1173         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1174         is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1175     };
1176     $patron_11_1->delete;
1177     $patron_11_2->delete;
1178     $patron_12->delete;
1179     $patron_21->delete;
1180 };
1181
1182 subtest 'account_locked' => sub {
1183     plan tests => 13;
1184     my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1185     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1186     for my $value ( undef, '', 0 ) {
1187         t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1188         $patron->login_attempts(0)->store;
1189         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1190         $patron->login_attempts(1)->store;
1191         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1192         $patron->login_attempts(-1)->store;
1193         is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1194     }
1195
1196     t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1197     $patron->login_attempts(2)->store;
1198     is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1199     $patron->login_attempts(3)->store;
1200     is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1201     $patron->login_attempts(4)->store;
1202     is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1203     $patron->login_attempts(-1)->store;
1204     is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1205
1206     $patron->delete;
1207 };
1208
1209 subtest 'is_child | is_adult' => sub {
1210     plan tests => 8;
1211     my $category = $builder->build_object(
1212         {
1213             class => 'Koha::Patron::Categories',
1214             value => { category_type => 'A' }
1215         }
1216     );
1217     my $patron_adult = $builder->build_object(
1218         {
1219             class => 'Koha::Patrons',
1220             value => { categorycode => $category->categorycode }
1221         }
1222     );
1223     $category = $builder->build_object(
1224         {
1225             class => 'Koha::Patron::Categories',
1226             value => { category_type => 'I' }
1227         }
1228     );
1229     my $patron_adult_i = $builder->build_object(
1230         {
1231             class => 'Koha::Patrons',
1232             value => { categorycode => $category->categorycode }
1233         }
1234     );
1235     $category = $builder->build_object(
1236         {
1237             class => 'Koha::Patron::Categories',
1238             value => { category_type => 'C' }
1239         }
1240     );
1241     my $patron_child = $builder->build_object(
1242         {
1243             class => 'Koha::Patrons',
1244             value => { categorycode => $category->categorycode }
1245         }
1246     );
1247     $category = $builder->build_object(
1248         {
1249             class => 'Koha::Patron::Categories',
1250             value => { category_type => 'O' }
1251         }
1252     );
1253     my $patron_other = $builder->build_object(
1254         {
1255             class => 'Koha::Patrons',
1256             value => { categorycode => $category->categorycode }
1257         }
1258     );
1259     is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1260     is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1261     is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1262     is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1263
1264     is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1265     is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1266     is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1267     is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1268
1269     # Clean up
1270     $patron_adult->delete;
1271     $patron_adult_i->delete;
1272     $patron_child->delete;
1273     $patron_other->delete;
1274 };
1275
1276 subtest 'get_overdues' => sub {
1277     plan tests => 7;
1278
1279     my $library = $builder->build( { source => 'Branch' } );
1280     my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1281     my $item_1 = $builder->build(
1282         {
1283             source => 'Item',
1284             value  => {
1285                 homebranch    => $library->{branchcode},
1286                 holdingbranch => $library->{branchcode},
1287                 biblionumber  => $biblionumber_1
1288             }
1289         }
1290     );
1291     my $item_2 = $builder->build(
1292         {
1293             source => 'Item',
1294             value  => {
1295                 homebranch    => $library->{branchcode},
1296                 holdingbranch => $library->{branchcode},
1297                 biblionumber  => $biblionumber_1
1298             }
1299         }
1300     );
1301     my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1302     my $item_3 = $builder->build(
1303         {
1304             source => 'Item',
1305             value  => {
1306                 homebranch    => $library->{branchcode},
1307                 holdingbranch => $library->{branchcode},
1308                 biblionumber  => $biblionumber_2
1309             }
1310         }
1311     );
1312     my $patron = $builder->build(
1313         {
1314             source => 'Borrower',
1315             value  => { branchcode => $library->{branchcode} }
1316         }
1317     );
1318
1319     t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1320
1321     AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1322     AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1323     AddIssue( $patron, $item_3->{barcode} );
1324
1325     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1326     my $overdues = $patron->get_overdues;
1327     is( $overdues->count, 2, 'Patron should have 2 overdues');
1328     is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1329     is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1330
1331     my $o = $overdues->reset->next;
1332     my $unblessed_overdue = $o->unblessed_all_relateds;
1333     is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1334     is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1335     is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1336     is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1337
1338     # Clean stuffs
1339     $patron->checkouts->delete;
1340     $patron->delete;
1341 };
1342
1343 subtest 'userid_is_valid' => sub {
1344     plan tests => 9;
1345
1346     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1347     my $patron_category = $builder->build_object(
1348         {
1349             class => 'Koha::Patron::Categories',
1350             value => { category_type => 'P', enrolmentfee => 0 }
1351         }
1352     );
1353     my %data = (
1354         cardnumber   => "123456789",
1355         firstname    => "Tomasito",
1356         surname      => "None",
1357         categorycode => $patron_category->categorycode,
1358         branchcode   => $library->branchcode,
1359     );
1360
1361     my $expected_userid_patron_1 = 'tomasito.none';
1362     my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1363     my $patron_1       = Koha::Patrons->find($borrowernumber);
1364     is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1365     is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1366
1367     $patron_1->userid( 'tomasito.non' );
1368     is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1369         1, 'recently created userid -> unique (borrowernumber passed)' );
1370
1371     $patron_1->userid( 'tomasitoxxx' );
1372     is( $patron_1->has_valid_userid,
1373         1, 'non-existent userid -> unique (borrowernumber passed)' );
1374     $patron_1->discard_changes; # We compare with the original userid later
1375
1376     my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1377     is( $patron_not_in_storage->has_valid_userid,
1378         0, 'userid exists for another patron, patron is not in storage yet' );
1379
1380     $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1381     is( $patron_not_in_storage->has_valid_userid,
1382         1, 'non-existent userid, patron is not in storage yet' );
1383
1384     # Regression tests for BZ12226
1385     my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1386     is( $db_patron->has_valid_userid,
1387         0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1388
1389     # Add a new borrower with the same userid but different cardnumber
1390     $data{cardnumber} = "987654321";
1391     my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1392     my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1393     $patron_2->userid($patron_1->userid);
1394     is( $patron_2->has_valid_userid,
1395         0, 'The userid is already in used, it cannot be used for another patron' );
1396
1397     my $new_userid = 'a_user_id';
1398     $data{cardnumber} = "234567890";
1399     $data{userid}     = 'a_user_id';
1400     $borrowernumber   = Koha::Patron->new(\%data)->store->borrowernumber;
1401     my $patron_3 = Koha::Patrons->find($borrowernumber);
1402     is( $patron_3->userid, $new_userid,
1403         'Koha::Patron->store should insert the given userid' );
1404
1405     # Cleanup
1406     $patron_1->delete;
1407     $patron_2->delete;
1408     $patron_3->delete;
1409 };
1410
1411 subtest 'generate_userid' => sub {
1412     plan tests => 7;
1413
1414     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1415     my $patron_category = $builder->build_object(
1416         {
1417             class => 'Koha::Patron::Categories',
1418             value => { category_type => 'P', enrolmentfee => 0 }
1419         }
1420     );
1421     my %data = (
1422         cardnumber   => "123456789",
1423         firstname    => "Tomasito",
1424         surname      => "None",
1425         categorycode => $patron_category->categorycode,
1426         branchcode   => $library->branchcode,
1427     );
1428
1429     my $expected_userid_patron_1 = 'tomasito.none';
1430     my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1431     $new_patron->generate_userid;
1432     my $userid = $new_patron->userid;
1433     is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1434     my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1435     my $patron_1 = Koha::Patrons->find($borrowernumber);
1436     is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1437
1438     $new_patron->generate_userid;
1439     $userid = $new_patron->userid;
1440     is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1441     $data{cardnumber} = '987654321';
1442     my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1443     my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1444     isnt( $patron_2->userid, 'tomasito',
1445         "Patron with duplicate userid has new userid generated" );
1446     is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1447         "Patron with duplicate userid has new userid generated (1 is appened" );
1448
1449     $new_patron->generate_userid;
1450     $userid = $new_patron->userid;
1451     is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1452
1453     $patron_1 = Koha::Patrons->find($borrowernumber);
1454     $patron_1->userid(undef);
1455     $patron_1->generate_userid;
1456     $userid = $patron_1->userid;
1457     is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1458
1459     # Cleanup
1460     $patron_1->delete;
1461     $patron_2->delete;
1462 };
1463
1464 subtest 'attributes' => sub {
1465     plan tests => 2;
1466
1467     my $library1 = Koha::Library->new({
1468         branchcode => 'LIBPATRON',
1469         branchname => 'Library of testing patron',
1470     })->store;
1471
1472     my $library2 = Koha::Library->new({
1473         branchcode => 'LIBATTR',
1474         branchname => 'Library for testing attribute',
1475     })->store;
1476
1477     my $category = Koha::Patron::Category->new({
1478         categorycode => 'CAT1',
1479         description => 'Category 1',
1480     })->store;
1481
1482     my $patron = Koha::Patron->new({
1483         firstname => 'Patron',
1484         surname => 'with attributes',
1485         branchcode => 'LIBPATRON',
1486         categorycode => 'CAT1',
1487     })->store;
1488
1489     my $attribute_type1 = Koha::Patron::Attribute::Type->new({
1490         code => 'CODE_A',
1491         description => 'Code A desciption',
1492     })->store;
1493
1494     my $attribute_type2 = Koha::Patron::Attribute::Type->new({
1495         code => 'CODE_B',
1496         description => 'Code A desciption',
1497     })->store;
1498
1499     $attribute_type2->library_limits ( [ $library2->branchcode ] );
1500
1501     Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type1->code, attribute => 'value 1' } )->store();
1502     Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type2->code, attribute => 'value 2' } )->store();
1503
1504     is( $patron->attributes->count, 1, 'There should be one attribute');
1505
1506     $attribute_type2->library_limits ( [ $library1->branchcode ] );
1507
1508     is( $patron->attributes->count, 2, 'There should be 2 attributes');
1509
1510     $patron->delete;
1511 };
1512
1513 $nb_of_patrons = Koha::Patrons->search->count;
1514 $retrieved_patron_1->delete;
1515 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1516
1517 subtest 'BorrowersLog tests' => sub {
1518     plan tests => 4;
1519
1520     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1521     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1522
1523     my $cardnumber = $patron->cardnumber;
1524     $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1525     $patron->store;
1526
1527     my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1528     my $log_info = from_json( $logs[0]->info );
1529     is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1530     is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1531     is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1532
1533     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1534     $patron->track_login();
1535     @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1536     is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1537 };
1538
1539 $schema->storage->txn_rollback;
1540
1541 subtest 'Test Koha::Patrons::merge' => sub {
1542     plan tests => 110;
1543
1544     my $schema = Koha::Database->new()->schema();
1545
1546     my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1547
1548     $schema->storage->txn_begin;
1549
1550     my $keeper  = $builder->build_object({ class => 'Koha::Patrons' });
1551     my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1552     my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1553
1554     while (my ($r, $field) = each(%$resultsets)) {
1555         $builder->build({ source => $r, value => { $field => $keeper->id } });
1556         $builder->build({ source => $r, value => { $field => $loser_1 } });
1557         $builder->build({ source => $r, value => { $field => $loser_2 } });
1558
1559         my $keeper_rs =
1560           $schema->resultset($r)->search( { $field => $keeper->id } );
1561         is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1562
1563         my $loser_1_rs =
1564           $schema->resultset($r)->search( { $field => $loser_1 } );
1565         is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1566
1567         my $loser_2_rs =
1568           $schema->resultset($r)->search( { $field => $loser_2 } );
1569         is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1570     }
1571
1572     my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1573
1574     while (my ($r, $field) = each(%$resultsets)) {
1575         my $keeper_rs =
1576           $schema->resultset($r)->search( {$field => $keeper->id } );
1577         is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1578     }
1579
1580     is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1581     is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1582
1583     $schema->storage->txn_rollback;
1584 };
1585
1586 subtest '->store' => sub {
1587     plan tests => 5;
1588     my $schema = Koha::Database->new->schema;
1589     $schema->storage->txn_begin;
1590
1591     my $print_error = $schema->storage->dbh->{PrintError};
1592     $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1593
1594     my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1595     my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1596
1597     throws_ok
1598         { $patron_2->userid($patron_1->userid)->store; }
1599         'Koha::Exceptions::Object::DuplicateID',
1600         'Koha::Patron->store raises an exception on duplicate ID';
1601
1602     # Test password
1603     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1604     my $password = 'password';
1605     $patron_1->set_password({ password => $password });
1606     like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1607     my $digest = $patron_1->password;
1608     $patron_1->surname('xxx')->store;
1609     is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1610
1611     # Test uppercasesurname
1612     t::lib::Mocks::mock_preference( 'uppercasesurname', 1 );
1613     my $surname = lc $patron_1->surname;
1614     $patron_1->surname($surname)->store;
1615     isnt( $patron_1->surname, $surname,
1616         'Surname converts to uppercase on store.');
1617     t::lib::Mocks::mock_preference( 'uppercasesurname', 0 );
1618     $patron_1->surname($surname)->store;
1619     is( $patron_1->surname, $surname,
1620         'Surname remains unchanged on store.');
1621
1622     $schema->storage->dbh->{PrintError} = $print_error;
1623     $schema->storage->txn_rollback;
1624 };
1625
1626 subtest '->set_password' => sub {
1627
1628     plan tests => 14;
1629
1630     $schema->storage->txn_begin;
1631
1632     my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1633
1634     # Disable logging password changes for this tests
1635     t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1636
1637     # Password-length tests
1638     t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1639     throws_ok { $patron->set_password({ password => 'ab' }); }
1640         'Koha::Exceptions::Password::TooShort',
1641         'minPasswordLength is undef, fall back to 3, fail test';
1642     is( "$@",
1643         'Password length (2) is shorter than required (3)',
1644         'Exception parameters passed correctly'
1645     );
1646
1647     t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1648     throws_ok { $patron->set_password({ password => 'ab' }); }
1649         'Koha::Exceptions::Password::TooShort',
1650         'minPasswordLength is 2, fall back to 3, fail test';
1651
1652     t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1653     throws_ok { $patron->set_password({ password => 'abcb' }); }
1654         'Koha::Exceptions::Password::TooShort',
1655         'minPasswordLength is 5, fail test';
1656
1657     # Trailing spaces tests
1658     throws_ok { $patron->set_password({ password => 'abcD12d   ' }); }
1659         'Koha::Exceptions::Password::WhitespaceCharacters',
1660         'Password contains trailing spaces, exception is thrown';
1661
1662     # Require strong password tests
1663     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1664     throws_ok { $patron->set_password({ password => 'abcd   a' }); }
1665         'Koha::Exceptions::Password::TooWeak',
1666         'Password is too weak, exception is thrown';
1667
1668     # Refresh patron from DB, just to make sure
1669     $patron->discard_changes;
1670     is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1671
1672     $patron->set_password({ password => 'abcD12 34' });
1673     $patron->discard_changes;
1674
1675     is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1676
1677     lives_ok { $patron->set_password({ password => 'abcd   a', skip_validation => 1 }) }
1678         'Password is weak, but skip_validation was passed, so no exception thrown';
1679
1680     # Completeness
1681     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1682     $patron->login_attempts(3)->store;
1683     my $old_digest = $patron->password;
1684     $patron->set_password({ password => 'abcd   a' });
1685     $patron->discard_changes;
1686
1687     isnt( $patron->password, $old_digest, 'Password has been updated' );
1688     ok( checkpw_hash('abcd   a', $patron->password), 'Password hash is correct' );
1689     is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1690
1691     my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1692     is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1693
1694     # Enable logging password changes
1695     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1696     $patron->set_password({ password => 'abcd   b' });
1697
1698     $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1699     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1700
1701     $schema->storage->txn_rollback;
1702 };
1703
1704 $schema->storage->txn_begin;
1705 subtest 'search_unsubscribed' => sub {
1706     plan tests => 4;
1707
1708     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1709     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
1710     is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
1711
1712     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1713     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1714
1715     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
1716     Koha::Patron::Consents->delete; # for correct counts
1717     Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING',  refused_on => dt_from_string })->store;
1718     is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
1719
1720     # Add another refusal but shift the period
1721     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
1722     Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING',  refused_on => dt_from_string->subtract(days=>2) })->store;
1723     is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
1724
1725     # Try another (special) attempts setting
1726     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
1727     # Lockout is now disabled
1728     # Patron2 still matches: refused earlier, not locked
1729     is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
1730 };
1731
1732 subtest 'search_anonymize_candidates' => sub {
1733     plan tests => 5;
1734     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1735     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1736     $patron1->anonymized(0);
1737     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1738     $patron2->anonymized(0);
1739     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1740
1741     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
1742     is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
1743
1744     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
1745     my $cnt = Koha::Patrons->search_anonymize_candidates->count;
1746     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1747     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1748     is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
1749
1750     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
1751     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1752     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1753     $cnt = Koha::Patrons->search_anonymize_candidates->count;
1754     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1755     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1756     is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
1757
1758     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
1759     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1760     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1761     $cnt = Koha::Patrons->search_anonymize_candidates->count;
1762     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1763     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1764     is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
1765
1766     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1767     $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1768     $patron1->login_attempts(0)->store;
1769     $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1770     $patron2->login_attempts(0)->store;
1771     $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
1772     $patron1->login_attempts(3)->store;
1773     is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1774         $cnt+1, 'Locked flag' );
1775 };
1776
1777 subtest 'search_anonymized' => sub {
1778     plan tests => 3;
1779     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1780
1781     t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
1782     is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
1783
1784     t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
1785     $patron1->dateexpiry( dt_from_string );
1786     $patron1->anonymized(0)->store;
1787     my $cnt = Koha::Patrons->search_anonymized->count;
1788     $patron1->anonymized(1)->store;
1789     is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
1790     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1791     is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
1792 };
1793
1794 subtest 'lock' => sub {
1795     plan tests => 8;
1796
1797     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1798     my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1799     my $hold = $builder->build_object({
1800         class => 'Koha::Holds',
1801         value => { borrowernumber => $patron1->borrowernumber },
1802     });
1803
1804     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1805     my $expiry = dt_from_string->add(days => 1);
1806     $patron1->dateexpiry( $expiry );
1807     $patron1->lock;
1808     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1809     is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
1810     is( $patron1->holds->count, 1, 'No holds removed' );
1811
1812     $patron1->lock({ expire => 1, remove => 1});
1813     isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
1814     is( $patron1->holds->count, 0, 'Holds removed' );
1815
1816     # Disable lockout feature
1817     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1818     $patron1->login_attempts(0);
1819     $patron1->dateexpiry( $expiry );
1820     $patron1->store;
1821     $patron1->lock;
1822     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1823
1824     # Trivial wrapper test (Koha::Patrons->lock)
1825     $patron1->login_attempts(0)->store;
1826     Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
1827     $patron1->discard_changes; # refresh
1828     $patron2->discard_changes;
1829     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
1830     is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
1831 };
1832
1833 subtest 'anonymize' => sub {
1834     plan tests => 10;
1835
1836     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1837     my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1838
1839     # First try patron with issues
1840     my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
1841     warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
1842     $issue->delete;
1843
1844     t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
1845     my $surname = $patron1->surname; # expect change, no clear
1846     my $branchcode = $patron1->branchcode; # expect skip
1847     $patron1->anonymize;
1848     is($patron1->anonymized, 1, 'Check flag' );
1849
1850     is( $patron1->dateofbirth, undef, 'Birth date cleared' );
1851     is( $patron1->firstname, undef, 'First name cleared' );
1852     isnt( $patron1->surname, $surname, 'Surname changed' );
1853     ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
1854     is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
1855     is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
1856
1857     # Test wrapper in Koha::Patrons
1858     $patron1->surname($surname)->store; # restore
1859     my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
1860     $patron1->discard_changes; # refresh
1861     isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
1862     $patron2->discard_changes; # refresh
1863     is( $patron2->firstname, undef, 'First name patron2 cleared' );
1864 };
1865 $schema->storage->txn_rollback;