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