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