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