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