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