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