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