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 => 4;
34 use C4::Auth qw(checkpw_hash);
40 use Koha::Old::Patrons;
41 use Koha::Patron::Categories;
42 use Koha::Patron::Relationship;
45 use Koha::Virtualshelves;
47 use t::lib::TestBuilder;
50 my $schema = Koha::Database->new->schema;
51 $schema->storage->txn_begin;
53 my $builder = t::lib::TestBuilder->new;
54 my $library = $builder->build({source => 'Branch' });
55 my $category = $builder->build({source => 'Category' });
56 my $nb_of_patrons = Koha::Patrons->search->count;
57 my $new_patron_1 = Koha::Patron->new(
58 { cardnumber => 'test_cn_1',
59 branchcode => $library->{branchcode},
60 categorycode => $category->{categorycode},
61 surname => 'surname for patron1',
62 firstname => 'firstname for patron1',
63 userid => 'a_nonexistent_userid_1',
64 flags => 1, # Is superlibrarian
67 my $new_patron_2 = Koha::Patron->new(
68 { cardnumber => 'test_cn_2',
69 branchcode => $library->{branchcode},
70 categorycode => $category->{categorycode},
71 surname => 'surname for patron2',
72 firstname => 'firstname for patron2',
73 userid => 'a_nonexistent_userid_2',
77 t::lib::Mocks::mock_userenv({ patron => $new_patron_1 });
79 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
81 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
82 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
84 subtest 'library' => sub {
86 is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
87 is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
90 subtest 'guarantees' => sub {
93 t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test|test2' );
95 my $guarantees = $new_patron_1->guarantee_relationships;
96 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
97 is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee relationships' );
98 my @guarantees = $new_patron_1->guarantee_relationships;
99 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantee_relationships should return an array in a list context' );
100 is( scalar(@guarantees), 0, 'new_patron_1 should have 0 guarantee' );
102 my $guarantee_1 = $builder->build({ source => 'Borrower' });
103 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
104 my $guarantee_2 = $builder->build({ source => 'Borrower' });
105 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
107 $guarantees = $new_patron_1->guarantee_relationships;
108 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantee_relationships should return a Koha::Patrons result set in a scalar context' );
109 is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
110 @guarantees = $new_patron_1->guarantee_relationships;
111 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantee_relationships should return an array in a list context' );
112 is( scalar(@guarantees), 2, 'new_patron_1 should have 2 guarantees' );
113 $_->delete for @guarantees;
115 #Test return order of guarantees BZ 18635
116 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
117 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
119 my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
121 my $order_guarantee1 = $builder->build_object(
123 class => 'Koha::Patrons',
129 $builder->build_object(
131 class => 'Koha::Patron::Relationships',
133 guarantor_id => $guarantor->id,
134 guarantee_id => $order_guarantee1,
135 relationship => 'test',
140 my $order_guarantee2 = $builder->build_object(
142 class => 'Koha::Patrons',
148 $builder->build_object(
150 class => 'Koha::Patron::Relationships',
152 guarantor_id => $guarantor->id,
153 guarantee_id => $order_guarantee2,
154 relationship => 'test',
159 my $order_guarantee3 = $builder->build_object(
161 class => 'Koha::Patrons',
164 firstname => 'Walrus',
168 $builder->build_object(
170 class => 'Koha::Patron::Relationships',
172 guarantor_id => $guarantor->id,
173 guarantee_id => $order_guarantee3,
174 relationship => 'test',
179 my $order_guarantee4 = $builder->build_object(
181 class => 'Koha::Patrons',
184 firstname => 'Vulture',
185 guarantorid => $guarantor->borrowernumber
189 $builder->build_object(
191 class => 'Koha::Patron::Relationships',
193 guarantor_id => $guarantor->id,
194 guarantee_id => $order_guarantee4,
195 relationship => 'test',
200 my $order_guarantee5 = $builder->build_object(
202 class => 'Koha::Patrons',
205 firstname => 'Unicorn',
206 guarantorid => $guarantor->borrowernumber
210 my $r = $builder->build_object(
212 class => 'Koha::Patron::Relationships',
214 guarantor_id => $guarantor->id,
215 guarantee_id => $order_guarantee5,
216 relationship => 'test',
221 $guarantees = $guarantor->guarantee_relationships->guarantees;
223 is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
224 is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
225 is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
226 is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
227 is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
230 subtest 'category' => sub {
232 my $patron_category = $new_patron_1->category;
233 is( ref( $patron_category), 'Koha::Patron::Category', );
234 is( $patron_category->categorycode, $category->{categorycode}, );
237 subtest 'siblings' => sub {
239 my $siblings = $new_patron_1->siblings;
240 is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
241 my $guarantee_1 = $builder->build( { source => 'Borrower' } );
242 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
243 my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
244 $siblings = $retrieved_guarantee_1->siblings;
245 is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
246 my @siblings = $retrieved_guarantee_1->siblings;
247 is( ref( \@siblings ), 'ARRAY', 'Koha::Patron->siblings should return an array in a list context' );
248 is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' );
249 my $guarantee_2 = $builder->build( { source => 'Borrower' } );
250 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
251 my $guarantee_3 = $builder->build( { source => 'Borrower' } );
252 my $relationship_3 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_3->{borrowernumber}, relationship => 'test' } )->store();
253 $siblings = $retrieved_guarantee_1->siblings;
254 is( $siblings->count, 2, 'guarantee_1 should have 2 siblings' );
255 is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
256 is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
257 $_->delete for $retrieved_guarantee_1->siblings;
258 $retrieved_guarantee_1->delete;
261 subtest 'has_overdues' => sub {
264 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
265 my $item_1 = $builder->build(
268 homebranch => $library->{branchcode},
269 holdingbranch => $library->{branchcode},
273 biblionumber => $biblioitem_1->{biblionumber}
277 my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
278 is( $retrieved_patron->has_overdues, 0, );
280 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
281 my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
282 is( $retrieved_patron->has_overdues, 0, );
284 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
285 $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
286 $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
287 is( $retrieved_patron->has_overdues, 1, );
291 subtest 'is_expired' => sub {
293 my $patron = $builder->build({ source => 'Borrower' });
294 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
295 $patron->dateexpiry( undef )->store->discard_changes;
296 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
297 $patron->dateexpiry( dt_from_string )->store->discard_changes;
298 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
299 $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
300 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
301 $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
302 is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
307 subtest 'is_going_to_expire' => sub {
310 my $today = dt_from_string(undef, undef, 'floating');
311 my $patron = $builder->build({ source => 'Borrower' });
312 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
313 $patron->dateexpiry( undef )->store->discard_changes;
314 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
316 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
317 $patron->dateexpiry( $today )->store->discard_changes;
318 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
320 $patron->dateexpiry( $today )->store->discard_changes;
321 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
323 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
324 $patron->dateexpiry( $today->clone->add( days => 11 ) )->store->discard_changes;
325 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');
327 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
328 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
329 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');
331 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
332 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
333 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');
336 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
337 $patron->dateexpiry( $today->clone->add( days => 20 ) )->store->discard_changes;
338 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');
340 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
341 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
342 is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
344 { # Testing invalid is going to expiry date
345 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 30);
346 # mock_config does not work here, because of tz vs timezone subroutines
347 my $context = new Test::MockModule('C4::Context');
348 $context->mock( 'tz', sub {
351 $patron->dateexpiry(DateTime->new( year => 2019, month => 12, day => 3 ))->store;
352 eval { $patron->is_going_to_expire };
353 is( $@, '', 'On invalid "is going to expire" date, the method should not crash with "Invalid local time for date in time zone"');
354 $context->unmock('tz');
361 subtest 'renew_account' => sub {
364 for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
365 my $dt = dt_from_string( $date, 'iso' );
366 Time::Fake->offset( $dt->epoch );
367 my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
368 my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
369 my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
370 my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
371 my $a_year_later_plus_a_month = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
372 my $patron_category = $builder->build(
373 { source => 'Category',
375 enrolmentperiod => 12,
376 enrolmentperioddate => undef,
380 my $patron = $builder->build(
381 { source => 'Borrower',
383 dateexpiry => $a_month_ago,
384 categorycode => $patron_category->{categorycode},
385 date_renewed => undef, # Force builder to not populate the column for new patron
389 my $patron_2 = $builder->build(
390 { source => 'Borrower',
392 dateexpiry => $a_month_ago,
393 categorycode => $patron_category->{categorycode},
397 my $patron_3 = $builder->build(
398 { source => 'Borrower',
400 dateexpiry => $a_month_later,
401 categorycode => $patron_category->{categorycode},
405 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
406 my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
407 my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
409 is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
411 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
412 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
413 my $expiry_date = $retrieved_patron->renew_account;
414 is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
415 my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
416 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" );
417 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
418 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
420 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
421 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
422 $expiry_date = $retrieved_patron->renew_account;
423 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
424 $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
425 is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
426 $retrieved_expiry_date = $retrieved_patron->dateexpiry;
427 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
428 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
429 is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
431 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
432 $expiry_date = $retrieved_patron_2->renew_account;
433 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
434 $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
435 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
437 $expiry_date = $retrieved_patron_3->renew_account;
438 is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
439 $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
440 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" );
442 $retrieved_patron->delete;
443 $retrieved_patron_2->delete;
444 $retrieved_patron_3->delete;
449 subtest "move_to_deleted" => sub {
451 my $originally_updated_on = '2016-01-01 12:12:12';
452 my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
453 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
454 is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
455 ; # FIXME This should be Koha::Deleted::Patron
456 my $deleted_patron = $schema->resultset('Deletedborrower')
457 ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
459 ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
460 ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
461 isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
462 $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
463 is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
464 $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup
467 subtest "delete" => sub {
469 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
470 my $patron = $builder->build( { source => 'Borrower' } );
471 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
472 my $hold = $builder->build(
473 { source => 'Reserve',
474 value => { borrowernumber => $patron->{borrowernumber} }
477 my $list = $builder->build(
478 { source => 'Virtualshelve',
479 value => { owner => $patron->{borrowernumber} }
483 my $deleted = $retrieved_patron->delete;
484 is( ref($deleted), 'Koha::Patron', 'Koha::Patron->delete should return the deleted patron object if the patron has been correctly deleted' );
486 is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
488 is (Koha::Old::Holds->search( { reserve_id => $hold->{ reserve_id } } )->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| );
490 is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have cancelled patron's holds 2| );
492 is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
494 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
495 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
498 subtest 'Koha::Patrons->delete' => sub {
501 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
502 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
503 my $id1 = $patron1->borrowernumber;
504 my $set = Koha::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
505 is( $set->count, 2, 'Two patrons found as expected' );
506 is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
507 my $deleted_patrons = Koha::Old::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
508 is( $deleted_patrons->count, 2, 'Patrons moved to deletedborrowers' );
510 # See other tests in t/db_dependent/Koha/Objects.t
513 subtest 'add_enrolment_fee_if_needed' => sub {
516 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
517 foreach( keys %{$enrolmentfees} ) {
518 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
520 my $enrolmentfee_K = $enrolmentfees->{K};
521 my $enrolmentfee_J = $enrolmentfees->{J};
522 my $enrolmentfee_YA = $enrolmentfees->{YA};
524 my %borrower_data = (
525 firstname => 'my firstname',
526 surname => 'my surname',
528 branchcode => $library->{branchcode},
531 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
532 $borrower_data{borrowernumber} = $borrowernumber;
534 my $patron = Koha::Patrons->find( $borrowernumber );
535 my $total = $patron->account->balance;
536 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
538 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
539 $borrower_data{categorycode} = 'J';
540 $patron->set(\%borrower_data)->store;
541 $total = $patron->account->balance;
542 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
544 $borrower_data{categorycode} = 'K';
545 $patron->set(\%borrower_data)->store;
546 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
548 $borrower_data{categorycode} = 'J';
549 $patron->set(\%borrower_data)->store;
550 $total = $patron->account->balance;
551 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
553 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
554 $patron->categorycode('YA')->store;
555 $total = $patron->account->balance;
557 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
558 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
564 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
567 my $library = $builder->build( { source => 'Branch' } );
568 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
569 my $item_1 = $builder->build(
573 homebranch => $library->{branchcode},
574 holdingbranch => $library->{branchcode},
575 biblionumber => $biblionumber_1,
581 my $item_2 = $builder->build(
585 homebranch => $library->{branchcode},
586 holdingbranch => $library->{branchcode},
587 biblionumber => $biblionumber_1,
593 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
594 my $item_3 = $builder->build(
598 homebranch => $library->{branchcode},
599 holdingbranch => $library->{branchcode},
600 biblionumber => $biblionumber_2,
606 my $patron = $builder->build(
608 source => 'Borrower',
609 value => { branchcode => $library->{branchcode} }
613 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
614 my $checkouts = $patron->checkouts;
615 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
616 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
617 my $pending_checkouts = $patron->pending_checkouts;
618 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
619 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
620 my $old_checkouts = $patron->old_checkouts;
621 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
622 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
624 # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
625 $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
627 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
629 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
630 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
631 AddIssue( $patron, $item_3->{barcode} );
633 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
634 $checkouts = $patron->checkouts;
635 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
636 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
637 $pending_checkouts = $patron->pending_checkouts;
638 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
639 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
641 my $first_checkout = $pending_checkouts->next;
642 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
644 my $overdues = $patron->get_overdues;
645 is( $overdues->count, 2, 'Patron should have 2 overdues');
646 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
647 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
648 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
651 C4::Circulation::AddReturn( $item_1->{barcode} );
652 C4::Circulation::AddReturn( $item_2->{barcode} );
653 $old_checkouts = $patron->old_checkouts;
654 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
655 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
658 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
662 subtest 'get_routing_lists' => sub {
665 my $biblio = Koha::Biblio->new()->store();
666 my $subscription = Koha::Subscription->new({
667 biblionumber => $biblio->biblionumber,
671 my $patron = $builder->build( { source => 'Borrower' } );
672 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
674 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
676 my $routinglist_count = Koha::Subscription::Routinglists->count;
677 my $routinglist = Koha::Subscription::Routinglist->new({
678 borrowernumber => $patron->borrowernumber,
680 subscriptionid => $subscription->subscriptionid
683 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
685 my $routinglists = $patron->get_routing_lists;
686 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
687 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
689 my $subscription2 = Koha::Subscription->new({
690 biblionumber => $biblio->biblionumber,
693 my $routinglist2 = Koha::Subscription::Routinglist->new({
694 borrowernumber => $patron->borrowernumber,
696 subscriptionid => $subscription2->subscriptionid
699 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
701 $patron->delete; # Clean up for later tests
705 subtest 'get_age' => sub {
708 my $patron = $builder->build( { source => 'Borrower' } );
709 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
711 my $dt = dt_from_string('2020-02-28');
713 Time::Fake->offset( $dt->epoch );
714 $patron->dateofbirth( undef );
715 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
717 my $add_m12_m6_m1 = '2007-08-27';
718 $patron->dateofbirth( dt_from_string($add_m12_m6_m1, 'iso') );
719 is( $patron->get_age, 12, 'Patron should be 12' );
721 my $add_m18_0_p1 = '2002-02-28';
722 $patron->dateofbirth( dt_from_string($add_m18_0_p1, 'iso'));
723 is( $patron->get_age, 17, 'Patron should be 17, happy birthday tomorrow!' );
725 my $add_m18_0_0 = '2002-02-28';
726 $patron->dateofbirth( dt_from_string($add_m18_0_0, 'iso'));
727 is( $patron->get_age, 18, 'Patron should be 18' );
729 my $add_m18_m12_m31 = '2001-01-28';
730 $patron->dateofbirth( dt_from_string($add_m18_m12_m31, 'iso'));
731 is( $patron->get_age, 19, 'Patron should be 19' );
733 my $add_m18_m12_m30 = '2001-01-29';
734 $patron->dateofbirth( dt_from_string($add_m18_m12_m30, 'iso' ));
735 is( $patron->get_age, 19, 'Patron should be 19 again' );
737 my $add_0_m1_m1 = '2020-01-27';
738 $patron->dateofbirth( dt_from_string($add_0_m1_m1, 'iso' ));
739 is( $patron->get_age, 0, 'Patron is a newborn child' );
746 subtest 'is_valid_age' => sub {
749 my $dt = dt_from_string('2020-02-28');
751 Time::Fake->offset( $dt->epoch );
753 my $category = $builder->build({
754 source => 'Category',
756 categorycode => 'AGE_5_10',
757 dateofbirthrequired => 5,
761 $category = Koha::Patron::Categories->find( $category->{categorycode} );
763 my $patron = $builder->build({
764 source => 'Borrower',
766 categorycode => 'AGE_5_10'
769 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
772 $patron->dateofbirth( undef );
773 is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
775 my $add_m12_m6_m1 = '2007-08-27';
776 $patron->dateofbirth( dt_from_string($add_m12_m6_m1, 'iso') );
777 is( $patron->is_valid_age, 0, 'Patron is 12, so the age is above allowed range 5-10 years');
779 my $add_m3_m6_m1 = '2016-08-27';
780 $patron->dateofbirth( dt_from_string($add_m3_m6_m1, 'iso'));
781 is( $patron->is_valid_age, 0, 'Patron is 3, so the age is below allowed range 5-10 years');
783 my $add_m7_m6_m1 = '2015-02-28';
784 $patron->dateofbirth( dt_from_string($add_m7_m6_m1, 'iso'));
785 is( $patron->is_valid_age, 1, 'Patron is 7, so the age perfectly suits allowed range 5-10 years');
787 my $add_m5_0_1 = '2015-02-28';
788 $patron->dateofbirth( dt_from_string($add_m5_0_1, 'iso' ));
789 is( $patron->is_valid_age, 1, 'Patron celebrates the 5th birthday today, so the age is allowed for this category');
791 my $add_m5_0_p1 = '2015-02-28';
792 $patron->dateofbirth( dt_from_string($add_m5_0_p1, 'iso'));
793 is( $patron->is_valid_age, 0, 'Patron will celebrate the 5th birthday tomorrow, so the age is NOT allowed for this category');
795 my $add_m5_0_m1 = '2015-02-27';
796 $patron->dateofbirth( dt_from_string($add_m5_0_m1, 'iso'));
797 is( $patron->is_valid_age, 1, 'Patron celebrated the 5th birthday yesterday, so the age is allowed for this category');
799 my $add_m11_0_p0 = '2009-02-28';
800 $patron->dateofbirth( dt_from_string($add_m11_0_p0, 'iso'));
801 is( $patron->is_valid_age, 0, 'Patron celebrate the 11th birthday today, so the age is NOT allowed for this category');
803 my $add_m11_0_p1 = '2009-02-28';
804 $patron->dateofbirth( dt_from_string($add_m11_0_p1, 'iso'));
805 is( $patron->is_valid_age, 1, 'Patron will celebrate the 11th birthday tomorrow, so the age is allowed for this category');
807 my $add_m11_0_m1 = '2009-02-27';
808 $patron->dateofbirth( dt_from_string($add_m11_0_m1, 'iso' ));
809 is( $patron->is_valid_age, 0, 'Patron celebrated the 11th birthday yesterday, so the age is NOT allowed for this category');
817 subtest 'account' => sub {
820 my $patron = $builder->build({source => 'Borrower'});
822 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
823 my $account = $patron->account;
824 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
829 subtest 'search_upcoming_membership_expires' => sub {
832 my $expiry_days = 15;
833 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
834 my $nb_of_days_before = 1;
835 my $nb_of_days_after = 2;
837 my $builder = t::lib::TestBuilder->new();
839 my $library = $builder->build({ source => 'Branch' });
841 # before we add borrowers to this branch, add the expires we have now
842 # note that this pertains to the current mocked setting of the pref
843 # for this reason we add the new branchcode to most of the tests
844 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
846 my $patron_1 = $builder->build({
847 source => 'Borrower',
849 branchcode => $library->{branchcode},
850 dateexpiry => dt_from_string->add( days => $expiry_days )
854 my $patron_2 = $builder->build({
855 source => 'Borrower',
857 branchcode => $library->{branchcode},
858 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
862 my $patron_3 = $builder->build({
863 source => 'Borrower',
865 branchcode => $library->{branchcode},
866 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
870 # Test without extra parameters
871 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
872 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
875 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
876 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
877 my $expired = $upcoming_mem_expires->next;
878 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
879 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
880 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
882 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
883 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
884 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
886 # Test MembershipExpiryDaysNotice == undef
887 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
888 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
889 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
891 # Test the before parameter
892 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
893 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
894 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
895 # Test after parameter also
896 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
897 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
898 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
901 subtest 'holds and old_holds' => sub {
904 my $library = $builder->build( { source => 'Branch' } );
905 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
906 my $item_1 = $builder->build(
910 homebranch => $library->{branchcode},
911 holdingbranch => $library->{branchcode},
912 biblionumber => $biblionumber_1
916 my $item_2 = $builder->build(
920 homebranch => $library->{branchcode},
921 holdingbranch => $library->{branchcode},
922 biblionumber => $biblionumber_1
926 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
927 my $item_3 = $builder->build(
931 homebranch => $library->{branchcode},
932 holdingbranch => $library->{branchcode},
933 biblionumber => $biblionumber_2
937 my $patron = $builder->build(
939 source => 'Borrower',
940 value => { branchcode => $library->{branchcode} }
944 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
945 my $holds = $patron->holds;
946 is( ref($holds), 'Koha::Holds',
947 'Koha::Patron->holds should return a Koha::Holds objects' );
948 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
950 C4::Reserves::AddReserve(
952 branchcode => $library->{branchcode},
953 borrowernumber => $patron->borrowernumber,
954 biblionumber => $biblionumber_1
958 C4::Reserves::AddReserve(
960 branchcode => $library->{branchcode},
961 borrowernumber => $patron->borrowernumber,
962 biblionumber => $biblionumber_2,
963 expiration_date => dt_from_string->add( days => 2 )
967 $holds = $patron->holds;
968 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
970 my $old_holds = $patron->old_holds;
971 is( ref($old_holds), 'Koha::Old::Holds',
972 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
973 is( $old_holds->count, 0, 'There should not be any old holds yet');
975 my $hold = $holds->next;
978 $old_holds = $patron->old_holds;
979 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
986 subtest 'notice_email_address' => sub {
989 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
991 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
992 is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
994 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
995 is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
1000 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
1003 # TODO create a subroutine in t::lib::Mocks
1004 my $branch = $builder->build({ source => 'Branch' });
1005 my $userenv_patron = $builder->build_object({
1006 class => 'Koha::Patrons',
1007 value => { branchcode => $branch->{branchcode}, flags => 0 },
1009 t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
1011 my $anonymous = $builder->build( { source => 'Borrower', }, );
1013 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
1015 subtest 'patron privacy is 1 (default)' => sub {
1018 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1019 my $patron = $builder->build(
1020 { source => 'Borrower',
1021 value => { privacy => 1, }
1024 my $item_1 = $builder->build(
1032 my $issue_1 = $builder->build(
1033 { source => 'Issue',
1035 borrowernumber => $patron->{borrowernumber},
1036 itemnumber => $item_1->{itemnumber},
1040 my $item_2 = $builder->build(
1048 my $issue_2 = $builder->build(
1049 { source => 'Issue',
1051 borrowernumber => $patron->{borrowernumber},
1052 itemnumber => $item_2->{itemnumber},
1057 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1058 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, dt_from_string('2011-11-11') );
1059 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
1061 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
1062 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
1064 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
1065 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1067 $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1068 is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
1070 my $dbh = C4::Context->dbh;
1071 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
1072 $sth->execute($item_1->{itemnumber});
1073 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1074 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
1075 $sth->execute($item_2->{itemnumber});
1076 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1077 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
1079 $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
1080 $sth->execute($item_2->{itemnumber});
1081 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1082 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
1084 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
1085 $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
1086 $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
1087 $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
1088 $sth->execute($item_1->{itemnumber});
1089 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1090 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
1091 $sth->execute($item_2->{itemnumber});
1092 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1093 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
1095 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1098 subtest 'patron privacy is 0 (forever)' => sub {
1101 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1102 my $patron = $builder->build(
1103 { source => 'Borrower',
1104 value => { privacy => 0, }
1107 my $item = $builder->build(
1115 my $issue = $builder->build(
1116 { source => 'Issue',
1118 borrowernumber => $patron->{borrowernumber},
1119 itemnumber => $item->{itemnumber},
1124 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1125 is( $returned, 1, 'The item should have been returned' );
1127 my $dbh = C4::Context->dbh;
1128 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1129 SELECT borrowernumber FROM old_issues where itemnumber = ?
1130 |, undef, $item->{itemnumber});
1131 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1132 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1135 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1137 subtest 'AnonymousPatron is not defined' => sub {
1140 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1141 my $patron = $builder->build(
1142 { source => 'Borrower',
1143 value => { privacy => 1, }
1146 my $item = $builder->build(
1154 my $issue = $builder->build(
1155 { source => 'Issue',
1157 borrowernumber => $patron->{borrowernumber},
1158 itemnumber => $item->{itemnumber},
1163 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1164 is( $returned, 1, 'The item should have been returned' );
1165 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
1166 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1168 my $dbh = C4::Context->dbh;
1169 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1170 SELECT borrowernumber FROM old_issues where itemnumber = ?
1171 |, undef, $item->{itemnumber});
1172 is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
1173 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1176 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1178 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1179 my $patron = $builder->build(
1180 { source => 'Borrower',
1181 value => { privacy => 1 } # Another branchcode than the logged in librarian
1184 my $item = $builder->build(
1192 my $issue = $builder->build(
1193 { source => 'Issue',
1195 borrowernumber => $patron->{borrowernumber},
1196 itemnumber => $item->{itemnumber},
1201 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1202 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1203 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1206 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1207 $userenv_patron->delete;
1209 # Reset IndependentBranches for further tests
1210 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1213 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1221 $nb_of_patrons = Koha::Patrons->search->count;
1222 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1223 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1224 my $library_11 = $builder->build( { source => 'Branch' } );
1225 my $library_12 = $builder->build( { source => 'Branch' } );
1226 my $library_21 = $builder->build( { source => 'Branch' } );
1227 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1228 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1229 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1230 Koha::Library::Group->new(
1231 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1232 Koha::Library::Group->new(
1233 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1234 Koha::Library::Group->new(
1235 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1237 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1238 # 2 patrons from library_11 (group1)
1239 # patron_11_1 see patron's infos from outside its group
1240 # Setting flags => undef to not be considered as superlibrarian
1241 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1242 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1243 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1244 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1245 # patron_11_2 can only see patron's info from its group
1246 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1247 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1248 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1249 # 1 patron from library_12 (group1)
1250 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1251 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1252 # 1 patron from library_21 (group2) can only see patron's info from its group
1253 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1254 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1255 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1257 # Pfiou, we can start now!
1258 subtest 'libraries_where_can_see_patrons' => sub {
1263 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1264 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1265 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1267 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1268 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1269 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| );
1271 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1272 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1273 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| );
1275 subtest 'can_see_patron_infos' => sub {
1278 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1279 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1280 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1281 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1283 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1284 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1285 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1286 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1288 subtest 'search_limited' => sub {
1291 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1292 my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1293 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1294 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1296 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1297 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1298 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' );
1300 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1301 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1302 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1304 $patron_11_1->delete;
1305 $patron_11_2->delete;
1310 subtest 'account_locked' => sub {
1312 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1313 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1314 for my $value ( undef, '', 0 ) {
1315 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1316 $patron->login_attempts(0)->store;
1317 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1318 $patron->login_attempts(1)->store;
1319 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1320 $patron->login_attempts(-1)->store;
1321 is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1324 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1325 $patron->login_attempts(2)->store;
1326 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1327 $patron->login_attempts(3)->store;
1328 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1329 $patron->login_attempts(4)->store;
1330 is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1331 $patron->login_attempts(-1)->store;
1332 is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1337 subtest 'is_child | is_adult' => sub {
1339 my $category = $builder->build_object(
1341 class => 'Koha::Patron::Categories',
1342 value => { category_type => 'A' }
1345 my $patron_adult = $builder->build_object(
1347 class => 'Koha::Patrons',
1348 value => { categorycode => $category->categorycode }
1351 $category = $builder->build_object(
1353 class => 'Koha::Patron::Categories',
1354 value => { category_type => 'I' }
1357 my $patron_adult_i = $builder->build_object(
1359 class => 'Koha::Patrons',
1360 value => { categorycode => $category->categorycode }
1363 $category = $builder->build_object(
1365 class => 'Koha::Patron::Categories',
1366 value => { category_type => 'C' }
1369 my $patron_child = $builder->build_object(
1371 class => 'Koha::Patrons',
1372 value => { categorycode => $category->categorycode }
1375 $category = $builder->build_object(
1377 class => 'Koha::Patron::Categories',
1378 value => { category_type => 'O' }
1381 my $patron_other = $builder->build_object(
1383 class => 'Koha::Patrons',
1384 value => { categorycode => $category->categorycode }
1387 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1388 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1389 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1390 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1392 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1393 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1394 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1395 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1398 $patron_adult->delete;
1399 $patron_adult_i->delete;
1400 $patron_child->delete;
1401 $patron_other->delete;
1404 subtest 'get_overdues' => sub {
1407 my $library = $builder->build( { source => 'Branch' } );
1408 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1409 my $item_1 = $builder->build(
1413 homebranch => $library->{branchcode},
1414 holdingbranch => $library->{branchcode},
1415 biblionumber => $biblionumber_1
1419 my $item_2 = $builder->build(
1423 homebranch => $library->{branchcode},
1424 holdingbranch => $library->{branchcode},
1425 biblionumber => $biblionumber_1
1429 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1430 my $item_3 = $builder->build(
1434 homebranch => $library->{branchcode},
1435 holdingbranch => $library->{branchcode},
1436 biblionumber => $biblionumber_2
1440 my $patron = $builder->build(
1442 source => 'Borrower',
1443 value => { branchcode => $library->{branchcode} }
1447 t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1449 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1450 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1451 AddIssue( $patron, $item_3->{barcode} );
1453 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1454 my $overdues = $patron->get_overdues;
1455 is( $overdues->count, 2, 'Patron should have 2 overdues');
1456 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1457 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1459 my $o = $overdues->reset->next;
1460 my $unblessed_overdue = $o->unblessed_all_relateds;
1461 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1462 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1463 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1464 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1467 $patron->checkouts->delete;
1471 subtest 'userid_is_valid' => sub {
1474 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1475 my $patron_category = $builder->build_object(
1477 class => 'Koha::Patron::Categories',
1478 value => { category_type => 'P', enrolmentfee => 0 }
1482 cardnumber => "123456789",
1483 firstname => "Tomasito",
1485 categorycode => $patron_category->categorycode,
1486 branchcode => $library->branchcode,
1489 my $expected_userid_patron_1 = 'tomasito.none';
1490 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1491 my $patron_1 = Koha::Patrons->find($borrowernumber);
1492 is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1493 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1495 $patron_1->userid( 'tomasito.non' );
1496 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1497 1, 'recently created userid -> unique (borrowernumber passed)' );
1499 $patron_1->userid( 'tomasitoxxx' );
1500 is( $patron_1->has_valid_userid,
1501 1, 'non-existent userid -> unique (borrowernumber passed)' );
1502 $patron_1->discard_changes; # We compare with the original userid later
1504 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1505 is( $patron_not_in_storage->has_valid_userid,
1506 0, 'userid exists for another patron, patron is not in storage yet' );
1508 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1509 is( $patron_not_in_storage->has_valid_userid,
1510 1, 'non-existent userid, patron is not in storage yet' );
1512 # Regression tests for BZ12226
1513 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1514 is( $db_patron->has_valid_userid,
1515 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1517 # Add a new borrower with the same userid but different cardnumber
1518 $data{cardnumber} = "987654321";
1519 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1520 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1521 $patron_2->userid($patron_1->userid);
1522 is( $patron_2->has_valid_userid,
1523 0, 'The userid is already in used, it cannot be used for another patron' );
1525 my $new_userid = 'a_user_id';
1526 $data{cardnumber} = "234567890";
1527 $data{userid} = 'a_user_id';
1528 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1529 my $patron_3 = Koha::Patrons->find($borrowernumber);
1530 is( $patron_3->userid, $new_userid,
1531 'Koha::Patron->store should insert the given userid' );
1539 subtest 'generate_userid' => sub {
1542 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1543 my $patron_category = $builder->build_object(
1545 class => 'Koha::Patron::Categories',
1546 value => { category_type => 'P', enrolmentfee => 0 }
1550 cardnumber => "123456789",
1551 firstname => "Tômà sÃtó",
1552 surname => "Ñoné",
1553 categorycode => $patron_category->categorycode,
1554 branchcode => $library->branchcode,
1557 my $expected_userid_patron_1 = 'tomasito.none';
1558 my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1559 $new_patron->generate_userid;
1560 my $userid = $new_patron->userid;
1561 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1562 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1563 my $patron_1 = Koha::Patrons->find($borrowernumber);
1564 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1566 $new_patron->generate_userid;
1567 $userid = $new_patron->userid;
1568 is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1569 $data{cardnumber} = '987654321';
1570 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1571 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1572 isnt( $patron_2->userid, 'tomasito',
1573 "Patron with duplicate userid has new userid generated" );
1574 is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1575 "Patron with duplicate userid has new userid generated (1 is appened" );
1577 $new_patron->generate_userid;
1578 $userid = $new_patron->userid;
1579 is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1581 $patron_1 = Koha::Patrons->find($borrowernumber);
1582 $patron_1->userid(undef);
1583 $patron_1->generate_userid;
1584 $userid = $patron_1->userid;
1585 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1592 subtest 'attributes' => sub {
1595 my $library1 = Koha::Library->new({
1596 branchcode => 'LIBPATRON',
1597 branchname => 'Library of testing patron',
1600 my $library2 = Koha::Library->new({
1601 branchcode => 'LIBATTR',
1602 branchname => 'Library for testing attribute',
1605 my $category = Koha::Patron::Category->new({
1606 categorycode => 'CAT1',
1607 description => 'Category 1',
1610 my $patron = Koha::Patron->new({
1611 firstname => 'Patron',
1612 surname => 'with attributes',
1613 branchcode => 'LIBPATRON',
1614 categorycode => 'CAT1',
1617 my $attribute_type1 = Koha::Patron::Attribute::Type->new({
1619 description => 'Code A desciption',
1622 my $attribute_type2 = Koha::Patron::Attribute::Type->new({
1624 description => 'Code A desciption',
1627 $attribute_type2->library_limits ( [ $library2->branchcode ] );
1629 Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type1->code, attribute => 'value 1' } )->store();
1630 Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type2->code, attribute => 'value 2' } )->store();
1632 is( $patron->attributes->count, 1, 'There should be one attribute');
1634 $attribute_type2->library_limits ( [ $library1->branchcode ] );
1636 is( $patron->attributes->count, 2, 'There should be 2 attributes');
1641 $nb_of_patrons = Koha::Patrons->search->count;
1642 $retrieved_patron_1->delete;
1643 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1645 subtest 'BorrowersLog tests' => sub {
1648 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1649 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1651 my $cardnumber = $patron->cardnumber;
1652 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1655 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1656 my $log_info = from_json( $logs[0]->info );
1657 is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1658 is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1659 is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1661 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1662 $patron->track_login();
1663 @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1664 is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1667 $schema->storage->txn_rollback;
1669 subtest 'Test Koha::Patrons::merge' => sub {
1672 my $schema = Koha::Database->new()->schema();
1674 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1676 $schema->storage->txn_begin;
1678 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1679 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1680 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1682 while (my ($r, $field) = each(%$resultsets)) {
1683 $builder->build({ source => $r, value => { $field => $keeper->id } });
1684 $builder->build({ source => $r, value => { $field => $loser_1 } });
1685 $builder->build({ source => $r, value => { $field => $loser_2 } });
1688 $schema->resultset($r)->search( { $field => $keeper->id } );
1689 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1692 $schema->resultset($r)->search( { $field => $loser_1 } );
1693 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1696 $schema->resultset($r)->search( { $field => $loser_2 } );
1697 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1700 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1702 while (my ($r, $field) = each(%$resultsets)) {
1704 $schema->resultset($r)->search( {$field => $keeper->id } );
1705 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1708 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1709 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1711 $schema->storage->txn_rollback;
1714 subtest '->store' => sub {
1716 my $schema = Koha::Database->new->schema;
1717 $schema->storage->txn_begin;
1719 my $print_error = $schema->storage->dbh->{PrintError};
1720 $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1722 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1723 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1726 { $patron_2->userid($patron_1->userid)->store; }
1727 'Koha::Exceptions::Object::DuplicateID',
1728 'Koha::Patron->store raises an exception on duplicate ID';
1731 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1732 my $password = 'password';
1733 $patron_1->set_password({ password => $password });
1734 like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1735 my $digest = $patron_1->password;
1736 $patron_1->surname('xxx')->store;
1737 is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1739 # Test uppercasesurnames
1740 t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 );
1741 my $surname = lc $patron_1->surname;
1742 $patron_1->surname($surname)->store;
1743 isnt( $patron_1->surname, $surname,
1744 'Surname converts to uppercase on store.');
1745 t::lib::Mocks::mock_preference( 'uppercasesurnames', 0 );
1746 $patron_1->surname($surname)->store;
1747 is( $patron_1->surname, $surname,
1748 'Surname remains unchanged on store.');
1751 $patron_1->relationship("")->store;
1752 is( $patron_1->relationship, undef, );
1754 $schema->storage->dbh->{PrintError} = $print_error;
1755 $schema->storage->txn_rollback;
1757 subtest 'skip updated_on for BorrowersLog' => sub {
1759 $schema->storage->txn_begin;
1760 t::lib::Mocks::mock_preference('BorrowersLog', 1);
1761 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1762 $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1763 my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1764 is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1765 $schema->storage->txn_rollback;
1769 subtest '->set_password' => sub {
1773 $schema->storage->txn_begin;
1775 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1777 # Disable logging password changes for this tests
1778 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1780 # Password-length tests
1781 t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1782 throws_ok { $patron->set_password({ password => 'ab' }); }
1783 'Koha::Exceptions::Password::TooShort',
1784 'minPasswordLength is undef, fall back to 3, fail test';
1786 'Password length (2) is shorter than required (3)',
1787 'Exception parameters passed correctly'
1790 t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1791 throws_ok { $patron->set_password({ password => 'ab' }); }
1792 'Koha::Exceptions::Password::TooShort',
1793 'minPasswordLength is 2, fall back to 3, fail test';
1795 t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1796 throws_ok { $patron->set_password({ password => 'abcb' }); }
1797 'Koha::Exceptions::Password::TooShort',
1798 'minPasswordLength is 5, fail test';
1800 # Trailing spaces tests
1801 throws_ok { $patron->set_password({ password => 'abcD12d ' }); }
1802 'Koha::Exceptions::Password::WhitespaceCharacters',
1803 'Password contains trailing spaces, exception is thrown';
1805 # Require strong password tests
1806 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1807 throws_ok { $patron->set_password({ password => 'abcd a' }); }
1808 'Koha::Exceptions::Password::TooWeak',
1809 'Password is too weak, exception is thrown';
1811 # Refresh patron from DB, just to make sure
1812 $patron->discard_changes;
1813 is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1815 $patron->set_password({ password => 'abcD12 34' });
1816 $patron->discard_changes;
1818 is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1820 lives_ok { $patron->set_password({ password => 'abcd a', skip_validation => 1 }) }
1821 'Password is weak, but skip_validation was passed, so no exception thrown';
1824 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1825 $patron->login_attempts(3)->store;
1826 my $old_digest = $patron->password;
1827 $patron->set_password({ password => 'abcd a' });
1828 $patron->discard_changes;
1830 isnt( $patron->password, $old_digest, 'Password has been updated' );
1831 ok( checkpw_hash('abcd a', $patron->password), 'Password hash is correct' );
1832 is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1834 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1835 is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1837 # Enable logging password changes
1838 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1839 $patron->set_password({ password => 'abcd b' });
1841 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1842 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1844 $schema->storage->txn_rollback;
1847 $schema->storage->txn_begin;
1848 subtest 'search_unsubscribed' => sub {
1851 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1852 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
1853 is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
1855 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1856 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1858 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
1859 Koha::Patron::Consents->delete; # for correct counts
1860 Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string })->store;
1861 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
1863 # Add another refusal but shift the period
1864 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
1865 Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string->subtract(days=>2) })->store;
1866 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
1868 # Try another (special) attempts setting
1869 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
1870 # Lockout is now disabled
1871 # Patron2 still matches: refused earlier, not locked
1872 is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
1875 subtest 'search_anonymize_candidates' => sub {
1877 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1878 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1879 $patron1->anonymized(0);
1880 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1881 $patron2->anonymized(0);
1882 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1884 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
1885 is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
1887 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
1888 my $cnt = Koha::Patrons->search_anonymize_candidates->count;
1889 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1890 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1891 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
1893 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
1894 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1895 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1896 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1897 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1898 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1899 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
1901 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
1902 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1903 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1904 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1905 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1906 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1907 is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
1909 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1910 $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1911 $patron1->login_attempts(0)->store;
1912 $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1913 $patron2->login_attempts(0)->store;
1914 $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
1915 $patron1->login_attempts(3)->store;
1916 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1917 $cnt+1, 'Locked flag' );
1919 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1920 # Patron 1 still on 3 == locked
1921 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1922 $cnt+1, 'Still expect same number for FailedLoginAttempts empty' );
1923 $patron1->login_attempts(0)->store;
1925 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1926 $cnt, 'Patron 1 unlocked' );
1929 subtest 'search_anonymized' => sub {
1931 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1933 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
1934 is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
1936 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
1937 $patron1->dateexpiry( dt_from_string );
1938 $patron1->anonymized(0)->store;
1939 my $cnt = Koha::Patrons->search_anonymized->count;
1940 $patron1->anonymized(1)->store;
1941 is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
1942 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1943 is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
1946 subtest 'lock' => sub {
1949 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1950 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1951 my $hold = $builder->build_object({
1952 class => 'Koha::Holds',
1953 value => { borrowernumber => $patron1->borrowernumber },
1956 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1957 my $expiry = dt_from_string->add(days => 1);
1958 $patron1->dateexpiry( $expiry );
1960 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1961 is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
1962 is( $patron1->holds->count, 1, 'No holds removed' );
1964 $patron1->lock({ expire => 1, remove => 1});
1965 isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
1966 is( $patron1->holds->count, 0, 'Holds removed' );
1968 # Disable lockout feature
1969 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1970 $patron1->login_attempts(0);
1971 $patron1->dateexpiry( $expiry );
1974 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1976 # Trivial wrapper test (Koha::Patrons->lock)
1977 $patron1->login_attempts(0)->store;
1978 Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
1979 $patron1->discard_changes; # refresh
1980 $patron2->discard_changes;
1981 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
1982 is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
1985 subtest 'anonymize' => sub {
1988 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1989 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1991 # First try patron with issues
1992 my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
1993 warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
1996 t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
1997 my $surname = $patron1->surname; # expect change, no clear
1998 my $branchcode = $patron1->branchcode; # expect skip
1999 $patron1->anonymize;
2000 is($patron1->anonymized, 1, 'Check flag' );
2002 is( $patron1->dateofbirth, undef, 'Birth date cleared' );
2003 is( $patron1->firstname, undef, 'First name cleared' );
2004 isnt( $patron1->surname, $surname, 'Surname changed' );
2005 ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
2006 is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
2007 is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
2009 # Test wrapper in Koha::Patrons
2010 $patron1->surname($surname)->store; # restore
2011 my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
2012 $patron1->discard_changes; # refresh
2013 isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
2014 $patron2->discard_changes; # refresh
2015 is( $patron2->firstname, undef, 'First name patron2 cleared' );
2017 $schema->storage->txn_rollback;