3 # Copyright 2015 Koha Development team
5 # This file is part of Koha
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22 use Test::More tests => 40;
34 use C4::Auth qw(checkpw_hash);
40 use Koha::Old::Patrons;
41 use Koha::Patron::Attribute::Types;
42 use Koha::Patron::Categories;
43 use Koha::Patron::Relationship;
46 use Koha::Virtualshelves;
48 use t::lib::TestBuilder;
51 my $schema = Koha::Database->new->schema;
52 $schema->storage->txn_begin;
54 my $builder = t::lib::TestBuilder->new;
55 my $library = $builder->build({source => 'Branch' });
56 my $category = $builder->build({source => 'Category' });
57 my $nb_of_patrons = Koha::Patrons->search->count;
58 my $new_patron_1 = Koha::Patron->new(
59 { cardnumber => 'test_cn_1',
60 branchcode => $library->{branchcode},
61 categorycode => $category->{categorycode},
62 surname => 'surname for patron1',
63 firstname => 'firstname for patron1',
64 userid => 'a_nonexistent_userid_1',
65 flags => 1, # Is superlibrarian
68 my $new_patron_2 = Koha::Patron->new(
69 { cardnumber => 'test_cn_2',
70 branchcode => $library->{branchcode},
71 categorycode => $category->{categorycode},
72 surname => 'surname for patron2',
73 firstname => 'firstname for patron2',
74 userid => 'a_nonexistent_userid_2',
78 t::lib::Mocks::mock_userenv({ patron => $new_patron_1 });
80 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
82 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
83 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
85 subtest 'library' => sub {
87 is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
88 is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
91 subtest 'guarantees' => sub {
94 t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test|test2' );
96 my $guarantees = $new_patron_1->guarantee_relationships;
97 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
98 is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee relationships' );
99 my @guarantees = $new_patron_1->guarantee_relationships;
100 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantee_relationships should return an array in a list context' );
101 is( scalar(@guarantees), 0, 'new_patron_1 should have 0 guarantee' );
103 my $guarantee_1 = $builder->build({ source => 'Borrower' });
104 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
105 my $guarantee_2 = $builder->build({ source => 'Borrower' });
106 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
108 $guarantees = $new_patron_1->guarantee_relationships;
109 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantee_relationships should return a Koha::Patrons result set in a scalar context' );
110 is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
111 @guarantees = $new_patron_1->guarantee_relationships;
112 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantee_relationships should return an array in a list context' );
113 is( scalar(@guarantees), 2, 'new_patron_1 should have 2 guarantees' );
114 $_->delete for @guarantees;
116 #Test return order of guarantees BZ 18635
117 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
118 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
120 my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
122 my $order_guarantee1 = $builder->build_object(
124 class => 'Koha::Patrons',
130 $builder->build_object(
132 class => 'Koha::Patron::Relationships',
134 guarantor_id => $guarantor->id,
135 guarantee_id => $order_guarantee1,
136 relationship => 'test',
141 my $order_guarantee2 = $builder->build_object(
143 class => 'Koha::Patrons',
149 $builder->build_object(
151 class => 'Koha::Patron::Relationships',
153 guarantor_id => $guarantor->id,
154 guarantee_id => $order_guarantee2,
155 relationship => 'test',
160 my $order_guarantee3 = $builder->build_object(
162 class => 'Koha::Patrons',
165 firstname => 'Walrus',
169 $builder->build_object(
171 class => 'Koha::Patron::Relationships',
173 guarantor_id => $guarantor->id,
174 guarantee_id => $order_guarantee3,
175 relationship => 'test',
180 my $order_guarantee4 = $builder->build_object(
182 class => 'Koha::Patrons',
185 firstname => 'Vulture',
186 guarantorid => $guarantor->borrowernumber
190 $builder->build_object(
192 class => 'Koha::Patron::Relationships',
194 guarantor_id => $guarantor->id,
195 guarantee_id => $order_guarantee4,
196 relationship => 'test',
201 my $order_guarantee5 = $builder->build_object(
203 class => 'Koha::Patrons',
206 firstname => 'Unicorn',
207 guarantorid => $guarantor->borrowernumber
211 my $r = $builder->build_object(
213 class => 'Koha::Patron::Relationships',
215 guarantor_id => $guarantor->id,
216 guarantee_id => $order_guarantee5,
217 relationship => 'test',
222 $guarantees = $guarantor->guarantee_relationships->guarantees;
224 is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
225 is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
226 is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
227 is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
228 is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
231 subtest 'category' => sub {
233 my $patron_category = $new_patron_1->category;
234 is( ref( $patron_category), 'Koha::Patron::Category', );
235 is( $patron_category->categorycode, $category->{categorycode}, );
238 subtest 'siblings' => sub {
240 my $siblings = $new_patron_1->siblings;
241 is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
242 my $guarantee_1 = $builder->build( { source => 'Borrower' } );
243 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
244 my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
245 $siblings = $retrieved_guarantee_1->siblings;
246 is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
247 my @siblings = $retrieved_guarantee_1->siblings;
248 is( ref( \@siblings ), 'ARRAY', 'Koha::Patron->siblings should return an array in a list context' );
249 is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' );
250 my $guarantee_2 = $builder->build( { source => 'Borrower' } );
251 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
252 my $guarantee_3 = $builder->build( { source => 'Borrower' } );
253 my $relationship_3 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_3->{borrowernumber}, relationship => 'test' } )->store();
254 $siblings = $retrieved_guarantee_1->siblings;
255 is( $siblings->count, 2, 'guarantee_1 should have 2 siblings' );
256 is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
257 is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
258 $_->delete for $retrieved_guarantee_1->siblings;
259 $retrieved_guarantee_1->delete;
262 subtest 'has_overdues' => sub {
265 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
266 my $item_1 = $builder->build(
269 homebranch => $library->{branchcode},
270 holdingbranch => $library->{branchcode},
274 biblionumber => $biblioitem_1->{biblionumber}
278 my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
279 is( $retrieved_patron->has_overdues, 0, );
281 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
282 my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
283 is( $retrieved_patron->has_overdues, 0, );
285 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
286 $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
287 $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
288 is( $retrieved_patron->has_overdues, 1, );
292 subtest 'is_expired' => sub {
294 my $patron = $builder->build({ source => 'Borrower' });
295 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
296 $patron->dateexpiry( undef )->store->discard_changes;
297 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
298 $patron->dateexpiry( dt_from_string )->store->discard_changes;
299 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
300 $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
301 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
302 $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
303 is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
308 subtest 'is_going_to_expire' => sub {
311 my $today = dt_from_string(undef, undef, 'floating');
312 my $patron = $builder->build({ source => 'Borrower' });
313 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
314 $patron->dateexpiry( undef )->store->discard_changes;
315 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
317 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
318 $patron->dateexpiry( $today )->store->discard_changes;
319 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
321 $patron->dateexpiry( $today )->store->discard_changes;
322 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
324 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
325 $patron->dateexpiry( $today->clone->add( days => 11 ) )->store->discard_changes;
326 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');
328 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
329 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
330 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');
332 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
333 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
334 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');
337 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
338 $patron->dateexpiry( $today->clone->add( days => 20 ) )->store->discard_changes;
339 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');
341 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
342 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
343 is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
345 { # Testing invalid is going to expiry date
346 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 30);
347 # mock_config does not work here, because of tz vs timezone subroutines
348 my $context = new Test::MockModule('C4::Context');
349 $context->mock( 'tz', sub {
352 $patron->dateexpiry(DateTime->new( year => 2019, month => 12, day => 3 ))->store;
353 eval { $patron->is_going_to_expire };
354 is( $@, '', 'On invalid "is going to expire" date, the method should not crash with "Invalid local time for date in time zone"');
355 $context->unmock('tz');
362 subtest 'renew_account' => sub {
365 for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
366 my $dt = dt_from_string( $date, 'iso' );
367 Time::Fake->offset( $dt->epoch );
368 my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
369 my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
370 my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
371 my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
372 my $a_year_later_plus_a_month = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
373 my $patron_category = $builder->build(
374 { source => 'Category',
376 enrolmentperiod => 12,
377 enrolmentperioddate => undef,
381 my $patron = $builder->build(
382 { source => 'Borrower',
384 dateexpiry => $a_month_ago,
385 categorycode => $patron_category->{categorycode},
386 date_renewed => undef, # Force builder to not populate the column for new patron
390 my $patron_2 = $builder->build(
391 { source => 'Borrower',
393 dateexpiry => $a_month_ago,
394 categorycode => $patron_category->{categorycode},
398 my $patron_3 = $builder->build(
399 { source => 'Borrower',
401 dateexpiry => $a_month_later,
402 categorycode => $patron_category->{categorycode},
406 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
407 my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
408 my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
410 is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
412 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
413 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
414 my $expiry_date = $retrieved_patron->renew_account;
415 is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
416 my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
417 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" );
418 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
419 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
421 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
422 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
423 $expiry_date = $retrieved_patron->renew_account;
424 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
425 $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
426 is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
427 $retrieved_expiry_date = $retrieved_patron->dateexpiry;
428 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
429 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
430 is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
432 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
433 $expiry_date = $retrieved_patron_2->renew_account;
434 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
435 $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
436 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
438 $expiry_date = $retrieved_patron_3->renew_account;
439 is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
440 $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
441 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" );
443 $retrieved_patron->delete;
444 $retrieved_patron_2->delete;
445 $retrieved_patron_3->delete;
450 subtest "move_to_deleted" => sub {
452 my $originally_updated_on = '2016-01-01 12:12:12';
453 my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
454 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
455 is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
456 ; # FIXME This should be Koha::Deleted::Patron
457 my $deleted_patron = $schema->resultset('Deletedborrower')
458 ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
460 ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
461 ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
462 isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
463 $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
464 is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
465 $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup
468 subtest "delete" => sub {
470 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
471 my $patron = $builder->build( { source => 'Borrower' } );
472 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
473 my $hold = $builder->build(
474 { source => 'Reserve',
475 value => { borrowernumber => $patron->{borrowernumber} }
478 my $list = $builder->build(
479 { source => 'Virtualshelve',
480 value => { owner => $patron->{borrowernumber} }
483 my $modification = $builder->build_object({ class => 'Koha::Patron::Modifications', value => { borrowernumber => $patron->{borrowernumber} } });
485 my $deleted = $retrieved_patron->delete;
486 is( ref($deleted), 'Koha::Patron', 'Koha::Patron->delete should return the deleted patron object if the patron has been correctly deleted' );
488 is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
490 is (Koha::Old::Holds->search( { reserve_id => $hold->{ reserve_id } } )->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| );
492 is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have cancelled patron's holds 2| );
494 is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
496 is( Koha::Patron::Modifications->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's modifications| );
498 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
499 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
502 subtest 'Koha::Patrons->delete' => sub {
505 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
506 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
507 my $id1 = $patron1->borrowernumber;
508 my $set = Koha::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
509 is( $set->count, 2, 'Two patrons found as expected' );
510 is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
511 my $deleted_patrons = Koha::Old::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
512 is( $deleted_patrons->count, 2, 'Patrons moved to deletedborrowers' );
514 # See other tests in t/db_dependent/Koha/Objects.t
517 subtest 'add_enrolment_fee_if_needed' => sub {
520 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
521 foreach( keys %{$enrolmentfees} ) {
522 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
524 my $enrolmentfee_K = $enrolmentfees->{K};
525 my $enrolmentfee_J = $enrolmentfees->{J};
526 my $enrolmentfee_YA = $enrolmentfees->{YA};
528 my %borrower_data = (
529 firstname => 'my firstname',
530 surname => 'my surname',
532 branchcode => $library->{branchcode},
535 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
536 $borrower_data{borrowernumber} = $borrowernumber;
538 my $patron = Koha::Patrons->find( $borrowernumber );
539 my $total = $patron->account->balance;
540 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
542 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
543 $borrower_data{categorycode} = 'J';
544 $patron->set(\%borrower_data)->store;
545 $total = $patron->account->balance;
546 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
548 $borrower_data{categorycode} = 'K';
549 $patron->set(\%borrower_data)->store;
550 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
552 $borrower_data{categorycode} = 'J';
553 $patron->set(\%borrower_data)->store;
554 $total = $patron->account->balance;
555 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
557 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
558 $patron->categorycode('YA')->store;
559 $total = $patron->account->balance;
561 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
562 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
568 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
571 my $library = $builder->build( { source => 'Branch' } );
572 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
573 my $item_1 = $builder->build(
577 homebranch => $library->{branchcode},
578 holdingbranch => $library->{branchcode},
579 biblionumber => $biblionumber_1,
585 my $item_2 = $builder->build(
589 homebranch => $library->{branchcode},
590 holdingbranch => $library->{branchcode},
591 biblionumber => $biblionumber_1,
597 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
598 my $item_3 = $builder->build(
602 homebranch => $library->{branchcode},
603 holdingbranch => $library->{branchcode},
604 biblionumber => $biblionumber_2,
610 my $patron = $builder->build(
612 source => 'Borrower',
613 value => { branchcode => $library->{branchcode} }
617 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
618 my $checkouts = $patron->checkouts;
619 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
620 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
621 my $pending_checkouts = $patron->pending_checkouts;
622 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
623 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
624 my $old_checkouts = $patron->old_checkouts;
625 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
626 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
628 # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
629 $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
631 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
633 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
634 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
635 AddIssue( $patron, $item_3->{barcode} );
637 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
638 $checkouts = $patron->checkouts;
639 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
640 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
641 $pending_checkouts = $patron->pending_checkouts;
642 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
643 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
645 my $first_checkout = $pending_checkouts->next;
646 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
648 my $overdues = $patron->get_overdues;
649 is( $overdues->count, 2, 'Patron should have 2 overdues');
650 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
651 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
652 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
655 C4::Circulation::AddReturn( $item_1->{barcode} );
656 C4::Circulation::AddReturn( $item_2->{barcode} );
657 $old_checkouts = $patron->old_checkouts;
658 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
659 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
662 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
666 subtest 'get_routing_lists' => sub {
669 my $biblio = Koha::Biblio->new()->store();
670 my $subscription = Koha::Subscription->new({
671 biblionumber => $biblio->biblionumber,
675 my $patron = $builder->build( { source => 'Borrower' } );
676 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
678 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
680 my $routinglist_count = Koha::Subscription::Routinglists->count;
681 my $routinglist = Koha::Subscription::Routinglist->new({
682 borrowernumber => $patron->borrowernumber,
684 subscriptionid => $subscription->subscriptionid
687 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
689 my $routinglists = $patron->get_routing_lists;
690 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
691 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
693 my $subscription2 = Koha::Subscription->new({
694 biblionumber => $biblio->biblionumber,
697 my $routinglist2 = Koha::Subscription::Routinglist->new({
698 borrowernumber => $patron->borrowernumber,
700 subscriptionid => $subscription2->subscriptionid
703 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
705 $patron->delete; # Clean up for later tests
709 subtest 'get_age' => sub {
712 my $patron = $builder->build( { source => 'Borrower' } );
713 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
717 today => '2020-02-28',
718 has_12 => { date => '2007-08-27', expected_age => 12 },
719 almost_18 => { date => '2002-03-01', expected_age => 17 },
720 has_18_today => { date => '2002-02-28', expected_age => 18 },
721 had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
722 almost_16 => { date => '2004-02-29', expected_age => 15 },
723 has_16_today => { date => '2004-02-28', expected_age => 16 },
724 had_16_yesterday => { date => '2004-02-27', expected_age => 16 },
725 new_born => { date => '2020-01-27', expected_age => 0 },
728 today => '2020-02-29',
729 has_12 => { date => '2007-08-27', expected_age => 12 },
730 almost_18 => { date => '2002-03-01', expected_age => 17 },
731 has_18_today => { date => '2002-02-28', expected_age => 18 },
732 had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
733 almost_16 => { date => '2004-03-01', expected_age => 15 },
734 has_16_today => { date => '2004-02-29', expected_age => 16 },
735 had_16_yesterday => { date => '2004-02-28', expected_age => 16 },
736 new_born => { date => '2020-01-27', expected_age => 0 },
739 today => '2020-03-01',
740 has_12 => { date => '2007-08-27', expected_age => 12 },
741 almost_18 => { date => '2002-03-02', expected_age => 17 },
742 has_18_today => { date => '2002-03-01', expected_age => 18 },
743 had_18_yesterday => { date => '2002-02-28', expected_age => 18 },
744 almost_16 => { date => '2004-03-02', expected_age => 15 },
745 has_16_today => { date => '2004-03-01', expected_age => 16 },
746 had_16_yesterday => { date => '2004-02-29', expected_age => 16 },
749 today => '2019-01-31',
750 has_12 => { date => '2006-08-27', expected_age => 12 },
751 almost_18 => { date => '2001-02-01', expected_age => 17 },
752 has_18_today => { date => '2001-01-31', expected_age => 18 },
753 had_18_yesterday => { date => '2001-01-30', expected_age => 18 },
754 almost_16 => { date => '2003-02-01', expected_age => 15 },
755 has_16_today => { date => '2003-01-31', expected_age => 16 },
756 had_16_yesterday => { date => '2003-01-30', expected_age => 16 },
760 $patron->dateofbirth( undef );
761 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
763 for my $date ( @dates ) {
765 my $dt = dt_from_string($date->{today});
767 Time::Fake->offset( $dt->epoch );
769 for my $k ( keys %$date ) {
770 next if $k eq 'today';
772 my $dob = $date->{$k};
773 $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
776 $dob->{expected_age},
778 "Today=%s, dob=%s, should be %d",
779 $date->{today}, $dob->{date}, $dob->{expected_age}
791 subtest 'is_valid_age' => sub {
794 my $dt = dt_from_string('2020-02-28');
796 Time::Fake->offset( $dt->epoch );
798 my $category = $builder->build({
799 source => 'Category',
801 categorycode => 'AGE_5_10',
802 dateofbirthrequired => 5,
806 $category = Koha::Patron::Categories->find( $category->{categorycode} );
808 my $patron = $builder->build({
809 source => 'Borrower',
811 categorycode => 'AGE_5_10'
814 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
817 $patron->dateofbirth( undef );
818 is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
822 today => '2020-02-28',
824 { date => '2007-08-27', expected_age => 12, valid => 0 },
826 { date => '2016-08-27', expected_age => 3, valid => 0 },
828 { date => '2015-02-28', expected_age => 7, valid => 1 },
830 { date => '2015-02-28', expected_age => 5, valid => 1 },
832 { date => '2015-03-01', expected_age => 5, valid => 0 },
834 { date => '2015-02-27', expected_age => 5, valid => 1 },
836 { date => '2009-02-28', expected_age => 11, valid => 0 },
838 { date => '2009-03-01', expected_age => 11, valid => 1 },
840 { date => '2009-02-27', expected_age => 11, valid => 0 },
844 for my $date ( @dates ) {
846 my $dt = dt_from_string($date->{today});
848 Time::Fake->offset( $dt->epoch );
850 for my $k ( keys %$date ) {
851 next if $k eq 'today';
853 my $dob = $date->{$k};
854 $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
856 $patron->is_valid_age,
859 "Today=%s, dob=%s, is %s, should be valid=%s",
860 $date->{today}, $dob->{date}, $dob->{expected_age}, $dob->{valid}
873 subtest 'account' => sub {
876 my $patron = $builder->build({source => 'Borrower'});
878 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
879 my $account = $patron->account;
880 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
885 subtest 'search_upcoming_membership_expires' => sub {
888 my $expiry_days = 15;
889 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
890 my $nb_of_days_before = 1;
891 my $nb_of_days_after = 2;
893 my $builder = t::lib::TestBuilder->new();
895 my $library = $builder->build({ source => 'Branch' });
897 # before we add borrowers to this branch, add the expires we have now
898 # note that this pertains to the current mocked setting of the pref
899 # for this reason we add the new branchcode to most of the tests
900 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
902 my $patron_1 = $builder->build({
903 source => 'Borrower',
905 branchcode => $library->{branchcode},
906 dateexpiry => dt_from_string->add( days => $expiry_days )
910 my $patron_2 = $builder->build({
911 source => 'Borrower',
913 branchcode => $library->{branchcode},
914 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
918 my $patron_3 = $builder->build({
919 source => 'Borrower',
921 branchcode => $library->{branchcode},
922 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
926 # Test without extra parameters
927 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
928 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
931 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
932 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
933 my $expired = $upcoming_mem_expires->next;
934 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
935 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
936 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
938 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
939 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
940 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
942 # Test MembershipExpiryDaysNotice == undef
943 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
944 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
945 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
947 # Test the before parameter
948 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
949 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
950 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
951 # Test after parameter also
952 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
953 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
954 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
957 subtest 'holds and old_holds' => sub {
960 my $library = $builder->build( { source => 'Branch' } );
961 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
962 my $item_1 = $builder->build(
966 homebranch => $library->{branchcode},
967 holdingbranch => $library->{branchcode},
968 biblionumber => $biblionumber_1
972 my $item_2 = $builder->build(
976 homebranch => $library->{branchcode},
977 holdingbranch => $library->{branchcode},
978 biblionumber => $biblionumber_1
982 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
983 my $item_3 = $builder->build(
987 homebranch => $library->{branchcode},
988 holdingbranch => $library->{branchcode},
989 biblionumber => $biblionumber_2
993 my $patron = $builder->build(
995 source => 'Borrower',
996 value => { branchcode => $library->{branchcode} }
1000 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1001 my $holds = $patron->holds;
1002 is( ref($holds), 'Koha::Holds',
1003 'Koha::Patron->holds should return a Koha::Holds objects' );
1004 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
1006 C4::Reserves::AddReserve(
1008 branchcode => $library->{branchcode},
1009 borrowernumber => $patron->borrowernumber,
1010 biblionumber => $biblionumber_1
1014 C4::Reserves::AddReserve(
1016 branchcode => $library->{branchcode},
1017 borrowernumber => $patron->borrowernumber,
1018 biblionumber => $biblionumber_2,
1019 expiration_date => dt_from_string->add( days => 2 )
1023 $holds = $patron->holds;
1024 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
1026 my $old_holds = $patron->old_holds;
1027 is( ref($old_holds), 'Koha::Old::Holds',
1028 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
1029 is( $old_holds->count, 0, 'There should not be any old holds yet');
1031 my $hold = $holds->next;
1034 $old_holds = $patron->old_holds;
1035 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
1042 subtest 'notice_email_address' => sub {
1045 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1047 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
1048 is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
1050 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
1051 is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
1056 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
1059 # TODO create a subroutine in t::lib::Mocks
1060 my $branch = $builder->build({ source => 'Branch' });
1061 my $userenv_patron = $builder->build_object({
1062 class => 'Koha::Patrons',
1063 value => { branchcode => $branch->{branchcode}, flags => 0 },
1065 t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
1067 my $anonymous = $builder->build( { source => 'Borrower', }, );
1069 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
1071 subtest 'patron privacy is 1 (default)' => sub {
1074 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1075 my $patron = $builder->build(
1076 { source => 'Borrower',
1077 value => { privacy => 1, }
1080 my $item_1 = $builder->build(
1088 my $issue_1 = $builder->build(
1089 { source => 'Issue',
1091 borrowernumber => $patron->{borrowernumber},
1092 itemnumber => $item_1->{itemnumber},
1096 my $item_2 = $builder->build(
1104 my $issue_2 = $builder->build(
1105 { source => 'Issue',
1107 borrowernumber => $patron->{borrowernumber},
1108 itemnumber => $item_2->{itemnumber},
1113 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1114 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, dt_from_string('2011-11-11') );
1115 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
1117 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
1118 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
1120 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
1121 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1123 $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1124 is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
1126 my $dbh = C4::Context->dbh;
1127 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
1128 $sth->execute($item_1->{itemnumber});
1129 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1130 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
1131 $sth->execute($item_2->{itemnumber});
1132 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1133 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
1135 $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
1136 $sth->execute($item_2->{itemnumber});
1137 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1138 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
1140 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
1141 $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
1142 $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
1143 $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
1144 $sth->execute($item_1->{itemnumber});
1145 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1146 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
1147 $sth->execute($item_2->{itemnumber});
1148 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1149 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
1151 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1154 subtest 'patron privacy is 0 (forever)' => sub {
1157 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1158 my $patron = $builder->build(
1159 { source => 'Borrower',
1160 value => { privacy => 0, }
1163 my $item = $builder->build(
1171 my $issue = $builder->build(
1172 { source => 'Issue',
1174 borrowernumber => $patron->{borrowernumber},
1175 itemnumber => $item->{itemnumber},
1180 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1181 is( $returned, 1, 'The item should have been returned' );
1183 my $dbh = C4::Context->dbh;
1184 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1185 SELECT borrowernumber FROM old_issues where itemnumber = ?
1186 |, undef, $item->{itemnumber});
1187 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1188 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1191 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1193 subtest 'AnonymousPatron is not defined' => sub {
1196 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1197 my $patron = $builder->build(
1198 { source => 'Borrower',
1199 value => { privacy => 1, }
1202 my $item = $builder->build(
1210 my $issue = $builder->build(
1211 { source => 'Issue',
1213 borrowernumber => $patron->{borrowernumber},
1214 itemnumber => $item->{itemnumber},
1219 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1220 is( $returned, 1, 'The item should have been returned' );
1221 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
1222 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1224 my $dbh = C4::Context->dbh;
1225 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1226 SELECT borrowernumber FROM old_issues where itemnumber = ?
1227 |, undef, $item->{itemnumber});
1228 is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
1229 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1232 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1234 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1235 my $patron = $builder->build(
1236 { source => 'Borrower',
1237 value => { privacy => 1 } # Another branchcode than the logged in librarian
1240 my $item = $builder->build(
1248 my $issue = $builder->build(
1249 { source => 'Issue',
1251 borrowernumber => $patron->{borrowernumber},
1252 itemnumber => $item->{itemnumber},
1257 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1258 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1259 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1262 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1263 $userenv_patron->delete;
1265 # Reset IndependentBranches for further tests
1266 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1269 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1277 $nb_of_patrons = Koha::Patrons->search->count;
1278 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1279 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1280 my $library_11 = $builder->build( { source => 'Branch' } );
1281 my $library_12 = $builder->build( { source => 'Branch' } );
1282 my $library_21 = $builder->build( { source => 'Branch' } );
1283 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1284 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1285 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1286 Koha::Library::Group->new(
1287 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1288 Koha::Library::Group->new(
1289 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1290 Koha::Library::Group->new(
1291 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1293 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1294 # 2 patrons from library_11 (group1)
1295 # patron_11_1 see patron's infos from outside its group
1296 # Setting flags => undef to not be considered as superlibrarian
1297 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1298 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1299 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1300 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1301 # patron_11_2 can only see patron's info from its group
1302 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1303 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1304 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1305 # 1 patron from library_12 (group1)
1306 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1307 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1308 # 1 patron from library_21 (group2) can only see patron's info from its group
1309 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1310 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1311 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1313 # Pfiou, we can start now!
1314 subtest 'libraries_where_can_see_patrons' => sub {
1319 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1320 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1321 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1323 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1324 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1325 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| );
1327 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1328 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1329 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| );
1331 subtest 'can_see_patron_infos' => sub {
1334 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1335 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1336 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1337 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1339 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1340 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1341 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1342 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1344 subtest 'search_limited' => sub {
1347 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1348 my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1349 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1350 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1352 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1353 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1354 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' );
1356 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1357 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1358 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1360 $patron_11_1->delete;
1361 $patron_11_2->delete;
1366 subtest 'account_locked' => sub {
1368 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1369 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1370 for my $value ( undef, '', 0 ) {
1371 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1372 $patron->login_attempts(0)->store;
1373 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1374 $patron->login_attempts(1)->store;
1375 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1376 $patron->login_attempts(-1)->store;
1377 is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1380 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1381 $patron->login_attempts(2)->store;
1382 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1383 $patron->login_attempts(3)->store;
1384 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1385 $patron->login_attempts(4)->store;
1386 is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1387 $patron->login_attempts(-1)->store;
1388 is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1393 subtest 'is_child | is_adult' => sub {
1395 my $category = $builder->build_object(
1397 class => 'Koha::Patron::Categories',
1398 value => { category_type => 'A' }
1401 my $patron_adult = $builder->build_object(
1403 class => 'Koha::Patrons',
1404 value => { categorycode => $category->categorycode }
1407 $category = $builder->build_object(
1409 class => 'Koha::Patron::Categories',
1410 value => { category_type => 'I' }
1413 my $patron_adult_i = $builder->build_object(
1415 class => 'Koha::Patrons',
1416 value => { categorycode => $category->categorycode }
1419 $category = $builder->build_object(
1421 class => 'Koha::Patron::Categories',
1422 value => { category_type => 'C' }
1425 my $patron_child = $builder->build_object(
1427 class => 'Koha::Patrons',
1428 value => { categorycode => $category->categorycode }
1431 $category = $builder->build_object(
1433 class => 'Koha::Patron::Categories',
1434 value => { category_type => 'O' }
1437 my $patron_other = $builder->build_object(
1439 class => 'Koha::Patrons',
1440 value => { categorycode => $category->categorycode }
1443 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1444 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1445 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1446 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1448 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1449 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1450 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1451 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1454 $patron_adult->delete;
1455 $patron_adult_i->delete;
1456 $patron_child->delete;
1457 $patron_other->delete;
1460 subtest 'get_overdues' => sub {
1463 my $library = $builder->build( { source => 'Branch' } );
1464 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1465 my $item_1 = $builder->build(
1469 homebranch => $library->{branchcode},
1470 holdingbranch => $library->{branchcode},
1471 biblionumber => $biblionumber_1
1475 my $item_2 = $builder->build(
1479 homebranch => $library->{branchcode},
1480 holdingbranch => $library->{branchcode},
1481 biblionumber => $biblionumber_1
1485 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1486 my $item_3 = $builder->build(
1490 homebranch => $library->{branchcode},
1491 holdingbranch => $library->{branchcode},
1492 biblionumber => $biblionumber_2
1496 my $patron = $builder->build(
1498 source => 'Borrower',
1499 value => { branchcode => $library->{branchcode} }
1503 t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1505 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1506 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1507 AddIssue( $patron, $item_3->{barcode} );
1509 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1510 my $overdues = $patron->get_overdues;
1511 is( $overdues->count, 2, 'Patron should have 2 overdues');
1512 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1513 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1515 my $o = $overdues->reset->next;
1516 my $unblessed_overdue = $o->unblessed_all_relateds;
1517 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1518 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1519 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1520 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1523 $patron->checkouts->delete;
1527 subtest 'userid_is_valid' => sub {
1530 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1531 my $patron_category = $builder->build_object(
1533 class => 'Koha::Patron::Categories',
1534 value => { category_type => 'P', enrolmentfee => 0 }
1538 cardnumber => "123456789",
1539 firstname => "Tomasito",
1541 categorycode => $patron_category->categorycode,
1542 branchcode => $library->branchcode,
1545 my $expected_userid_patron_1 = 'tomasito.none';
1546 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1547 my $patron_1 = Koha::Patrons->find($borrowernumber);
1548 is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1549 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1551 $patron_1->userid( 'tomasito.non' );
1552 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1553 1, 'recently created userid -> unique (borrowernumber passed)' );
1555 $patron_1->userid( 'tomasitoxxx' );
1556 is( $patron_1->has_valid_userid,
1557 1, 'non-existent userid -> unique (borrowernumber passed)' );
1558 $patron_1->discard_changes; # We compare with the original userid later
1560 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1561 is( $patron_not_in_storage->has_valid_userid,
1562 0, 'userid exists for another patron, patron is not in storage yet' );
1564 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1565 is( $patron_not_in_storage->has_valid_userid,
1566 1, 'non-existent userid, patron is not in storage yet' );
1568 # Regression tests for BZ12226
1569 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1570 is( $db_patron->has_valid_userid,
1571 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1573 # Add a new borrower with the same userid but different cardnumber
1574 $data{cardnumber} = "987654321";
1575 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1576 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1577 $patron_2->userid($patron_1->userid);
1578 is( $patron_2->has_valid_userid,
1579 0, 'The userid is already in used, it cannot be used for another patron' );
1581 my $new_userid = 'a_user_id';
1582 $data{cardnumber} = "234567890";
1583 $data{userid} = 'a_user_id';
1584 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1585 my $patron_3 = Koha::Patrons->find($borrowernumber);
1586 is( $patron_3->userid, $new_userid,
1587 'Koha::Patron->store should insert the given userid' );
1595 subtest 'generate_userid' => sub {
1598 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1599 my $patron_category = $builder->build_object(
1601 class => 'Koha::Patron::Categories',
1602 value => { category_type => 'P', enrolmentfee => 0 }
1606 cardnumber => "123456789",
1607 firstname => "Tômà sÃtó",
1608 surname => "Ñoné",
1609 categorycode => $patron_category->categorycode,
1610 branchcode => $library->branchcode,
1613 my $expected_userid_patron_1 = 'tomasito.none';
1614 my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1615 $new_patron->generate_userid;
1616 my $userid = $new_patron->userid;
1617 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1618 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1619 my $patron_1 = Koha::Patrons->find($borrowernumber);
1620 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1622 $new_patron->generate_userid;
1623 $userid = $new_patron->userid;
1624 is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1625 $data{cardnumber} = '987654321';
1626 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1627 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1628 isnt( $patron_2->userid, 'tomasito',
1629 "Patron with duplicate userid has new userid generated" );
1630 is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1631 "Patron with duplicate userid has new userid generated (1 is appened" );
1633 $new_patron->generate_userid;
1634 $userid = $new_patron->userid;
1635 is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1637 $patron_1 = Koha::Patrons->find($borrowernumber);
1638 $patron_1->userid(undef);
1639 $patron_1->generate_userid;
1640 $userid = $patron_1->userid;
1641 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1648 $nb_of_patrons = Koha::Patrons->search->count;
1649 $retrieved_patron_1->delete;
1650 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1652 subtest 'BorrowersLog tests' => sub {
1655 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1656 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1658 my $cardnumber = $patron->cardnumber;
1659 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1662 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1663 my $log_info = from_json( $logs[0]->info );
1664 is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1665 is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1666 is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1668 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1669 $patron->track_login();
1670 @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1671 is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1674 $schema->storage->txn_rollback;
1676 subtest 'Test Koha::Patrons::merge' => sub {
1679 my $schema = Koha::Database->new()->schema();
1681 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1683 $schema->storage->txn_begin;
1685 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1686 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1687 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1689 while (my ($r, $field) = each(%$resultsets)) {
1690 $builder->build({ source => $r, value => { $field => $keeper->id } });
1691 $builder->build({ source => $r, value => { $field => $loser_1 } });
1692 $builder->build({ source => $r, value => { $field => $loser_2 } });
1695 $schema->resultset($r)->search( { $field => $keeper->id } );
1696 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1699 $schema->resultset($r)->search( { $field => $loser_1 } );
1700 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1703 $schema->resultset($r)->search( { $field => $loser_2 } );
1704 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1707 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1709 while (my ($r, $field) = each(%$resultsets)) {
1711 $schema->resultset($r)->search( {$field => $keeper->id } );
1712 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1715 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1716 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1718 $schema->storage->txn_rollback;
1721 subtest '->store' => sub {
1723 my $schema = Koha::Database->new->schema;
1724 $schema->storage->txn_begin;
1726 my $print_error = $schema->storage->dbh->{PrintError};
1727 $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1729 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1730 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1733 { $patron_2->userid($patron_1->userid)->store; }
1734 'Koha::Exceptions::Object::DuplicateID',
1735 'Koha::Patron->store raises an exception on duplicate ID';
1738 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1739 my $password = 'password';
1740 $patron_1->set_password({ password => $password });
1741 like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1742 my $digest = $patron_1->password;
1743 $patron_1->surname('xxx')->store;
1744 is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1746 # Test uppercasesurnames
1747 t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 );
1748 my $surname = lc $patron_1->surname;
1749 $patron_1->surname($surname)->store;
1750 isnt( $patron_1->surname, $surname,
1751 'Surname converts to uppercase on store.');
1752 t::lib::Mocks::mock_preference( 'uppercasesurnames', 0 );
1753 $patron_1->surname($surname)->store;
1754 is( $patron_1->surname, $surname,
1755 'Surname remains unchanged on store.');
1758 $patron_1->relationship("")->store;
1759 is( $patron_1->relationship, undef, );
1761 $schema->storage->dbh->{PrintError} = $print_error;
1762 $schema->storage->txn_rollback;
1764 subtest 'skip updated_on for BorrowersLog' => sub {
1766 $schema->storage->txn_begin;
1767 t::lib::Mocks::mock_preference('BorrowersLog', 1);
1768 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1769 $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1770 my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1771 is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1772 $schema->storage->txn_rollback;
1776 subtest '->set_password' => sub {
1780 $schema->storage->txn_begin;
1782 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1784 # Disable logging password changes for this tests
1785 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1787 # Password-length tests
1788 t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1789 throws_ok { $patron->set_password({ password => 'ab' }); }
1790 'Koha::Exceptions::Password::TooShort',
1791 'minPasswordLength is undef, fall back to 3, fail test';
1793 'Password length (2) is shorter than required (3)',
1794 'Exception parameters passed correctly'
1797 t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1798 throws_ok { $patron->set_password({ password => 'ab' }); }
1799 'Koha::Exceptions::Password::TooShort',
1800 'minPasswordLength is 2, fall back to 3, fail test';
1802 t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1803 throws_ok { $patron->set_password({ password => 'abcb' }); }
1804 'Koha::Exceptions::Password::TooShort',
1805 'minPasswordLength is 5, fail test';
1807 # Trailing spaces tests
1808 throws_ok { $patron->set_password({ password => 'abcD12d ' }); }
1809 'Koha::Exceptions::Password::WhitespaceCharacters',
1810 'Password contains trailing spaces, exception is thrown';
1812 # Require strong password tests
1813 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1814 throws_ok { $patron->set_password({ password => 'abcd a' }); }
1815 'Koha::Exceptions::Password::TooWeak',
1816 'Password is too weak, exception is thrown';
1818 # Refresh patron from DB, just to make sure
1819 $patron->discard_changes;
1820 is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1822 $patron->set_password({ password => 'abcD12 34' });
1823 $patron->discard_changes;
1825 is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1827 lives_ok { $patron->set_password({ password => 'abcd a', skip_validation => 1 }) }
1828 'Password is weak, but skip_validation was passed, so no exception thrown';
1831 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1832 $patron->login_attempts(3)->store;
1833 my $old_digest = $patron->password;
1834 $patron->set_password({ password => 'abcd a' });
1835 $patron->discard_changes;
1837 isnt( $patron->password, $old_digest, 'Password has been updated' );
1838 ok( checkpw_hash('abcd a', $patron->password), 'Password hash is correct' );
1839 is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1841 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1842 is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1844 # Enable logging password changes
1845 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1846 $patron->set_password({ password => 'abcd b' });
1848 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1849 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1851 $schema->storage->txn_rollback;
1854 $schema->storage->txn_begin;
1855 subtest 'search_unsubscribed' => sub {
1858 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1859 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
1860 is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
1862 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1863 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1865 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
1866 Koha::Patron::Consents->delete; # for correct counts
1867 Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string })->store;
1868 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
1870 # Add another refusal but shift the period
1871 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
1872 Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string->subtract(days=>2) })->store;
1873 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
1875 # Try another (special) attempts setting
1876 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
1877 # Lockout is now disabled
1878 # Patron2 still matches: refused earlier, not locked
1879 is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
1882 subtest 'search_anonymize_candidates' => sub {
1884 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1885 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1886 $patron1->anonymized(0);
1887 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1888 $patron2->anonymized(0);
1889 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1891 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
1892 is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
1894 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
1895 my $cnt = Koha::Patrons->search_anonymize_candidates->count;
1896 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1897 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1898 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
1900 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
1901 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1902 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1903 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1904 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1905 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1906 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
1908 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
1909 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1910 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1911 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1912 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1913 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1914 is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
1916 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1917 $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1918 $patron1->login_attempts(0)->store;
1919 $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1920 $patron2->login_attempts(0)->store;
1921 $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
1922 $patron1->login_attempts(3)->store;
1923 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1924 $cnt+1, 'Locked flag' );
1926 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1927 # Patron 1 still on 3 == locked
1928 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1929 $cnt+1, 'Still expect same number for FailedLoginAttempts empty' );
1930 $patron1->login_attempts(0)->store;
1932 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1933 $cnt, 'Patron 1 unlocked' );
1936 subtest 'search_anonymized' => sub {
1938 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1940 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
1941 is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
1943 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
1944 $patron1->dateexpiry( dt_from_string );
1945 $patron1->anonymized(0)->store;
1946 my $cnt = Koha::Patrons->search_anonymized->count;
1947 $patron1->anonymized(1)->store;
1948 is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
1949 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1950 is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
1953 subtest 'lock' => sub {
1956 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1957 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1958 my $hold = $builder->build_object({
1959 class => 'Koha::Holds',
1960 value => { borrowernumber => $patron1->borrowernumber },
1963 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1964 my $expiry = dt_from_string->add(days => 1);
1965 $patron1->dateexpiry( $expiry );
1967 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1968 is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
1969 is( $patron1->holds->count, 1, 'No holds removed' );
1971 $patron1->lock({ expire => 1, remove => 1});
1972 isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
1973 is( $patron1->holds->count, 0, 'Holds removed' );
1975 # Disable lockout feature
1976 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1977 $patron1->login_attempts(0);
1978 $patron1->dateexpiry( $expiry );
1981 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1983 # Trivial wrapper test (Koha::Patrons->lock)
1984 $patron1->login_attempts(0)->store;
1985 Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
1986 $patron1->discard_changes; # refresh
1987 $patron2->discard_changes;
1988 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
1989 is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
1992 subtest 'anonymize' => sub {
1995 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1996 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1998 # First try patron with issues
1999 my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
2000 warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
2003 t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
2004 my $surname = $patron1->surname; # expect change, no clear
2005 my $branchcode = $patron1->branchcode; # expect skip
2006 $patron1->anonymize;
2007 is($patron1->anonymized, 1, 'Check flag' );
2009 is( $patron1->dateofbirth, undef, 'Birth date cleared' );
2010 is( $patron1->firstname, undef, 'First name cleared' );
2011 isnt( $patron1->surname, $surname, 'Surname changed' );
2012 ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
2013 is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
2014 is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
2016 # Test wrapper in Koha::Patrons
2017 $patron1->surname($surname)->store; # restore
2018 my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
2019 $patron1->discard_changes; # refresh
2020 isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
2021 $patron2->discard_changes; # refresh
2022 is( $patron2->firstname, undef, 'First name patron2 cleared' );
2024 $schema->storage->txn_rollback;
2026 subtest 'extended_attributes' => sub {
2028 my $schema = Koha::Database->new->schema;
2029 $schema->storage->txn_begin;
2031 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
2032 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
2034 t::lib::Mocks::mock_userenv({ patron => $patron_1 });
2036 my $attribute_type1 = Koha::Patron::Attribute::Type->new(
2039 description => 'my description1',
2043 my $attribute_type2 = Koha::Patron::Attribute::Type->new(
2046 description => 'my description2',
2048 staff_searchable => 1
2052 my $attribute_type3 = $builder->build_object({ class => 'Koha::Patron::Attribute::Types' });
2054 my $deleted_attribute_type = $builder->build_object({ class => 'Koha::Patron::Attribute::Types' });
2055 my $deleted_attribute_type_code = $deleted_attribute_type->code;
2056 $deleted_attribute_type->delete;
2058 my $new_library = $builder->build( { source => 'Branch' } );
2059 my $attribute_type_limited = Koha::Patron::Attribute::Type->new(
2060 { code => 'my code3', description => 'my description3' } )->store;
2061 $attribute_type_limited->library_limits( [ $new_library->{branchcode} ] );
2063 my $attributes_for_1 = [
2065 attribute => 'my attribute1',
2066 code => $attribute_type1->code(),
2069 attribute => 'my attribute2',
2070 code => $attribute_type2->code(),
2073 attribute => 'my attribute limited',
2074 code => $attribute_type_limited->code(),
2078 my $attributes_for_2 = [
2080 attribute => 'my attribute12',
2081 code => $attribute_type1->code(),
2084 attribute => 'my attribute limited 2',
2085 code => $attribute_type_limited->code(),
2088 attribute => 'my nonexistent attribute 2',
2089 code => $deleted_attribute_type_code,
2093 my $extended_attributes = $patron_1->extended_attributes;
2094 is( ref($extended_attributes), 'Koha::Patron::Attributes', 'Koha::Patron->extended_attributes must return a Koha::Patron::Attribute set' );
2095 is( $extended_attributes->count, 0, 'There should not be attribute yet');
2097 $patron_1->extended_attributes->filter_by_branch_limitations->delete;
2098 $patron_2->extended_attributes->filter_by_branch_limitations->delete;
2099 $patron_1->extended_attributes($attributes_for_1);
2102 $patron_2->extended_attributes($attributes_for_2);
2103 } [ qr/a foreign key constraint fails/ ], 'nonexistent attribute should have not exploded but print a warning';
2105 my $extended_attributes_for_1 = $patron_1->extended_attributes;
2106 is( $extended_attributes_for_1->count, 3, 'There should be 3 attributes now for patron 1');
2108 my $extended_attributes_for_2 = $patron_2->extended_attributes;
2109 is( $extended_attributes_for_2->count, 2, 'There should be 2 attributes now for patron 2');
2111 my $attribute_12 = $extended_attributes_for_2->search({ code => $attribute_type1->code });
2112 is( $attribute_12->next->attribute, 'my attribute12', 'search by code should return the correct attribute' );
2114 $attribute_12 = $patron_2->get_extended_attribute( $attribute_type1->code );
2115 is( $attribute_12->attribute, 'my attribute12', 'Koha::Patron->get_extended_attribute should return the correct attribute value' );
2118 $extended_attributes_for_2 = $patron_2->extended_attributes->merge_with(
2121 attribute => 'my attribute12 XXX',
2122 code => $attribute_type1->code(),
2125 attribute => 'my nonexistent attribute 2',
2126 code => $deleted_attribute_type_code,
2129 attribute => 'my attribute 3', # Adding a new attribute using merge_with
2130 code => $attribute_type3->code,
2135 "Cannot merge element: unrecognized code = '$deleted_attribute_type_code'",
2136 "Trying to merge_with using a nonexistent attribute code should display a warning";
2138 is( @$extended_attributes_for_2, 3, 'There should be 3 attributes now for patron 3');
2139 my $expected_attributes_for_2 = [
2141 code => $attribute_type1->code(),
2142 attribute => 'my attribute12 XXX',
2145 code => $attribute_type_limited->code(),
2146 attribute => 'my attribute limited 2',
2149 attribute => 'my attribute 3',
2150 code => $attribute_type3->code,
2153 # Sorting them by code
2154 $expected_attributes_for_2 = [ sort { $a->{code} cmp $b->{code} } @$expected_attributes_for_2 ];
2159 code => $extended_attributes_for_2->[0]->{code},
2160 attribute => $extended_attributes_for_2->[0]->{attribute}
2163 code => $extended_attributes_for_2->[1]->{code},
2164 attribute => $extended_attributes_for_2->[1]->{attribute}
2167 code => $extended_attributes_for_2->[2]->{code},
2168 attribute => $extended_attributes_for_2->[2]->{attribute}
2171 $expected_attributes_for_2
2174 # TODO - What about multiple? POD explains the problem
2175 my $non_existent = $patron_2->get_extended_attribute( 'not_exist' );
2176 is( $non_existent, undef, 'Koha::Patron->get_extended_attribute must return undef if the attribute does not exist' );
2178 # Test branch limitations
2179 t::lib::Mocks::mock_userenv({ patron => $patron_2 });
2181 $extended_attributes_for_1 = $patron_1->extended_attributes;
2182 is( $extended_attributes_for_1->count, 3, 'There should be 2 attributes for patron 1, the limited one should be returned');
2185 $extended_attributes_for_1 = $patron_1->extended_attributes->filter_by_branch_limitations;
2186 is( $extended_attributes_for_1->count, 2, 'There should be 2 attributes for patron 1, the limited one should be returned');
2189 my $limited_value = $patron_1->get_extended_attribute( $attribute_type_limited->code );
2190 is( $limited_value->attribute, 'my attribute limited', );
2192 ## Do we need a filtered?
2193 #$limited_value = $patron_1->get_extended_attribute( $attribute_type_limited->code );
2194 #is( $limited_value, undef, );
2196 $schema->storage->txn_rollback;