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