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