3 # Copyright 2015 Koha Development team
5 # This file is part of Koha
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.
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.
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>.
22 use Test::More tests => 40;
34 use C4::Auth qw(checkpw_hash);
40 use Koha::Patron::Categories;
41 use Koha::Patron::Relationship;
44 use Koha::Virtualshelves;
46 use t::lib::TestBuilder;
49 my $schema = Koha::Database->new->schema;
50 $schema->storage->txn_begin;
52 my $builder = t::lib::TestBuilder->new;
53 my $library = $builder->build({source => 'Branch' });
54 my $category = $builder->build({source => 'Category' });
55 my $nb_of_patrons = Koha::Patrons->search->count;
56 my $new_patron_1 = Koha::Patron->new(
57 { cardnumber => 'test_cn_1',
58 branchcode => $library->{branchcode},
59 categorycode => $category->{categorycode},
60 surname => 'surname for patron1',
61 firstname => 'firstname for patron1',
62 userid => 'a_nonexistent_userid_1',
63 flags => 1, # Is superlibrarian
66 my $new_patron_2 = Koha::Patron->new(
67 { cardnumber => 'test_cn_2',
68 branchcode => $library->{branchcode},
69 categorycode => $category->{categorycode},
70 surname => 'surname for patron2',
71 firstname => 'firstname for patron2',
72 userid => 'a_nonexistent_userid_2',
76 t::lib::Mocks::mock_userenv({ patron => $new_patron_1 });
78 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
80 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
81 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
83 subtest 'library' => sub {
85 is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
86 is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
89 subtest 'guarantees' => sub {
92 t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test|test2' );
94 my $guarantees = $new_patron_1->guarantee_relationships;
95 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
96 is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee relationships' );
97 my @guarantees = $new_patron_1->guarantee_relationships;
98 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantee_relationships should return an array in a list context' );
99 is( scalar(@guarantees), 0, 'new_patron_1 should have 0 guarantee' );
101 my $guarantee_1 = $builder->build({ source => 'Borrower' });
102 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
103 my $guarantee_2 = $builder->build({ source => 'Borrower' });
104 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
106 $guarantees = $new_patron_1->guarantee_relationships;
107 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantee_relationships should return a Koha::Patrons result set in a scalar context' );
108 is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
109 @guarantees = $new_patron_1->guarantee_relationships;
110 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantee_relationships should return an array in a list context' );
111 is( scalar(@guarantees), 2, 'new_patron_1 should have 2 guarantees' );
112 $_->delete for @guarantees;
114 #Test return order of guarantees BZ 18635
115 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
116 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
118 my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
120 my $order_guarantee1 = $builder->build_object(
122 class => 'Koha::Patrons',
128 $builder->build_object(
130 class => 'Koha::Patron::Relationships',
132 guarantor_id => $guarantor->id,
133 guarantee_id => $order_guarantee1,
134 relationship => 'test',
139 my $order_guarantee2 = $builder->build_object(
141 class => 'Koha::Patrons',
147 $builder->build_object(
149 class => 'Koha::Patron::Relationships',
151 guarantor_id => $guarantor->id,
152 guarantee_id => $order_guarantee2,
153 relationship => 'test',
158 my $order_guarantee3 = $builder->build_object(
160 class => 'Koha::Patrons',
163 firstname => 'Walrus',
167 $builder->build_object(
169 class => 'Koha::Patron::Relationships',
171 guarantor_id => $guarantor->id,
172 guarantee_id => $order_guarantee3,
173 relationship => 'test',
178 my $order_guarantee4 = $builder->build_object(
180 class => 'Koha::Patrons',
183 firstname => 'Vulture',
184 guarantorid => $guarantor->borrowernumber
188 $builder->build_object(
190 class => 'Koha::Patron::Relationships',
192 guarantor_id => $guarantor->id,
193 guarantee_id => $order_guarantee4,
194 relationship => 'test',
199 my $order_guarantee5 = $builder->build_object(
201 class => 'Koha::Patrons',
204 firstname => 'Unicorn',
205 guarantorid => $guarantor->borrowernumber
209 my $r = $builder->build_object(
211 class => 'Koha::Patron::Relationships',
213 guarantor_id => $guarantor->id,
214 guarantee_id => $order_guarantee5,
215 relationship => 'test',
220 $guarantees = $guarantor->guarantee_relationships->guarantees;
222 is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
223 is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
224 is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
225 is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
226 is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
229 subtest 'category' => sub {
231 my $patron_category = $new_patron_1->category;
232 is( ref( $patron_category), 'Koha::Patron::Category', );
233 is( $patron_category->categorycode, $category->{categorycode}, );
236 subtest 'siblings' => sub {
238 my $siblings = $new_patron_1->siblings;
239 is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
240 my $guarantee_1 = $builder->build( { source => 'Borrower' } );
241 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
242 my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
243 $siblings = $retrieved_guarantee_1->siblings;
244 is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
245 my @siblings = $retrieved_guarantee_1->siblings;
246 is( ref( \@siblings ), 'ARRAY', 'Koha::Patron->siblings should return an array in a list context' );
247 is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' );
248 my $guarantee_2 = $builder->build( { source => 'Borrower' } );
249 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
250 my $guarantee_3 = $builder->build( { source => 'Borrower' } );
251 my $relationship_3 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_3->{borrowernumber}, relationship => 'test' } )->store();
252 $siblings = $retrieved_guarantee_1->siblings;
253 is( $siblings->count, 2, 'guarantee_1 should have 2 siblings' );
254 is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
255 is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
256 $_->delete for $retrieved_guarantee_1->siblings;
257 $retrieved_guarantee_1->delete;
260 subtest 'has_overdues' => sub {
263 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
264 my $item_1 = $builder->build(
267 homebranch => $library->{branchcode},
268 holdingbranch => $library->{branchcode},
272 biblionumber => $biblioitem_1->{biblionumber}
276 my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
277 is( $retrieved_patron->has_overdues, 0, );
279 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
280 my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
281 is( $retrieved_patron->has_overdues, 0, );
283 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
284 $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
285 $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
286 is( $retrieved_patron->has_overdues, 1, );
290 subtest 'is_expired' => sub {
292 my $patron = $builder->build({ source => 'Borrower' });
293 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
294 $patron->dateexpiry( undef )->store->discard_changes;
295 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
296 $patron->dateexpiry( dt_from_string )->store->discard_changes;
297 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
298 $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
299 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
300 $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
301 is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
306 subtest 'is_going_to_expire' => sub {
309 my $today = dt_from_string(undef, undef, 'floating');
310 my $patron = $builder->build({ source => 'Borrower' });
311 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
312 $patron->dateexpiry( undef )->store->discard_changes;
313 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
315 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
316 $patron->dateexpiry( $today )->store->discard_changes;
317 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
319 $patron->dateexpiry( $today )->store->discard_changes;
320 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
322 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
323 $patron->dateexpiry( $today->clone->add( days => 11 ) )->store->discard_changes;
324 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 11 days ahead and pref is 10');
326 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
327 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
328 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 10 days ahead and pref is 0');
330 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
331 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
332 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 10 days ahead and pref is 10');
335 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
336 $patron->dateexpiry( $today->clone->add( days => 20 ) )->store->discard_changes;
337 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 20 days ahead and pref is 10');
339 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
340 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
341 is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
343 { # Testing invalid is going to expiry date
344 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 30);
345 # mock_config does not work here, because of tz vs timezone subroutines
346 my $context = new Test::MockModule('C4::Context');
347 $context->mock( 'tz', sub {
350 $patron->dateexpiry(DateTime->new( year => 2019, month => 12, day => 3 ))->store;
351 eval { $patron->is_going_to_expire };
352 is( $@, '', 'On invalid "is going to expire" date, the method should not crash with "Invalid local time for date in time zone"');
353 $context->unmock('tz');
360 subtest 'renew_account' => sub {
363 for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
364 my $dt = dt_from_string( $date, 'iso' );
365 Time::Fake->offset( $dt->epoch );
366 my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
367 my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
368 my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
369 my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
370 my $a_year_later_plus_a_month = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
371 my $patron_category = $builder->build(
372 { source => 'Category',
374 enrolmentperiod => 12,
375 enrolmentperioddate => undef,
379 my $patron = $builder->build(
380 { source => 'Borrower',
382 dateexpiry => $a_month_ago,
383 categorycode => $patron_category->{categorycode},
384 date_renewed => undef, # Force builder to not populate the column for new patron
388 my $patron_2 = $builder->build(
389 { source => 'Borrower',
391 dateexpiry => $a_month_ago,
392 categorycode => $patron_category->{categorycode},
396 my $patron_3 = $builder->build(
397 { source => 'Borrower',
399 dateexpiry => $a_month_later,
400 categorycode => $patron_category->{categorycode},
404 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
405 my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
406 my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
408 is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
410 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
411 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
412 my $expiry_date = $retrieved_patron->renew_account;
413 is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
414 my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
415 is( dt_from_string($retrieved_expiry_date), $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
416 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
417 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
419 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
420 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
421 $expiry_date = $retrieved_patron->renew_account;
422 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
423 $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
424 is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
425 $retrieved_expiry_date = $retrieved_patron->dateexpiry;
426 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
427 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
428 is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
430 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
431 $expiry_date = $retrieved_patron_2->renew_account;
432 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
433 $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
434 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
436 $expiry_date = $retrieved_patron_3->renew_account;
437 is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
438 $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
439 is( dt_from_string($retrieved_expiry_date), $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
441 $retrieved_patron->delete;
442 $retrieved_patron_2->delete;
443 $retrieved_patron_3->delete;
448 subtest "move_to_deleted" => sub {
450 my $originally_updated_on = '2016-01-01 12:12:12';
451 my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
452 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
453 is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
454 ; # FIXME This should be Koha::Deleted::Patron
455 my $deleted_patron = $schema->resultset('Deletedborrower')
456 ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
458 ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
459 ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
460 isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
461 $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
462 is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
463 $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup
466 subtest "delete" => sub {
468 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
469 my $patron = $builder->build( { source => 'Borrower' } );
470 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
471 my $hold = $builder->build(
472 { source => 'Reserve',
473 value => { borrowernumber => $patron->{borrowernumber} }
476 my $list = $builder->build(
477 { source => 'Virtualshelve',
478 value => { owner => $patron->{borrowernumber} }
482 my $deleted = $retrieved_patron->delete;
483 is( $deleted, 1, 'Koha::Patron->delete should return 1 if the patron has been correctly deleted' );
485 is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
487 is (Koha::Old::Holds->search( { reserve_id => $hold->{ reserve_id } } )->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| );
489 is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have cancelled patron's holds 2| );
491 is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
493 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
494 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
497 subtest 'Koha::Patrons->delete' => sub {
500 my $mod_patron = Test::MockModule->new( 'Koha::Patron' );
501 my $moved_to_deleted = 0;
502 $mod_patron->mock( 'move_to_deleted', sub { $moved_to_deleted++; } );
504 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
505 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
506 my $id1 = $patron1->borrowernumber;
507 my $set = Koha::Patrons->search({ borrowernumber => { '>=' => $id1 }});
508 is( $set->count, 2, 'Two patrons found as expected' );
509 is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
510 is( $moved_to_deleted, 2, 'Patrons moved to deletedborrowers' );
512 # Add again, test if we can raise an exception
513 $mod_patron->mock( 'delete', sub { return -1; } );
514 $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
515 $id1 = $patron1->borrowernumber;
516 $set = Koha::Patrons->search({ borrowernumber => { '>=' => $id1 }});
517 throws_ok { $set->delete } 'Koha::Exceptions::Patron::FailedDelete',
518 'Exception raised for deleting patron';
521 subtest 'add_enrolment_fee_if_needed' => sub {
524 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
525 foreach( keys %{$enrolmentfees} ) {
526 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
528 my $enrolmentfee_K = $enrolmentfees->{K};
529 my $enrolmentfee_J = $enrolmentfees->{J};
530 my $enrolmentfee_YA = $enrolmentfees->{YA};
532 my %borrower_data = (
533 firstname => 'my firstname',
534 surname => 'my surname',
536 branchcode => $library->{branchcode},
539 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
540 $borrower_data{borrowernumber} = $borrowernumber;
542 my $patron = Koha::Patrons->find( $borrowernumber );
543 my $total = $patron->account->balance;
544 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
546 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
547 $borrower_data{categorycode} = 'J';
548 $patron->set(\%borrower_data)->store;
549 $total = $patron->account->balance;
550 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
552 $borrower_data{categorycode} = 'K';
553 $patron->set(\%borrower_data)->store;
554 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
556 $borrower_data{categorycode} = 'J';
557 $patron->set(\%borrower_data)->store;
558 $total = $patron->account->balance;
559 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
561 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
562 $patron->categorycode('YA')->store;
563 $total = $patron->account->balance;
565 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
566 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
572 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
575 my $library = $builder->build( { source => 'Branch' } );
576 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
577 my $item_1 = $builder->build(
581 homebranch => $library->{branchcode},
582 holdingbranch => $library->{branchcode},
583 biblionumber => $biblionumber_1,
589 my $item_2 = $builder->build(
593 homebranch => $library->{branchcode},
594 holdingbranch => $library->{branchcode},
595 biblionumber => $biblionumber_1,
601 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
602 my $item_3 = $builder->build(
606 homebranch => $library->{branchcode},
607 holdingbranch => $library->{branchcode},
608 biblionumber => $biblionumber_2,
614 my $patron = $builder->build(
616 source => 'Borrower',
617 value => { branchcode => $library->{branchcode} }
621 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
622 my $checkouts = $patron->checkouts;
623 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
624 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
625 my $pending_checkouts = $patron->pending_checkouts;
626 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
627 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
628 my $old_checkouts = $patron->old_checkouts;
629 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
630 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
632 # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
633 $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
635 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
637 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
638 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
639 AddIssue( $patron, $item_3->{barcode} );
641 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
642 $checkouts = $patron->checkouts;
643 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
644 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
645 $pending_checkouts = $patron->pending_checkouts;
646 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
647 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
649 my $first_checkout = $pending_checkouts->next;
650 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
652 my $overdues = $patron->get_overdues;
653 is( $overdues->count, 2, 'Patron should have 2 overdues');
654 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
655 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
656 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
659 C4::Circulation::AddReturn( $item_1->{barcode} );
660 C4::Circulation::AddReturn( $item_2->{barcode} );
661 $old_checkouts = $patron->old_checkouts;
662 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
663 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
666 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
670 subtest 'get_routing_lists' => sub {
673 my $biblio = Koha::Biblio->new()->store();
674 my $subscription = Koha::Subscription->new({
675 biblionumber => $biblio->biblionumber,
679 my $patron = $builder->build( { source => 'Borrower' } );
680 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
682 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
684 my $routinglist_count = Koha::Subscription::Routinglists->count;
685 my $routinglist = Koha::Subscription::Routinglist->new({
686 borrowernumber => $patron->borrowernumber,
688 subscriptionid => $subscription->subscriptionid
691 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
693 my $routinglists = $patron->get_routing_lists;
694 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
695 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
697 my $subscription2 = Koha::Subscription->new({
698 biblionumber => $biblio->biblionumber,
701 my $routinglist2 = Koha::Subscription::Routinglist->new({
702 borrowernumber => $patron->borrowernumber,
704 subscriptionid => $subscription2->subscriptionid
707 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
709 $patron->delete; # Clean up for later tests
713 subtest 'get_age' => sub {
716 my $patron = $builder->build( { source => 'Borrower' } );
717 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
719 my $today = dt_from_string;
721 $patron->dateofbirth( undef );
722 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
723 $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1, end_of_month => 'limit' ) );
724 is( $patron->get_age, 12, 'Patron should be 12' );
725 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 1, end_of_month => 'limit' ) );
726 is( $patron->get_age, 17, 'Patron should be 17, happy birthday tomorrow!' );
727 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 0, end_of_month => 'limit' ) );
728 is( $patron->get_age, 18, 'Patron should be 18' );
729 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -31, end_of_month => 'limit' ) );
730 is( $patron->get_age, 19, 'Patron should be 19' );
731 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -30, end_of_month => 'limit' ) );
732 is( $patron->get_age, 19, 'Patron should be 19 again' );
733 $patron->dateofbirth( $today->clone->add( years => 0, months => -1, days => -1, end_of_month => 'limit' ) );
734 is( $patron->get_age, 0, 'Patron is a newborn child' );
739 subtest 'is_valid_age' => sub {
742 my $today = dt_from_string;
744 my $category = $builder->build({
745 source => 'Category',
747 categorycode => 'AGE_5_10',
748 dateofbirthrequired => 5,
752 $category = Koha::Patron::Categories->find( $category->{categorycode} );
754 my $patron = $builder->build({
755 source => 'Borrower',
757 categorycode => 'AGE_5_10'
760 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
763 $patron->dateofbirth( undef );
764 is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
766 $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1 ) );
767 is( $patron->is_valid_age, 0, 'Patron is 12, so the age is above allowed range 5-10 years');
769 $patron->dateofbirth( $today->clone->add( years => -3, months => -6, days => -1 ) );
770 is( $patron->is_valid_age, 0, 'Patron is 3, so the age is below allowed range 5-10 years');
772 $patron->dateofbirth( $today->clone->add( years => -7, months => -6, days => -1 ) );
773 is( $patron->is_valid_age, 1, 'Patron is 7, so the age perfectly suits allowed range 5-10 years');
775 $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => 0 ) );
776 is( $patron->is_valid_age, 1, 'Patron celebrates the 5th birthday today, so the age is allowed for this category');
778 $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => 1 ) );
779 is( $patron->is_valid_age, 0, 'Patron will celebrate the 5th birthday tomorrow, so the age is NOT allowed for this category');
781 $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => -1 ) );
782 is( $patron->is_valid_age, 1, 'Patron celebrated the 5th birthday yesterday, so the age is allowed for this category');
784 $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => 0 ) );
785 is( $patron->is_valid_age, 0, 'Patron celebrate the 11th birthday today, so the age is NOT allowed for this category');
787 $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => 1 ) );
788 is( $patron->is_valid_age, 1, 'Patron will celebrate the 11th birthday tomorrow, so the age is allowed for this category');
790 $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => -1 ) );
791 is( $patron->is_valid_age, 0, 'Patron celebrated the 11th birthday yesterday, so the age is NOT allowed for this category');
797 subtest 'account' => sub {
800 my $patron = $builder->build({source => 'Borrower'});
802 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
803 my $account = $patron->account;
804 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
809 subtest 'search_upcoming_membership_expires' => sub {
812 my $expiry_days = 15;
813 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
814 my $nb_of_days_before = 1;
815 my $nb_of_days_after = 2;
817 my $builder = t::lib::TestBuilder->new();
819 my $library = $builder->build({ source => 'Branch' });
821 # before we add borrowers to this branch, add the expires we have now
822 # note that this pertains to the current mocked setting of the pref
823 # for this reason we add the new branchcode to most of the tests
824 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
826 my $patron_1 = $builder->build({
827 source => 'Borrower',
829 branchcode => $library->{branchcode},
830 dateexpiry => dt_from_string->add( days => $expiry_days )
834 my $patron_2 = $builder->build({
835 source => 'Borrower',
837 branchcode => $library->{branchcode},
838 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
842 my $patron_3 = $builder->build({
843 source => 'Borrower',
845 branchcode => $library->{branchcode},
846 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
850 # Test without extra parameters
851 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
852 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
855 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
856 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
857 my $expired = $upcoming_mem_expires->next;
858 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
859 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
860 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
862 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
863 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
864 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
866 # Test MembershipExpiryDaysNotice == undef
867 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
868 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
869 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
871 # Test the before parameter
872 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
873 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
874 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
875 # Test after parameter also
876 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
877 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
878 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
881 subtest 'holds and old_holds' => sub {
884 my $library = $builder->build( { source => 'Branch' } );
885 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
886 my $item_1 = $builder->build(
890 homebranch => $library->{branchcode},
891 holdingbranch => $library->{branchcode},
892 biblionumber => $biblionumber_1
896 my $item_2 = $builder->build(
900 homebranch => $library->{branchcode},
901 holdingbranch => $library->{branchcode},
902 biblionumber => $biblionumber_1
906 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
907 my $item_3 = $builder->build(
911 homebranch => $library->{branchcode},
912 holdingbranch => $library->{branchcode},
913 biblionumber => $biblionumber_2
917 my $patron = $builder->build(
919 source => 'Borrower',
920 value => { branchcode => $library->{branchcode} }
924 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
925 my $holds = $patron->holds;
926 is( ref($holds), 'Koha::Holds',
927 'Koha::Patron->holds should return a Koha::Holds objects' );
928 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
930 C4::Reserves::AddReserve( $library->{branchcode},
931 $patron->borrowernumber, $biblionumber_1 );
933 C4::Reserves::AddReserve( $library->{branchcode},
934 $patron->borrowernumber, $biblionumber_2, undef, undef, dt_from_string->add( days => 2 ) );
936 $holds = $patron->holds;
937 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
939 my $old_holds = $patron->old_holds;
940 is( ref($old_holds), 'Koha::Old::Holds',
941 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
942 is( $old_holds->count, 0, 'There should not be any old holds yet');
944 my $hold = $holds->next;
947 $old_holds = $patron->old_holds;
948 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
955 subtest 'notice_email_address' => sub {
958 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
960 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
961 is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
963 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
964 is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
969 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
972 # TODO create a subroutine in t::lib::Mocks
973 my $branch = $builder->build({ source => 'Branch' });
974 my $userenv_patron = $builder->build_object({
975 class => 'Koha::Patrons',
976 value => { branchcode => $branch->{branchcode}, flags => 0 },
978 t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
980 my $anonymous = $builder->build( { source => 'Borrower', }, );
982 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
984 subtest 'patron privacy is 1 (default)' => sub {
987 t::lib::Mocks::mock_preference('IndependentBranches', 0);
988 my $patron = $builder->build(
989 { source => 'Borrower',
990 value => { privacy => 1, }
993 my $item_1 = $builder->build(
1001 my $issue_1 = $builder->build(
1002 { source => 'Issue',
1004 borrowernumber => $patron->{borrowernumber},
1005 itemnumber => $item_1->{itemnumber},
1009 my $item_2 = $builder->build(
1017 my $issue_2 = $builder->build(
1018 { source => 'Issue',
1020 borrowernumber => $patron->{borrowernumber},
1021 itemnumber => $item_2->{itemnumber},
1026 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1027 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, dt_from_string('2011-11-11') );
1028 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
1030 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
1031 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
1033 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
1034 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1036 $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1037 is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
1039 my $dbh = C4::Context->dbh;
1040 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
1041 $sth->execute($item_1->{itemnumber});
1042 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1043 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
1044 $sth->execute($item_2->{itemnumber});
1045 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1046 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
1048 $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
1049 $sth->execute($item_2->{itemnumber});
1050 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1051 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
1053 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
1054 $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
1055 $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
1056 $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
1057 $sth->execute($item_1->{itemnumber});
1058 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1059 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
1060 $sth->execute($item_2->{itemnumber});
1061 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1062 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
1064 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1067 subtest 'patron privacy is 0 (forever)' => sub {
1070 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1071 my $patron = $builder->build(
1072 { source => 'Borrower',
1073 value => { privacy => 0, }
1076 my $item = $builder->build(
1084 my $issue = $builder->build(
1085 { source => 'Issue',
1087 borrowernumber => $patron->{borrowernumber},
1088 itemnumber => $item->{itemnumber},
1093 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1094 is( $returned, 1, 'The item should have been returned' );
1096 my $dbh = C4::Context->dbh;
1097 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1098 SELECT borrowernumber FROM old_issues where itemnumber = ?
1099 |, undef, $item->{itemnumber});
1100 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1101 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1104 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1106 subtest 'AnonymousPatron is not defined' => sub {
1109 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1110 my $patron = $builder->build(
1111 { source => 'Borrower',
1112 value => { privacy => 1, }
1115 my $item = $builder->build(
1123 my $issue = $builder->build(
1124 { source => 'Issue',
1126 borrowernumber => $patron->{borrowernumber},
1127 itemnumber => $item->{itemnumber},
1132 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1133 is( $returned, 1, 'The item should have been returned' );
1134 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
1135 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1137 my $dbh = C4::Context->dbh;
1138 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1139 SELECT borrowernumber FROM old_issues where itemnumber = ?
1140 |, undef, $item->{itemnumber});
1141 is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
1142 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1145 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1147 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1148 my $patron = $builder->build(
1149 { source => 'Borrower',
1150 value => { privacy => 1 } # Another branchcode than the logged in librarian
1153 my $item = $builder->build(
1161 my $issue = $builder->build(
1162 { source => 'Issue',
1164 borrowernumber => $patron->{borrowernumber},
1165 itemnumber => $item->{itemnumber},
1170 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1171 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1172 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1175 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1176 $userenv_patron->delete;
1178 # Reset IndependentBranches for further tests
1179 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1182 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1190 $nb_of_patrons = Koha::Patrons->search->count;
1191 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1192 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1193 my $library_11 = $builder->build( { source => 'Branch' } );
1194 my $library_12 = $builder->build( { source => 'Branch' } );
1195 my $library_21 = $builder->build( { source => 'Branch' } );
1196 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1197 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1198 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1199 Koha::Library::Group->new(
1200 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1201 Koha::Library::Group->new(
1202 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1203 Koha::Library::Group->new(
1204 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1206 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1207 # 2 patrons from library_11 (group1)
1208 # patron_11_1 see patron's infos from outside its group
1209 # Setting flags => undef to not be considered as superlibrarian
1210 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1211 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1212 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1213 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1214 # patron_11_2 can only see patron's info from its group
1215 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1216 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1217 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1218 # 1 patron from library_12 (group1)
1219 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1220 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1221 # 1 patron from library_21 (group2) can only see patron's info from its group
1222 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1223 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1224 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1226 # Pfiou, we can start now!
1227 subtest 'libraries_where_can_see_patrons' => sub {
1232 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1233 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1234 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1236 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1237 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1238 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| );
1240 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1241 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1242 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| );
1244 subtest 'can_see_patron_infos' => sub {
1247 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1248 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1249 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1250 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1252 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1253 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1254 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1255 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1257 subtest 'search_limited' => sub {
1260 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1261 my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1262 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1263 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1265 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1266 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1267 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' );
1269 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1270 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1271 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1273 $patron_11_1->delete;
1274 $patron_11_2->delete;
1279 subtest 'account_locked' => sub {
1281 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1282 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1283 for my $value ( undef, '', 0 ) {
1284 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1285 $patron->login_attempts(0)->store;
1286 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1287 $patron->login_attempts(1)->store;
1288 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1289 $patron->login_attempts(-1)->store;
1290 is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1293 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1294 $patron->login_attempts(2)->store;
1295 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1296 $patron->login_attempts(3)->store;
1297 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1298 $patron->login_attempts(4)->store;
1299 is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1300 $patron->login_attempts(-1)->store;
1301 is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1306 subtest 'is_child | is_adult' => sub {
1308 my $category = $builder->build_object(
1310 class => 'Koha::Patron::Categories',
1311 value => { category_type => 'A' }
1314 my $patron_adult = $builder->build_object(
1316 class => 'Koha::Patrons',
1317 value => { categorycode => $category->categorycode }
1320 $category = $builder->build_object(
1322 class => 'Koha::Patron::Categories',
1323 value => { category_type => 'I' }
1326 my $patron_adult_i = $builder->build_object(
1328 class => 'Koha::Patrons',
1329 value => { categorycode => $category->categorycode }
1332 $category = $builder->build_object(
1334 class => 'Koha::Patron::Categories',
1335 value => { category_type => 'C' }
1338 my $patron_child = $builder->build_object(
1340 class => 'Koha::Patrons',
1341 value => { categorycode => $category->categorycode }
1344 $category = $builder->build_object(
1346 class => 'Koha::Patron::Categories',
1347 value => { category_type => 'O' }
1350 my $patron_other = $builder->build_object(
1352 class => 'Koha::Patrons',
1353 value => { categorycode => $category->categorycode }
1356 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1357 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1358 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1359 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1361 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1362 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1363 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1364 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1367 $patron_adult->delete;
1368 $patron_adult_i->delete;
1369 $patron_child->delete;
1370 $patron_other->delete;
1373 subtest 'get_overdues' => sub {
1376 my $library = $builder->build( { source => 'Branch' } );
1377 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1378 my $item_1 = $builder->build(
1382 homebranch => $library->{branchcode},
1383 holdingbranch => $library->{branchcode},
1384 biblionumber => $biblionumber_1
1388 my $item_2 = $builder->build(
1392 homebranch => $library->{branchcode},
1393 holdingbranch => $library->{branchcode},
1394 biblionumber => $biblionumber_1
1398 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1399 my $item_3 = $builder->build(
1403 homebranch => $library->{branchcode},
1404 holdingbranch => $library->{branchcode},
1405 biblionumber => $biblionumber_2
1409 my $patron = $builder->build(
1411 source => 'Borrower',
1412 value => { branchcode => $library->{branchcode} }
1416 t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1418 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1419 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1420 AddIssue( $patron, $item_3->{barcode} );
1422 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1423 my $overdues = $patron->get_overdues;
1424 is( $overdues->count, 2, 'Patron should have 2 overdues');
1425 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1426 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1428 my $o = $overdues->reset->next;
1429 my $unblessed_overdue = $o->unblessed_all_relateds;
1430 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1431 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1432 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1433 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1436 $patron->checkouts->delete;
1440 subtest 'userid_is_valid' => sub {
1443 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1444 my $patron_category = $builder->build_object(
1446 class => 'Koha::Patron::Categories',
1447 value => { category_type => 'P', enrolmentfee => 0 }
1451 cardnumber => "123456789",
1452 firstname => "Tomasito",
1454 categorycode => $patron_category->categorycode,
1455 branchcode => $library->branchcode,
1458 my $expected_userid_patron_1 = 'tomasito.none';
1459 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1460 my $patron_1 = Koha::Patrons->find($borrowernumber);
1461 is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1462 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1464 $patron_1->userid( 'tomasito.non' );
1465 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1466 1, 'recently created userid -> unique (borrowernumber passed)' );
1468 $patron_1->userid( 'tomasitoxxx' );
1469 is( $patron_1->has_valid_userid,
1470 1, 'non-existent userid -> unique (borrowernumber passed)' );
1471 $patron_1->discard_changes; # We compare with the original userid later
1473 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1474 is( $patron_not_in_storage->has_valid_userid,
1475 0, 'userid exists for another patron, patron is not in storage yet' );
1477 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1478 is( $patron_not_in_storage->has_valid_userid,
1479 1, 'non-existent userid, patron is not in storage yet' );
1481 # Regression tests for BZ12226
1482 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1483 is( $db_patron->has_valid_userid,
1484 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1486 # Add a new borrower with the same userid but different cardnumber
1487 $data{cardnumber} = "987654321";
1488 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1489 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1490 $patron_2->userid($patron_1->userid);
1491 is( $patron_2->has_valid_userid,
1492 0, 'The userid is already in used, it cannot be used for another patron' );
1494 my $new_userid = 'a_user_id';
1495 $data{cardnumber} = "234567890";
1496 $data{userid} = 'a_user_id';
1497 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1498 my $patron_3 = Koha::Patrons->find($borrowernumber);
1499 is( $patron_3->userid, $new_userid,
1500 'Koha::Patron->store should insert the given userid' );
1508 subtest 'generate_userid' => sub {
1511 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1512 my $patron_category = $builder->build_object(
1514 class => 'Koha::Patron::Categories',
1515 value => { category_type => 'P', enrolmentfee => 0 }
1519 cardnumber => "123456789",
1520 firstname => "Tômà sÃtó",
1521 surname => "Ñoné",
1522 categorycode => $patron_category->categorycode,
1523 branchcode => $library->branchcode,
1526 my $expected_userid_patron_1 = 'tomasito.none';
1527 my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1528 $new_patron->generate_userid;
1529 my $userid = $new_patron->userid;
1530 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1531 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1532 my $patron_1 = Koha::Patrons->find($borrowernumber);
1533 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1535 $new_patron->generate_userid;
1536 $userid = $new_patron->userid;
1537 is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1538 $data{cardnumber} = '987654321';
1539 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1540 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1541 isnt( $patron_2->userid, 'tomasito',
1542 "Patron with duplicate userid has new userid generated" );
1543 is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1544 "Patron with duplicate userid has new userid generated (1 is appened" );
1546 $new_patron->generate_userid;
1547 $userid = $new_patron->userid;
1548 is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1550 $patron_1 = Koha::Patrons->find($borrowernumber);
1551 $patron_1->userid(undef);
1552 $patron_1->generate_userid;
1553 $userid = $patron_1->userid;
1554 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1561 subtest 'attributes' => sub {
1564 my $library1 = Koha::Library->new({
1565 branchcode => 'LIBPATRON',
1566 branchname => 'Library of testing patron',
1569 my $library2 = Koha::Library->new({
1570 branchcode => 'LIBATTR',
1571 branchname => 'Library for testing attribute',
1574 my $category = Koha::Patron::Category->new({
1575 categorycode => 'CAT1',
1576 description => 'Category 1',
1579 my $patron = Koha::Patron->new({
1580 firstname => 'Patron',
1581 surname => 'with attributes',
1582 branchcode => 'LIBPATRON',
1583 categorycode => 'CAT1',
1586 my $attribute_type1 = Koha::Patron::Attribute::Type->new({
1588 description => 'Code A desciption',
1591 my $attribute_type2 = Koha::Patron::Attribute::Type->new({
1593 description => 'Code A desciption',
1596 $attribute_type2->library_limits ( [ $library2->branchcode ] );
1598 Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type1->code, attribute => 'value 1' } )->store();
1599 Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type2->code, attribute => 'value 2' } )->store();
1601 is( $patron->attributes->count, 1, 'There should be one attribute');
1603 $attribute_type2->library_limits ( [ $library1->branchcode ] );
1605 is( $patron->attributes->count, 2, 'There should be 2 attributes');
1610 $nb_of_patrons = Koha::Patrons->search->count;
1611 $retrieved_patron_1->delete;
1612 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1614 subtest 'BorrowersLog tests' => sub {
1617 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1618 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1620 my $cardnumber = $patron->cardnumber;
1621 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1624 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1625 my $log_info = from_json( $logs[0]->info );
1626 is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1627 is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1628 is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1630 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1631 $patron->track_login();
1632 @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1633 is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1636 $schema->storage->txn_rollback;
1638 subtest 'Test Koha::Patrons::merge' => sub {
1641 my $schema = Koha::Database->new()->schema();
1643 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1645 $schema->storage->txn_begin;
1647 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1648 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1649 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1651 while (my ($r, $field) = each(%$resultsets)) {
1652 $builder->build({ source => $r, value => { $field => $keeper->id } });
1653 $builder->build({ source => $r, value => { $field => $loser_1 } });
1654 $builder->build({ source => $r, value => { $field => $loser_2 } });
1657 $schema->resultset($r)->search( { $field => $keeper->id } );
1658 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1661 $schema->resultset($r)->search( { $field => $loser_1 } );
1662 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1665 $schema->resultset($r)->search( { $field => $loser_2 } );
1666 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1669 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1671 while (my ($r, $field) = each(%$resultsets)) {
1673 $schema->resultset($r)->search( {$field => $keeper->id } );
1674 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1677 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1678 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1680 $schema->storage->txn_rollback;
1683 subtest '->store' => sub {
1685 my $schema = Koha::Database->new->schema;
1686 $schema->storage->txn_begin;
1688 my $print_error = $schema->storage->dbh->{PrintError};
1689 $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1691 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1692 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1695 { $patron_2->userid($patron_1->userid)->store; }
1696 'Koha::Exceptions::Object::DuplicateID',
1697 'Koha::Patron->store raises an exception on duplicate ID';
1700 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1701 my $password = 'password';
1702 $patron_1->set_password({ password => $password });
1703 like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1704 my $digest = $patron_1->password;
1705 $patron_1->surname('xxx')->store;
1706 is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1708 # Test uppercasesurnames
1709 t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 );
1710 my $surname = lc $patron_1->surname;
1711 $patron_1->surname($surname)->store;
1712 isnt( $patron_1->surname, $surname,
1713 'Surname converts to uppercase on store.');
1714 t::lib::Mocks::mock_preference( 'uppercasesurnames', 0 );
1715 $patron_1->surname($surname)->store;
1716 is( $patron_1->surname, $surname,
1717 'Surname remains unchanged on store.');
1720 $patron_1->relationship("")->store;
1721 is( $patron_1->relationship, undef, );
1723 $schema->storage->dbh->{PrintError} = $print_error;
1724 $schema->storage->txn_rollback;
1726 subtest 'skip updated_on for BorrowersLog' => sub {
1728 $schema->storage->txn_begin;
1729 t::lib::Mocks::mock_preference('BorrowersLog', 1);
1730 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1731 $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1732 my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1733 is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1734 $schema->storage->txn_rollback;
1738 subtest '->set_password' => sub {
1742 $schema->storage->txn_begin;
1744 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1746 # Disable logging password changes for this tests
1747 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1749 # Password-length tests
1750 t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1751 throws_ok { $patron->set_password({ password => 'ab' }); }
1752 'Koha::Exceptions::Password::TooShort',
1753 'minPasswordLength is undef, fall back to 3, fail test';
1755 'Password length (2) is shorter than required (3)',
1756 'Exception parameters passed correctly'
1759 t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1760 throws_ok { $patron->set_password({ password => 'ab' }); }
1761 'Koha::Exceptions::Password::TooShort',
1762 'minPasswordLength is 2, fall back to 3, fail test';
1764 t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1765 throws_ok { $patron->set_password({ password => 'abcb' }); }
1766 'Koha::Exceptions::Password::TooShort',
1767 'minPasswordLength is 5, fail test';
1769 # Trailing spaces tests
1770 throws_ok { $patron->set_password({ password => 'abcD12d ' }); }
1771 'Koha::Exceptions::Password::WhitespaceCharacters',
1772 'Password contains trailing spaces, exception is thrown';
1774 # Require strong password tests
1775 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1776 throws_ok { $patron->set_password({ password => 'abcd a' }); }
1777 'Koha::Exceptions::Password::TooWeak',
1778 'Password is too weak, exception is thrown';
1780 # Refresh patron from DB, just to make sure
1781 $patron->discard_changes;
1782 is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1784 $patron->set_password({ password => 'abcD12 34' });
1785 $patron->discard_changes;
1787 is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1789 lives_ok { $patron->set_password({ password => 'abcd a', skip_validation => 1 }) }
1790 'Password is weak, but skip_validation was passed, so no exception thrown';
1793 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1794 $patron->login_attempts(3)->store;
1795 my $old_digest = $patron->password;
1796 $patron->set_password({ password => 'abcd a' });
1797 $patron->discard_changes;
1799 isnt( $patron->password, $old_digest, 'Password has been updated' );
1800 ok( checkpw_hash('abcd a', $patron->password), 'Password hash is correct' );
1801 is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1803 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1804 is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1806 # Enable logging password changes
1807 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1808 $patron->set_password({ password => 'abcd b' });
1810 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1811 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1813 $schema->storage->txn_rollback;
1816 $schema->storage->txn_begin;
1817 subtest 'search_unsubscribed' => sub {
1820 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1821 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
1822 is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
1824 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1825 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1827 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
1828 Koha::Patron::Consents->delete; # for correct counts
1829 Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string })->store;
1830 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
1832 # Add another refusal but shift the period
1833 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
1834 Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string->subtract(days=>2) })->store;
1835 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
1837 # Try another (special) attempts setting
1838 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
1839 # Lockout is now disabled
1840 # Patron2 still matches: refused earlier, not locked
1841 is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
1844 subtest 'search_anonymize_candidates' => sub {
1846 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1847 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1848 $patron1->anonymized(0);
1849 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1850 $patron2->anonymized(0);
1851 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1853 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
1854 is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
1856 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
1857 my $cnt = Koha::Patrons->search_anonymize_candidates->count;
1858 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1859 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1860 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
1862 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
1863 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1864 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1865 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1866 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1867 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1868 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
1870 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
1871 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1872 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1873 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1874 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1875 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1876 is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
1878 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1879 $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1880 $patron1->login_attempts(0)->store;
1881 $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1882 $patron2->login_attempts(0)->store;
1883 $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
1884 $patron1->login_attempts(3)->store;
1885 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1886 $cnt+1, 'Locked flag' );
1888 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1889 # Patron 1 still on 3 == locked
1890 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1891 $cnt+1, 'Still expect same number for FailedLoginAttempts empty' );
1892 $patron1->login_attempts(0)->store;
1894 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1895 $cnt, 'Patron 1 unlocked' );
1898 subtest 'search_anonymized' => sub {
1900 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1902 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
1903 is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
1905 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
1906 $patron1->dateexpiry( dt_from_string );
1907 $patron1->anonymized(0)->store;
1908 my $cnt = Koha::Patrons->search_anonymized->count;
1909 $patron1->anonymized(1)->store;
1910 is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
1911 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1912 is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
1915 subtest 'lock' => sub {
1918 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1919 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1920 my $hold = $builder->build_object({
1921 class => 'Koha::Holds',
1922 value => { borrowernumber => $patron1->borrowernumber },
1925 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1926 my $expiry = dt_from_string->add(days => 1);
1927 $patron1->dateexpiry( $expiry );
1929 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1930 is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
1931 is( $patron1->holds->count, 1, 'No holds removed' );
1933 $patron1->lock({ expire => 1, remove => 1});
1934 isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
1935 is( $patron1->holds->count, 0, 'Holds removed' );
1937 # Disable lockout feature
1938 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1939 $patron1->login_attempts(0);
1940 $patron1->dateexpiry( $expiry );
1943 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1945 # Trivial wrapper test (Koha::Patrons->lock)
1946 $patron1->login_attempts(0)->store;
1947 Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
1948 $patron1->discard_changes; # refresh
1949 $patron2->discard_changes;
1950 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
1951 is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
1954 subtest 'anonymize' => sub {
1957 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1958 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1960 # First try patron with issues
1961 my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
1962 warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
1965 t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
1966 my $surname = $patron1->surname; # expect change, no clear
1967 my $branchcode = $patron1->branchcode; # expect skip
1968 $patron1->anonymize;
1969 is($patron1->anonymized, 1, 'Check flag' );
1971 is( $patron1->dateofbirth, undef, 'Birth date cleared' );
1972 is( $patron1->firstname, undef, 'First name cleared' );
1973 isnt( $patron1->surname, $surname, 'Surname changed' );
1974 ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
1975 is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
1976 is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
1978 # Test wrapper in Koha::Patrons
1979 $patron1->surname($surname)->store; # restore
1980 my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
1981 $patron1->discard_changes; # refresh
1982 isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
1983 $patron2->discard_changes; # refresh
1984 is( $patron2->firstname, undef, 'First name patron2 cleared' );
1986 $schema->storage->txn_rollback;