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