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