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