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