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;
33 use C4::Auth qw(checkpw_hash);
39 use Koha::Old::Patrons;
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( ref($deleted), 'Koha::Patron', 'Koha::Patron->delete should return the deleted patron object 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 $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
501 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
502 my $id1 = $patron1->borrowernumber;
503 my $set = Koha::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
504 is( $set->count, 2, 'Two patrons found as expected' );
505 is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
506 my $deleted_patrons = Koha::Old::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
507 is( $deleted_patrons->count, 2, 'Patrons moved to deletedborrowers' );
509 # See other tests in t/db_dependent/Koha/Objects.t
512 subtest 'add_enrolment_fee_if_needed' => sub {
515 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
516 foreach( keys %{$enrolmentfees} ) {
517 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
519 my $enrolmentfee_K = $enrolmentfees->{K};
520 my $enrolmentfee_J = $enrolmentfees->{J};
521 my $enrolmentfee_YA = $enrolmentfees->{YA};
523 my %borrower_data = (
524 firstname => 'my firstname',
525 surname => 'my surname',
527 branchcode => $library->{branchcode},
530 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
531 $borrower_data{borrowernumber} = $borrowernumber;
533 my $patron = Koha::Patrons->find( $borrowernumber );
534 my $total = $patron->account->balance;
535 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
537 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
538 $borrower_data{categorycode} = 'J';
539 $patron->set(\%borrower_data)->store;
540 $total = $patron->account->balance;
541 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
543 $borrower_data{categorycode} = 'K';
544 $patron->set(\%borrower_data)->store;
545 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
547 $borrower_data{categorycode} = 'J';
548 $patron->set(\%borrower_data)->store;
549 $total = $patron->account->balance;
550 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
552 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
553 $patron->categorycode('YA')->store;
554 $total = $patron->account->balance;
556 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
557 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
563 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
566 my $library = $builder->build( { source => 'Branch' } );
567 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
568 my $item_1 = $builder->build(
572 homebranch => $library->{branchcode},
573 holdingbranch => $library->{branchcode},
574 biblionumber => $biblionumber_1,
580 my $item_2 = $builder->build(
584 homebranch => $library->{branchcode},
585 holdingbranch => $library->{branchcode},
586 biblionumber => $biblionumber_1,
592 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
593 my $item_3 = $builder->build(
597 homebranch => $library->{branchcode},
598 holdingbranch => $library->{branchcode},
599 biblionumber => $biblionumber_2,
605 my $patron = $builder->build(
607 source => 'Borrower',
608 value => { branchcode => $library->{branchcode} }
612 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
613 my $checkouts = $patron->checkouts;
614 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
615 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
616 my $pending_checkouts = $patron->pending_checkouts;
617 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
618 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
619 my $old_checkouts = $patron->old_checkouts;
620 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
621 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
623 # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
624 $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
626 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
628 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
629 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
630 AddIssue( $patron, $item_3->{barcode} );
632 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
633 $checkouts = $patron->checkouts;
634 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
635 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
636 $pending_checkouts = $patron->pending_checkouts;
637 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
638 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
640 my $first_checkout = $pending_checkouts->next;
641 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
643 my $overdues = $patron->get_overdues;
644 is( $overdues->count, 2, 'Patron should have 2 overdues');
645 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
646 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
647 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
650 C4::Circulation::AddReturn( $item_1->{barcode} );
651 C4::Circulation::AddReturn( $item_2->{barcode} );
652 $old_checkouts = $patron->old_checkouts;
653 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
654 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
657 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
661 subtest 'get_routing_lists' => sub {
664 my $biblio = Koha::Biblio->new()->store();
665 my $subscription = Koha::Subscription->new({
666 biblionumber => $biblio->biblionumber,
670 my $patron = $builder->build( { source => 'Borrower' } );
671 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
673 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
675 my $routinglist_count = Koha::Subscription::Routinglists->count;
676 my $routinglist = Koha::Subscription::Routinglist->new({
677 borrowernumber => $patron->borrowernumber,
679 subscriptionid => $subscription->subscriptionid
682 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
684 my $routinglists = $patron->get_routing_lists;
685 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
686 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
688 my $subscription2 = Koha::Subscription->new({
689 biblionumber => $biblio->biblionumber,
692 my $routinglist2 = Koha::Subscription::Routinglist->new({
693 borrowernumber => $patron->borrowernumber,
695 subscriptionid => $subscription2->subscriptionid
698 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
700 $patron->delete; # Clean up for later tests
704 subtest 'get_age' => sub {
707 my $patron = $builder->build( { source => 'Borrower' } );
708 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
710 my $today = dt_from_string;
712 $patron->dateofbirth( undef );
713 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
714 $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1, end_of_month => 'limit' ) );
715 is( $patron->get_age, 12, 'Patron should be 12' );
716 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 1, end_of_month => 'limit' ) );
717 is( $patron->get_age, 17, 'Patron should be 17, happy birthday tomorrow!' );
718 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 0, end_of_month => 'limit' ) );
719 is( $patron->get_age, 18, 'Patron should be 18' );
720 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -31, end_of_month => 'limit' ) );
721 is( $patron->get_age, 19, 'Patron should be 19' );
722 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -30, end_of_month => 'limit' ) );
723 is( $patron->get_age, 19, 'Patron should be 19 again' );
724 $patron->dateofbirth( $today->clone->add( years => 0, months => -1, days => -1, end_of_month => 'limit' ) );
725 is( $patron->get_age, 0, 'Patron is a newborn child' );
730 subtest 'is_valid_age' => sub {
733 my $today = dt_from_string;
735 my $category = $builder->build({
736 source => 'Category',
738 categorycode => 'AGE_5_10',
739 dateofbirthrequired => 5,
743 $category = Koha::Patron::Categories->find( $category->{categorycode} );
745 my $patron = $builder->build({
746 source => 'Borrower',
748 categorycode => 'AGE_5_10'
751 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
754 $patron->dateofbirth( undef );
755 is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
757 $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1 ) );
758 is( $patron->is_valid_age, 0, 'Patron is 12, so the age is above allowed range 5-10 years');
760 $patron->dateofbirth( $today->clone->add( years => -3, months => -6, days => -1 ) );
761 is( $patron->is_valid_age, 0, 'Patron is 3, so the age is below allowed range 5-10 years');
763 $patron->dateofbirth( $today->clone->add( years => -7, months => -6, days => -1 ) );
764 is( $patron->is_valid_age, 1, 'Patron is 7, so the age perfectly suits allowed range 5-10 years');
766 $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => 0 ) );
767 is( $patron->is_valid_age, 1, 'Patron celebrates the 5th birthday today, so the age is allowed for this category');
769 $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => 1 ) );
770 is( $patron->is_valid_age, 0, 'Patron will celebrate the 5th birthday tomorrow, so the age is NOT allowed for this category');
772 $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => -1 ) );
773 is( $patron->is_valid_age, 1, 'Patron celebrated the 5th birthday yesterday, so the age is allowed for this category');
775 $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => 0 ) );
776 is( $patron->is_valid_age, 0, 'Patron celebrate the 11th birthday today, so the age is NOT allowed for this category');
778 $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => 1 ) );
779 is( $patron->is_valid_age, 1, 'Patron will celebrate the 11th birthday tomorrow, so the age is allowed for this category');
781 $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => -1 ) );
782 is( $patron->is_valid_age, 0, 'Patron celebrated the 11th birthday yesterday, so the age is NOT allowed for this category');
788 subtest 'account' => sub {
791 my $patron = $builder->build({source => 'Borrower'});
793 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
794 my $account = $patron->account;
795 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
800 subtest 'search_upcoming_membership_expires' => sub {
803 my $expiry_days = 15;
804 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
805 my $nb_of_days_before = 1;
806 my $nb_of_days_after = 2;
808 my $builder = t::lib::TestBuilder->new();
810 my $library = $builder->build({ source => 'Branch' });
812 # before we add borrowers to this branch, add the expires we have now
813 # note that this pertains to the current mocked setting of the pref
814 # for this reason we add the new branchcode to most of the tests
815 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
817 my $patron_1 = $builder->build({
818 source => 'Borrower',
820 branchcode => $library->{branchcode},
821 dateexpiry => dt_from_string->add( days => $expiry_days )
825 my $patron_2 = $builder->build({
826 source => 'Borrower',
828 branchcode => $library->{branchcode},
829 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
833 my $patron_3 = $builder->build({
834 source => 'Borrower',
836 branchcode => $library->{branchcode},
837 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
841 # Test without extra parameters
842 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
843 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
846 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
847 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
848 my $expired = $upcoming_mem_expires->next;
849 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
850 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
851 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
853 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
854 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
855 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
857 # Test MembershipExpiryDaysNotice == undef
858 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
859 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
860 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
862 # Test the before parameter
863 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
864 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
865 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
866 # Test after parameter also
867 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
868 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
869 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
872 subtest 'holds and old_holds' => sub {
875 my $library = $builder->build( { source => 'Branch' } );
876 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
877 my $item_1 = $builder->build(
881 homebranch => $library->{branchcode},
882 holdingbranch => $library->{branchcode},
883 biblionumber => $biblionumber_1
887 my $item_2 = $builder->build(
891 homebranch => $library->{branchcode},
892 holdingbranch => $library->{branchcode},
893 biblionumber => $biblionumber_1
897 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
898 my $item_3 = $builder->build(
902 homebranch => $library->{branchcode},
903 holdingbranch => $library->{branchcode},
904 biblionumber => $biblionumber_2
908 my $patron = $builder->build(
910 source => 'Borrower',
911 value => { branchcode => $library->{branchcode} }
915 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
916 my $holds = $patron->holds;
917 is( ref($holds), 'Koha::Holds',
918 'Koha::Patron->holds should return a Koha::Holds objects' );
919 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
921 C4::Reserves::AddReserve( $library->{branchcode},
922 $patron->borrowernumber, $biblionumber_1 );
924 C4::Reserves::AddReserve( $library->{branchcode},
925 $patron->borrowernumber, $biblionumber_2, undef, undef, dt_from_string->add( days => 2 ) );
927 $holds = $patron->holds;
928 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
930 my $old_holds = $patron->old_holds;
931 is( ref($old_holds), 'Koha::Old::Holds',
932 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
933 is( $old_holds->count, 0, 'There should not be any old holds yet');
935 my $hold = $holds->next;
938 $old_holds = $patron->old_holds;
939 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
946 subtest 'notice_email_address' => sub {
949 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
951 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
952 is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
954 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
955 is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
960 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
963 # TODO create a subroutine in t::lib::Mocks
964 my $branch = $builder->build({ source => 'Branch' });
965 my $userenv_patron = $builder->build_object({
966 class => 'Koha::Patrons',
967 value => { branchcode => $branch->{branchcode}, flags => 0 },
969 t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
971 my $anonymous = $builder->build( { source => 'Borrower', }, );
973 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
975 subtest 'patron privacy is 1 (default)' => sub {
978 t::lib::Mocks::mock_preference('IndependentBranches', 0);
979 my $patron = $builder->build(
980 { source => 'Borrower',
981 value => { privacy => 1, }
984 my $item_1 = $builder->build(
992 my $issue_1 = $builder->build(
995 borrowernumber => $patron->{borrowernumber},
996 itemnumber => $item_1->{itemnumber},
1000 my $item_2 = $builder->build(
1008 my $issue_2 = $builder->build(
1009 { source => 'Issue',
1011 borrowernumber => $patron->{borrowernumber},
1012 itemnumber => $item_2->{itemnumber},
1017 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1018 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, dt_from_string('2011-11-11') );
1019 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
1021 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
1022 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
1024 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
1025 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1027 $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1028 is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
1030 my $dbh = C4::Context->dbh;
1031 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
1032 $sth->execute($item_1->{itemnumber});
1033 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1034 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
1035 $sth->execute($item_2->{itemnumber});
1036 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1037 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
1039 $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
1040 $sth->execute($item_2->{itemnumber});
1041 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1042 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
1044 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
1045 $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
1046 $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
1047 $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
1048 $sth->execute($item_1->{itemnumber});
1049 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1050 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
1051 $sth->execute($item_2->{itemnumber});
1052 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1053 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
1055 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1058 subtest 'patron privacy is 0 (forever)' => sub {
1061 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1062 my $patron = $builder->build(
1063 { source => 'Borrower',
1064 value => { privacy => 0, }
1067 my $item = $builder->build(
1075 my $issue = $builder->build(
1076 { source => 'Issue',
1078 borrowernumber => $patron->{borrowernumber},
1079 itemnumber => $item->{itemnumber},
1084 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1085 is( $returned, 1, 'The item should have been returned' );
1087 my $dbh = C4::Context->dbh;
1088 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1089 SELECT borrowernumber FROM old_issues where itemnumber = ?
1090 |, undef, $item->{itemnumber});
1091 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1092 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1095 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1097 subtest 'AnonymousPatron is not defined' => sub {
1100 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1101 my $patron = $builder->build(
1102 { source => 'Borrower',
1103 value => { privacy => 1, }
1106 my $item = $builder->build(
1114 my $issue = $builder->build(
1115 { source => 'Issue',
1117 borrowernumber => $patron->{borrowernumber},
1118 itemnumber => $item->{itemnumber},
1123 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1124 is( $returned, 1, 'The item should have been returned' );
1125 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
1126 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1128 my $dbh = C4::Context->dbh;
1129 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1130 SELECT borrowernumber FROM old_issues where itemnumber = ?
1131 |, undef, $item->{itemnumber});
1132 is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
1133 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1136 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1138 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1139 my $patron = $builder->build(
1140 { source => 'Borrower',
1141 value => { privacy => 1 } # Another branchcode than the logged in librarian
1144 my $item = $builder->build(
1152 my $issue = $builder->build(
1153 { source => 'Issue',
1155 borrowernumber => $patron->{borrowernumber},
1156 itemnumber => $item->{itemnumber},
1161 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1162 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1163 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1166 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1167 $userenv_patron->delete;
1169 # Reset IndependentBranches for further tests
1170 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1173 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1181 $nb_of_patrons = Koha::Patrons->search->count;
1182 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1183 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1184 my $library_11 = $builder->build( { source => 'Branch' } );
1185 my $library_12 = $builder->build( { source => 'Branch' } );
1186 my $library_21 = $builder->build( { source => 'Branch' } );
1187 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1188 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1189 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1190 Koha::Library::Group->new(
1191 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1192 Koha::Library::Group->new(
1193 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1194 Koha::Library::Group->new(
1195 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1197 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1198 # 2 patrons from library_11 (group1)
1199 # patron_11_1 see patron's infos from outside its group
1200 # Setting flags => undef to not be considered as superlibrarian
1201 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1202 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1203 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1204 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1205 # patron_11_2 can only see patron's info from its group
1206 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1207 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1208 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1209 # 1 patron from library_12 (group1)
1210 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1211 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1212 # 1 patron from library_21 (group2) can only see patron's info from its group
1213 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1214 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1215 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1217 # Pfiou, we can start now!
1218 subtest 'libraries_where_can_see_patrons' => sub {
1223 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1224 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1225 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1227 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1228 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1229 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| );
1231 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1232 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1233 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| );
1235 subtest 'can_see_patron_infos' => sub {
1238 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1239 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1240 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1241 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1243 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1244 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1245 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1246 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1248 subtest 'search_limited' => sub {
1251 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1252 my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1253 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1254 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1256 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1257 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1258 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' );
1260 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1261 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1262 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1264 $patron_11_1->delete;
1265 $patron_11_2->delete;
1270 subtest 'account_locked' => sub {
1272 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1273 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1274 for my $value ( undef, '', 0 ) {
1275 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1276 $patron->login_attempts(0)->store;
1277 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1278 $patron->login_attempts(1)->store;
1279 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1280 $patron->login_attempts(-1)->store;
1281 is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1284 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1285 $patron->login_attempts(2)->store;
1286 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1287 $patron->login_attempts(3)->store;
1288 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1289 $patron->login_attempts(4)->store;
1290 is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1291 $patron->login_attempts(-1)->store;
1292 is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1297 subtest 'is_child | is_adult' => sub {
1299 my $category = $builder->build_object(
1301 class => 'Koha::Patron::Categories',
1302 value => { category_type => 'A' }
1305 my $patron_adult = $builder->build_object(
1307 class => 'Koha::Patrons',
1308 value => { categorycode => $category->categorycode }
1311 $category = $builder->build_object(
1313 class => 'Koha::Patron::Categories',
1314 value => { category_type => 'I' }
1317 my $patron_adult_i = $builder->build_object(
1319 class => 'Koha::Patrons',
1320 value => { categorycode => $category->categorycode }
1323 $category = $builder->build_object(
1325 class => 'Koha::Patron::Categories',
1326 value => { category_type => 'C' }
1329 my $patron_child = $builder->build_object(
1331 class => 'Koha::Patrons',
1332 value => { categorycode => $category->categorycode }
1335 $category = $builder->build_object(
1337 class => 'Koha::Patron::Categories',
1338 value => { category_type => 'O' }
1341 my $patron_other = $builder->build_object(
1343 class => 'Koha::Patrons',
1344 value => { categorycode => $category->categorycode }
1347 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1348 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1349 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1350 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1352 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1353 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1354 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1355 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1358 $patron_adult->delete;
1359 $patron_adult_i->delete;
1360 $patron_child->delete;
1361 $patron_other->delete;
1364 subtest 'get_overdues' => sub {
1367 my $library = $builder->build( { source => 'Branch' } );
1368 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1369 my $item_1 = $builder->build(
1373 homebranch => $library->{branchcode},
1374 holdingbranch => $library->{branchcode},
1375 biblionumber => $biblionumber_1
1379 my $item_2 = $builder->build(
1383 homebranch => $library->{branchcode},
1384 holdingbranch => $library->{branchcode},
1385 biblionumber => $biblionumber_1
1389 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1390 my $item_3 = $builder->build(
1394 homebranch => $library->{branchcode},
1395 holdingbranch => $library->{branchcode},
1396 biblionumber => $biblionumber_2
1400 my $patron = $builder->build(
1402 source => 'Borrower',
1403 value => { branchcode => $library->{branchcode} }
1407 t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1409 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1410 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1411 AddIssue( $patron, $item_3->{barcode} );
1413 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1414 my $overdues = $patron->get_overdues;
1415 is( $overdues->count, 2, 'Patron should have 2 overdues');
1416 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1417 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1419 my $o = $overdues->reset->next;
1420 my $unblessed_overdue = $o->unblessed_all_relateds;
1421 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1422 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1423 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1424 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1427 $patron->checkouts->delete;
1431 subtest 'userid_is_valid' => sub {
1434 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1435 my $patron_category = $builder->build_object(
1437 class => 'Koha::Patron::Categories',
1438 value => { category_type => 'P', enrolmentfee => 0 }
1442 cardnumber => "123456789",
1443 firstname => "Tomasito",
1445 categorycode => $patron_category->categorycode,
1446 branchcode => $library->branchcode,
1449 my $expected_userid_patron_1 = 'tomasito.none';
1450 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1451 my $patron_1 = Koha::Patrons->find($borrowernumber);
1452 is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1453 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1455 $patron_1->userid( 'tomasito.non' );
1456 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1457 1, 'recently created userid -> unique (borrowernumber passed)' );
1459 $patron_1->userid( 'tomasitoxxx' );
1460 is( $patron_1->has_valid_userid,
1461 1, 'non-existent userid -> unique (borrowernumber passed)' );
1462 $patron_1->discard_changes; # We compare with the original userid later
1464 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1465 is( $patron_not_in_storage->has_valid_userid,
1466 0, 'userid exists for another patron, patron is not in storage yet' );
1468 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1469 is( $patron_not_in_storage->has_valid_userid,
1470 1, 'non-existent userid, patron is not in storage yet' );
1472 # Regression tests for BZ12226
1473 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1474 is( $db_patron->has_valid_userid,
1475 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1477 # Add a new borrower with the same userid but different cardnumber
1478 $data{cardnumber} = "987654321";
1479 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1480 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1481 $patron_2->userid($patron_1->userid);
1482 is( $patron_2->has_valid_userid,
1483 0, 'The userid is already in used, it cannot be used for another patron' );
1485 my $new_userid = 'a_user_id';
1486 $data{cardnumber} = "234567890";
1487 $data{userid} = 'a_user_id';
1488 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1489 my $patron_3 = Koha::Patrons->find($borrowernumber);
1490 is( $patron_3->userid, $new_userid,
1491 'Koha::Patron->store should insert the given userid' );
1499 subtest 'generate_userid' => sub {
1502 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1503 my $patron_category = $builder->build_object(
1505 class => 'Koha::Patron::Categories',
1506 value => { category_type => 'P', enrolmentfee => 0 }
1510 cardnumber => "123456789",
1511 firstname => "Tomasito",
1513 categorycode => $patron_category->categorycode,
1514 branchcode => $library->branchcode,
1517 my $expected_userid_patron_1 = 'tomasito.none';
1518 my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1519 $new_patron->generate_userid;
1520 my $userid = $new_patron->userid;
1521 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1522 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1523 my $patron_1 = Koha::Patrons->find($borrowernumber);
1524 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1526 $new_patron->generate_userid;
1527 $userid = $new_patron->userid;
1528 is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1529 $data{cardnumber} = '987654321';
1530 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1531 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1532 isnt( $patron_2->userid, 'tomasito',
1533 "Patron with duplicate userid has new userid generated" );
1534 is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1535 "Patron with duplicate userid has new userid generated (1 is appened" );
1537 $new_patron->generate_userid;
1538 $userid = $new_patron->userid;
1539 is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1541 $patron_1 = Koha::Patrons->find($borrowernumber);
1542 $patron_1->userid(undef);
1543 $patron_1->generate_userid;
1544 $userid = $patron_1->userid;
1545 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1552 subtest 'attributes' => sub {
1555 my $library1 = Koha::Library->new({
1556 branchcode => 'LIBPATRON',
1557 branchname => 'Library of testing patron',
1560 my $library2 = Koha::Library->new({
1561 branchcode => 'LIBATTR',
1562 branchname => 'Library for testing attribute',
1565 my $category = Koha::Patron::Category->new({
1566 categorycode => 'CAT1',
1567 description => 'Category 1',
1570 my $patron = Koha::Patron->new({
1571 firstname => 'Patron',
1572 surname => 'with attributes',
1573 branchcode => 'LIBPATRON',
1574 categorycode => 'CAT1',
1577 my $attribute_type1 = Koha::Patron::Attribute::Type->new({
1579 description => 'Code A desciption',
1582 my $attribute_type2 = Koha::Patron::Attribute::Type->new({
1584 description => 'Code A desciption',
1587 $attribute_type2->library_limits ( [ $library2->branchcode ] );
1589 Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type1->code, attribute => 'value 1' } )->store();
1590 Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type2->code, attribute => 'value 2' } )->store();
1592 is( $patron->attributes->count, 1, 'There should be one attribute');
1594 $attribute_type2->library_limits ( [ $library1->branchcode ] );
1596 is( $patron->attributes->count, 2, 'There should be 2 attributes');
1601 $nb_of_patrons = Koha::Patrons->search->count;
1602 $retrieved_patron_1->delete;
1603 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1605 subtest 'BorrowersLog tests' => sub {
1608 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1609 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1611 my $cardnumber = $patron->cardnumber;
1612 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1615 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1616 my $log_info = from_json( $logs[0]->info );
1617 is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1618 is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1619 is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1621 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1622 $patron->track_login();
1623 @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1624 is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1627 $schema->storage->txn_rollback;
1629 subtest 'Test Koha::Patrons::merge' => sub {
1632 my $schema = Koha::Database->new()->schema();
1634 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1636 $schema->storage->txn_begin;
1638 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1639 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1640 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1642 while (my ($r, $field) = each(%$resultsets)) {
1643 $builder->build({ source => $r, value => { $field => $keeper->id } });
1644 $builder->build({ source => $r, value => { $field => $loser_1 } });
1645 $builder->build({ source => $r, value => { $field => $loser_2 } });
1648 $schema->resultset($r)->search( { $field => $keeper->id } );
1649 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1652 $schema->resultset($r)->search( { $field => $loser_1 } );
1653 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1656 $schema->resultset($r)->search( { $field => $loser_2 } );
1657 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1660 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1662 while (my ($r, $field) = each(%$resultsets)) {
1664 $schema->resultset($r)->search( {$field => $keeper->id } );
1665 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1668 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1669 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1671 $schema->storage->txn_rollback;
1674 subtest '->store' => sub {
1676 my $schema = Koha::Database->new->schema;
1677 $schema->storage->txn_begin;
1679 my $print_error = $schema->storage->dbh->{PrintError};
1680 $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1682 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1683 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1686 { $patron_2->userid($patron_1->userid)->store; }
1687 'Koha::Exceptions::Object::DuplicateID',
1688 'Koha::Patron->store raises an exception on duplicate ID';
1691 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1692 my $password = 'password';
1693 $patron_1->set_password({ password => $password });
1694 like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1695 my $digest = $patron_1->password;
1696 $patron_1->surname('xxx')->store;
1697 is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1699 # Test uppercasesurnames
1700 t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 );
1701 my $surname = lc $patron_1->surname;
1702 $patron_1->surname($surname)->store;
1703 isnt( $patron_1->surname, $surname,
1704 'Surname converts to uppercase on store.');
1705 t::lib::Mocks::mock_preference( 'uppercasesurnames', 0 );
1706 $patron_1->surname($surname)->store;
1707 is( $patron_1->surname, $surname,
1708 'Surname remains unchanged on store.');
1711 $patron_1->relationship("")->store;
1712 is( $patron_1->relationship, undef, );
1714 $schema->storage->dbh->{PrintError} = $print_error;
1715 $schema->storage->txn_rollback;
1717 subtest 'skip updated_on for BorrowersLog' => sub {
1719 $schema->storage->txn_begin;
1720 t::lib::Mocks::mock_preference('BorrowersLog', 1);
1721 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1722 $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1723 my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1724 is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1725 $schema->storage->txn_rollback;
1729 subtest '->set_password' => sub {
1733 $schema->storage->txn_begin;
1735 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1737 # Disable logging password changes for this tests
1738 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1740 # Password-length tests
1741 t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1742 throws_ok { $patron->set_password({ password => 'ab' }); }
1743 'Koha::Exceptions::Password::TooShort',
1744 'minPasswordLength is undef, fall back to 3, fail test';
1746 'Password length (2) is shorter than required (3)',
1747 'Exception parameters passed correctly'
1750 t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1751 throws_ok { $patron->set_password({ password => 'ab' }); }
1752 'Koha::Exceptions::Password::TooShort',
1753 'minPasswordLength is 2, fall back to 3, fail test';
1755 t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1756 throws_ok { $patron->set_password({ password => 'abcb' }); }
1757 'Koha::Exceptions::Password::TooShort',
1758 'minPasswordLength is 5, fail test';
1760 # Trailing spaces tests
1761 throws_ok { $patron->set_password({ password => 'abcD12d ' }); }
1762 'Koha::Exceptions::Password::WhitespaceCharacters',
1763 'Password contains trailing spaces, exception is thrown';
1765 # Require strong password tests
1766 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1767 throws_ok { $patron->set_password({ password => 'abcd a' }); }
1768 'Koha::Exceptions::Password::TooWeak',
1769 'Password is too weak, exception is thrown';
1771 # Refresh patron from DB, just to make sure
1772 $patron->discard_changes;
1773 is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1775 $patron->set_password({ password => 'abcD12 34' });
1776 $patron->discard_changes;
1778 is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1780 lives_ok { $patron->set_password({ password => 'abcd a', skip_validation => 1 }) }
1781 'Password is weak, but skip_validation was passed, so no exception thrown';
1784 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1785 $patron->login_attempts(3)->store;
1786 my $old_digest = $patron->password;
1787 $patron->set_password({ password => 'abcd a' });
1788 $patron->discard_changes;
1790 isnt( $patron->password, $old_digest, 'Password has been updated' );
1791 ok( checkpw_hash('abcd a', $patron->password), 'Password hash is correct' );
1792 is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1794 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1795 is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1797 # Enable logging password changes
1798 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1799 $patron->set_password({ password => 'abcd b' });
1801 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1802 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1804 $schema->storage->txn_rollback;
1807 $schema->storage->txn_begin;
1808 subtest 'search_unsubscribed' => sub {
1811 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1812 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
1813 is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
1815 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1816 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1818 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
1819 Koha::Patron::Consents->delete; # for correct counts
1820 Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string })->store;
1821 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
1823 # Add another refusal but shift the period
1824 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
1825 Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string->subtract(days=>2) })->store;
1826 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
1828 # Try another (special) attempts setting
1829 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
1830 # Lockout is now disabled
1831 # Patron2 still matches: refused earlier, not locked
1832 is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
1835 subtest 'search_anonymize_candidates' => sub {
1837 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1838 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1839 $patron1->anonymized(0);
1840 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1841 $patron2->anonymized(0);
1842 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1844 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
1845 is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
1847 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
1848 my $cnt = Koha::Patrons->search_anonymize_candidates->count;
1849 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1850 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1851 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
1853 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
1854 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1855 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1856 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1857 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1858 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1859 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
1861 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
1862 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1863 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1864 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1865 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1866 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1867 is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
1869 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1870 $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1871 $patron1->login_attempts(0)->store;
1872 $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1873 $patron2->login_attempts(0)->store;
1874 $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
1875 $patron1->login_attempts(3)->store;
1876 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1877 $cnt+1, 'Locked flag' );
1880 subtest 'search_anonymized' => sub {
1882 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1884 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
1885 is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
1887 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
1888 $patron1->dateexpiry( dt_from_string );
1889 $patron1->anonymized(0)->store;
1890 my $cnt = Koha::Patrons->search_anonymized->count;
1891 $patron1->anonymized(1)->store;
1892 is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
1893 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1894 is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
1897 subtest 'lock' => sub {
1900 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1901 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1902 my $hold = $builder->build_object({
1903 class => 'Koha::Holds',
1904 value => { borrowernumber => $patron1->borrowernumber },
1907 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1908 my $expiry = dt_from_string->add(days => 1);
1909 $patron1->dateexpiry( $expiry );
1911 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1912 is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
1913 is( $patron1->holds->count, 1, 'No holds removed' );
1915 $patron1->lock({ expire => 1, remove => 1});
1916 isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
1917 is( $patron1->holds->count, 0, 'Holds removed' );
1919 # Disable lockout feature
1920 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1921 $patron1->login_attempts(0);
1922 $patron1->dateexpiry( $expiry );
1925 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1927 # Trivial wrapper test (Koha::Patrons->lock)
1928 $patron1->login_attempts(0)->store;
1929 Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
1930 $patron1->discard_changes; # refresh
1931 $patron2->discard_changes;
1932 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
1933 is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
1936 subtest 'anonymize' => sub {
1939 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1940 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1942 # First try patron with issues
1943 my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
1944 warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
1947 t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
1948 my $surname = $patron1->surname; # expect change, no clear
1949 my $branchcode = $patron1->branchcode; # expect skip
1950 $patron1->anonymize;
1951 is($patron1->anonymized, 1, 'Check flag' );
1953 is( $patron1->dateofbirth, undef, 'Birth date cleared' );
1954 is( $patron1->firstname, undef, 'First name cleared' );
1955 isnt( $patron1->surname, $surname, 'Surname changed' );
1956 ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
1957 is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
1958 is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
1960 # Test wrapper in Koha::Patrons
1961 $patron1->surname($surname)->store; # restore
1962 my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
1963 $patron1->discard_changes; # refresh
1964 isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
1965 $patron2->discard_changes; # refresh
1966 is( $patron2->firstname, undef, 'First name patron2 cleared' );
1968 $schema->storage->txn_rollback;