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