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