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 => 41;
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 'sms_provider' => sub {
93 my $sms_provider = $builder->build({source => 'SmsProvider' });
94 $retrieved_patron_1->sms_provider_id( $sms_provider->{id} )->store;
95 is_deeply( $retrieved_patron_1->sms_provider->unblessed, $sms_provider, 'Koha::Patron->sms_provider returns the correct SMS provider' );
96 is( ref($retrieved_patron_1->sms_provider), 'Koha::SMS::Provider', 'Koha::Patron->sms_provider should return a Koha::SMS::Provider object' );
99 subtest 'guarantees' => sub {
102 t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test|test2' );
104 my $guarantees = $new_patron_1->guarantee_relationships;
105 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
106 is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee relationships' );
107 my @guarantees = $new_patron_1->guarantee_relationships;
108 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantee_relationships should return an array in a list context' );
109 is( scalar(@guarantees), 0, 'new_patron_1 should have 0 guarantee' );
111 my $guarantee_1 = $builder->build({ source => 'Borrower' });
112 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
113 my $guarantee_2 = $builder->build({ source => 'Borrower' });
114 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
116 $guarantees = $new_patron_1->guarantee_relationships;
117 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantee_relationships should return a Koha::Patrons result set in a scalar context' );
118 is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
119 @guarantees = $new_patron_1->guarantee_relationships;
120 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantee_relationships should return an array in a list context' );
121 is( scalar(@guarantees), 2, 'new_patron_1 should have 2 guarantees' );
122 $_->delete for @guarantees;
124 #Test return order of guarantees BZ 18635
125 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
126 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
128 my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
130 my $order_guarantee1 = $builder->build_object(
132 class => 'Koha::Patrons',
138 $builder->build_object(
140 class => 'Koha::Patron::Relationships',
142 guarantor_id => $guarantor->id,
143 guarantee_id => $order_guarantee1,
144 relationship => 'test',
149 my $order_guarantee2 = $builder->build_object(
151 class => 'Koha::Patrons',
157 $builder->build_object(
159 class => 'Koha::Patron::Relationships',
161 guarantor_id => $guarantor->id,
162 guarantee_id => $order_guarantee2,
163 relationship => 'test',
168 my $order_guarantee3 = $builder->build_object(
170 class => 'Koha::Patrons',
173 firstname => 'Walrus',
177 $builder->build_object(
179 class => 'Koha::Patron::Relationships',
181 guarantor_id => $guarantor->id,
182 guarantee_id => $order_guarantee3,
183 relationship => 'test',
188 my $order_guarantee4 = $builder->build_object(
190 class => 'Koha::Patrons',
193 firstname => 'Vulture',
194 guarantorid => $guarantor->borrowernumber
198 $builder->build_object(
200 class => 'Koha::Patron::Relationships',
202 guarantor_id => $guarantor->id,
203 guarantee_id => $order_guarantee4,
204 relationship => 'test',
209 my $order_guarantee5 = $builder->build_object(
211 class => 'Koha::Patrons',
214 firstname => 'Unicorn',
215 guarantorid => $guarantor->borrowernumber
219 my $r = $builder->build_object(
221 class => 'Koha::Patron::Relationships',
223 guarantor_id => $guarantor->id,
224 guarantee_id => $order_guarantee5,
225 relationship => 'test',
230 $guarantees = $guarantor->guarantee_relationships->guarantees;
232 is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
233 is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
234 is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
235 is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
236 is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
239 subtest 'category' => sub {
241 my $patron_category = $new_patron_1->category;
242 is( ref( $patron_category), 'Koha::Patron::Category', );
243 is( $patron_category->categorycode, $category->{categorycode}, );
246 subtest 'siblings' => sub {
248 my $siblings = $new_patron_1->siblings;
249 is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
250 my $guarantee_1 = $builder->build( { source => 'Borrower' } );
251 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
252 my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
253 $siblings = $retrieved_guarantee_1->siblings;
254 is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
255 my @siblings = $retrieved_guarantee_1->siblings;
256 is( ref( \@siblings ), 'ARRAY', 'Koha::Patron->siblings should return an array in a list context' );
257 is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' );
258 my $guarantee_2 = $builder->build( { source => 'Borrower' } );
259 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
260 my $guarantee_3 = $builder->build( { source => 'Borrower' } );
261 my $relationship_3 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_3->{borrowernumber}, relationship => 'test' } )->store();
262 $siblings = $retrieved_guarantee_1->siblings;
263 is( $siblings->count, 2, 'guarantee_1 should have 2 siblings' );
264 is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
265 is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
266 $_->delete for $retrieved_guarantee_1->siblings;
267 $retrieved_guarantee_1->delete;
270 subtest 'has_overdues' => sub {
273 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
274 my $item_1 = $builder->build(
277 homebranch => $library->{branchcode},
278 holdingbranch => $library->{branchcode},
282 biblionumber => $biblioitem_1->{biblionumber}
286 my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
287 is( $retrieved_patron->has_overdues, 0, );
289 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
290 my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
291 is( $retrieved_patron->has_overdues, 0, );
293 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
294 $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
295 $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
296 is( $retrieved_patron->has_overdues, 1, );
300 subtest 'is_expired' => sub {
302 my $patron = $builder->build({ source => 'Borrower' });
303 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
304 $patron->dateexpiry( undef )->store->discard_changes;
305 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
306 $patron->dateexpiry( dt_from_string )->store->discard_changes;
307 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
308 $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
309 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
310 $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
311 is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
316 subtest 'is_going_to_expire' => sub {
319 my $today = dt_from_string(undef, undef, 'floating');
320 my $patron = $builder->build({ source => 'Borrower' });
321 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
322 $patron->dateexpiry( undef )->store->discard_changes;
323 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
325 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
326 $patron->dateexpiry( $today )->store->discard_changes;
327 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
329 $patron->dateexpiry( $today )->store->discard_changes;
330 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
332 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
333 $patron->dateexpiry( $today->clone->add( days => 11 ) )->store->discard_changes;
334 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');
336 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
337 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
338 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');
340 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
341 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
342 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');
345 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
346 $patron->dateexpiry( $today->clone->add( days => 20 ) )->store->discard_changes;
347 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');
349 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
350 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
351 is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
353 { # Testing invalid is going to expiry date
354 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 30);
355 # mock_config does not work here, because of tz vs timezone subroutines
356 my $context = new Test::MockModule('C4::Context');
357 $context->mock( 'tz', sub {
360 $patron->dateexpiry(DateTime->new( year => 2019, month => 12, day => 3 ))->store;
361 eval { $patron->is_going_to_expire };
362 is( $@, '', 'On invalid "is going to expire" date, the method should not crash with "Invalid local time for date in time zone"');
363 $context->unmock('tz');
370 subtest 'renew_account' => sub {
373 for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
374 my $dt = dt_from_string( $date, 'iso' );
375 Time::Fake->offset( $dt->epoch );
376 my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
377 my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
378 my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
379 my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
380 my $a_year_later_plus_a_month = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
381 my $patron_category = $builder->build(
382 { source => 'Category',
384 enrolmentperiod => 12,
385 enrolmentperioddate => undef,
389 my $patron = $builder->build(
390 { source => 'Borrower',
392 dateexpiry => $a_month_ago,
393 categorycode => $patron_category->{categorycode},
394 date_renewed => undef, # Force builder to not populate the column for new patron
398 my $patron_2 = $builder->build(
399 { source => 'Borrower',
401 dateexpiry => $a_month_ago,
402 categorycode => $patron_category->{categorycode},
406 my $patron_3 = $builder->build(
407 { source => 'Borrower',
409 dateexpiry => $a_month_later,
410 categorycode => $patron_category->{categorycode},
414 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
415 my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
416 my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
418 is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
420 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
421 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
422 my $expiry_date = $retrieved_patron->renew_account;
423 is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
424 my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
425 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" );
426 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
427 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
429 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
430 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
431 $expiry_date = $retrieved_patron->renew_account;
432 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
433 $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
434 is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
435 $retrieved_expiry_date = $retrieved_patron->dateexpiry;
436 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
437 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
438 is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
440 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
441 $expiry_date = $retrieved_patron_2->renew_account;
442 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
443 $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
444 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
446 $expiry_date = $retrieved_patron_3->renew_account;
447 is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
448 $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
449 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" );
451 $retrieved_patron->delete;
452 $retrieved_patron_2->delete;
453 $retrieved_patron_3->delete;
458 subtest "move_to_deleted" => sub {
460 my $originally_updated_on = '2016-01-01 12:12:12';
461 my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
462 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
463 is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
464 ; # FIXME This should be Koha::Deleted::Patron
465 my $deleted_patron = $schema->resultset('Deletedborrower')
466 ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
468 ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
469 ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
470 isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
471 $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
472 is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
473 $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup
476 subtest "delete" => sub {
478 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
479 my $patron = $builder->build( { source => 'Borrower' } );
480 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
481 my $hold = $builder->build(
482 { source => 'Reserve',
483 value => { borrowernumber => $patron->{borrowernumber} }
486 my $list = $builder->build(
487 { source => 'Virtualshelve',
488 value => { owner => $patron->{borrowernumber} }
491 my $modification = $builder->build_object({ class => 'Koha::Patron::Modifications', value => { borrowernumber => $patron->{borrowernumber} } });
493 my $deleted = $retrieved_patron->delete;
494 is( ref($deleted), 'Koha::Patron', 'Koha::Patron->delete should return the deleted patron object if the patron has been correctly deleted' );
496 is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
498 is (Koha::Old::Holds->search( { reserve_id => $hold->{ reserve_id } } )->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| );
500 is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have cancelled patron's holds 2| );
502 is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
504 is( Koha::Patron::Modifications->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's modifications| );
506 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
507 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
510 subtest 'Koha::Patrons->delete' => sub {
513 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
514 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
515 my $id1 = $patron1->borrowernumber;
516 my $set = Koha::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
517 is( $set->count, 2, 'Two patrons found as expected' );
518 is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
519 my $deleted_patrons = Koha::Old::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
520 is( $deleted_patrons->count, 2, 'Patrons moved to deletedborrowers' );
522 # See other tests in t/db_dependent/Koha/Objects.t
525 subtest 'add_enrolment_fee_if_needed' => sub {
528 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
529 foreach( keys %{$enrolmentfees} ) {
530 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
532 my $enrolmentfee_K = $enrolmentfees->{K};
533 my $enrolmentfee_J = $enrolmentfees->{J};
534 my $enrolmentfee_YA = $enrolmentfees->{YA};
536 my %borrower_data = (
537 firstname => 'my firstname',
538 surname => 'my surname',
540 branchcode => $library->{branchcode},
543 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
544 $borrower_data{borrowernumber} = $borrowernumber;
546 my $patron = Koha::Patrons->find( $borrowernumber );
547 my $total = $patron->account->balance;
548 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
550 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
551 $borrower_data{categorycode} = 'J';
552 $patron->set(\%borrower_data)->store;
553 $total = $patron->account->balance;
554 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
556 $borrower_data{categorycode} = 'K';
557 $patron->set(\%borrower_data)->store;
558 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
560 $borrower_data{categorycode} = 'J';
561 $patron->set(\%borrower_data)->store;
562 $total = $patron->account->balance;
563 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
565 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
566 $patron->categorycode('YA')->store;
567 $total = $patron->account->balance;
569 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
570 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
576 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
579 my $library = $builder->build( { source => 'Branch' } );
580 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
581 my $item_1 = $builder->build(
585 homebranch => $library->{branchcode},
586 holdingbranch => $library->{branchcode},
587 biblionumber => $biblionumber_1,
593 my $item_2 = $builder->build(
597 homebranch => $library->{branchcode},
598 holdingbranch => $library->{branchcode},
599 biblionumber => $biblionumber_1,
605 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
606 my $item_3 = $builder->build(
610 homebranch => $library->{branchcode},
611 holdingbranch => $library->{branchcode},
612 biblionumber => $biblionumber_2,
618 my $patron = $builder->build(
620 source => 'Borrower',
621 value => { branchcode => $library->{branchcode} }
625 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
626 my $checkouts = $patron->checkouts;
627 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
628 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
629 my $pending_checkouts = $patron->pending_checkouts;
630 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
631 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
632 my $old_checkouts = $patron->old_checkouts;
633 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
634 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
636 # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
637 $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
639 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
641 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
642 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
643 AddIssue( $patron, $item_3->{barcode} );
645 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
646 $checkouts = $patron->checkouts;
647 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
648 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
649 $pending_checkouts = $patron->pending_checkouts;
650 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
651 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
653 my $first_checkout = $pending_checkouts->next;
654 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
656 my $overdues = $patron->get_overdues;
657 is( $overdues->count, 2, 'Patron should have 2 overdues');
658 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
659 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
660 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
663 C4::Circulation::AddReturn( $item_1->{barcode} );
664 C4::Circulation::AddReturn( $item_2->{barcode} );
665 $old_checkouts = $patron->old_checkouts;
666 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
667 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
670 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
674 subtest 'get_routing_lists' => sub {
677 my $biblio = Koha::Biblio->new()->store();
678 my $subscription = Koha::Subscription->new({
679 biblionumber => $biblio->biblionumber,
683 my $patron = $builder->build( { source => 'Borrower' } );
684 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
686 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
688 my $routinglist_count = Koha::Subscription::Routinglists->count;
689 my $routinglist = Koha::Subscription::Routinglist->new({
690 borrowernumber => $patron->borrowernumber,
692 subscriptionid => $subscription->subscriptionid
695 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
697 my $routinglists = $patron->get_routing_lists;
698 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
699 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
701 my $subscription2 = Koha::Subscription->new({
702 biblionumber => $biblio->biblionumber,
705 my $routinglist2 = Koha::Subscription::Routinglist->new({
706 borrowernumber => $patron->borrowernumber,
708 subscriptionid => $subscription2->subscriptionid
711 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
713 $patron->delete; # Clean up for later tests
717 subtest 'get_age' => sub {
720 my $patron = $builder->build( { source => 'Borrower' } );
721 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
725 today => '2020-02-28',
726 has_12 => { date => '2007-08-27', expected_age => 12 },
727 almost_18 => { date => '2002-03-01', expected_age => 17 },
728 has_18_today => { date => '2002-02-28', expected_age => 18 },
729 had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
730 almost_16 => { date => '2004-02-29', expected_age => 15 },
731 has_16_today => { date => '2004-02-28', expected_age => 16 },
732 had_16_yesterday => { date => '2004-02-27', expected_age => 16 },
733 new_born => { date => '2020-01-27', expected_age => 0 },
736 today => '2020-02-29',
737 has_12 => { date => '2007-08-27', expected_age => 12 },
738 almost_18 => { date => '2002-03-01', expected_age => 17 },
739 has_18_today => { date => '2002-02-28', expected_age => 18 },
740 had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
741 almost_16 => { date => '2004-03-01', expected_age => 15 },
742 has_16_today => { date => '2004-02-29', expected_age => 16 },
743 had_16_yesterday => { date => '2004-02-28', expected_age => 16 },
744 new_born => { date => '2020-01-27', expected_age => 0 },
747 today => '2020-03-01',
748 has_12 => { date => '2007-08-27', expected_age => 12 },
749 almost_18 => { date => '2002-03-02', expected_age => 17 },
750 has_18_today => { date => '2002-03-01', expected_age => 18 },
751 had_18_yesterday => { date => '2002-02-28', expected_age => 18 },
752 almost_16 => { date => '2004-03-02', expected_age => 15 },
753 has_16_today => { date => '2004-03-01', expected_age => 16 },
754 had_16_yesterday => { date => '2004-02-29', expected_age => 16 },
757 today => '2019-01-31',
758 has_12 => { date => '2006-08-27', expected_age => 12 },
759 almost_18 => { date => '2001-02-01', expected_age => 17 },
760 has_18_today => { date => '2001-01-31', expected_age => 18 },
761 had_18_yesterday => { date => '2001-01-30', expected_age => 18 },
762 almost_16 => { date => '2003-02-01', expected_age => 15 },
763 has_16_today => { date => '2003-01-31', expected_age => 16 },
764 had_16_yesterday => { date => '2003-01-30', expected_age => 16 },
768 $patron->dateofbirth( undef );
769 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
771 for my $date ( @dates ) {
773 my $dt = dt_from_string($date->{today});
775 Time::Fake->offset( $dt->epoch );
777 for my $k ( keys %$date ) {
778 next if $k eq 'today';
780 my $dob = $date->{$k};
781 $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
784 $dob->{expected_age},
786 "Today=%s, dob=%s, should be %d",
787 $date->{today}, $dob->{date}, $dob->{expected_age}
799 subtest 'is_valid_age' => sub {
802 my $dt = dt_from_string('2020-02-28');
804 Time::Fake->offset( $dt->epoch );
806 my $category = $builder->build({
807 source => 'Category',
809 categorycode => 'AGE_5_10',
810 dateofbirthrequired => 5,
814 $category = Koha::Patron::Categories->find( $category->{categorycode} );
816 my $patron = $builder->build({
817 source => 'Borrower',
819 categorycode => 'AGE_5_10'
822 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
825 $patron->dateofbirth( undef );
826 is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
830 today => '2020-02-28',
832 { date => '2007-08-27', expected_age => 12, valid => 0 },
834 { date => '2016-08-27', expected_age => 3, valid => 0 },
836 { date => '2015-02-28', expected_age => 7, valid => 1 },
838 { date => '2015-02-28', expected_age => 5, valid => 1 },
840 { date => '2015-03-01', expected_age => 5, valid => 0 },
842 { date => '2015-02-27', expected_age => 5, valid => 1 },
844 { date => '2009-02-28', expected_age => 11, valid => 0 },
846 { date => '2009-03-01', expected_age => 11, valid => 1 },
848 { date => '2009-02-27', expected_age => 11, valid => 0 },
852 for my $date ( @dates ) {
854 my $dt = dt_from_string($date->{today});
856 Time::Fake->offset( $dt->epoch );
858 for my $k ( keys %$date ) {
859 next if $k eq 'today';
861 my $dob = $date->{$k};
862 $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
864 $patron->is_valid_age,
867 "Today=%s, dob=%s, is %s, should be valid=%s",
868 $date->{today}, $dob->{date}, $dob->{expected_age}, $dob->{valid}
881 subtest 'account' => sub {
884 my $patron = $builder->build({source => 'Borrower'});
886 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
887 my $account = $patron->account;
888 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
893 subtest 'search_upcoming_membership_expires' => sub {
896 my $expiry_days = 15;
897 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
898 my $nb_of_days_before = 1;
899 my $nb_of_days_after = 2;
901 my $builder = t::lib::TestBuilder->new();
903 my $library = $builder->build({ source => 'Branch' });
905 # before we add borrowers to this branch, add the expires we have now
906 # note that this pertains to the current mocked setting of the pref
907 # for this reason we add the new branchcode to most of the tests
908 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
910 my $patron_1 = $builder->build({
911 source => 'Borrower',
913 branchcode => $library->{branchcode},
914 dateexpiry => dt_from_string->add( days => $expiry_days )
918 my $patron_2 = $builder->build({
919 source => 'Borrower',
921 branchcode => $library->{branchcode},
922 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
926 my $patron_3 = $builder->build({
927 source => 'Borrower',
929 branchcode => $library->{branchcode},
930 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
934 # Test without extra parameters
935 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
936 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
939 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
940 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
941 my $expired = $upcoming_mem_expires->next;
942 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
943 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
944 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
946 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
947 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
948 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
950 # Test MembershipExpiryDaysNotice == undef
951 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
952 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
953 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
955 # Test the before parameter
956 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
957 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
958 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
959 # Test after parameter also
960 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
961 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
962 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
965 subtest 'holds and old_holds' => sub {
968 my $library = $builder->build( { source => 'Branch' } );
969 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
970 my $item_1 = $builder->build(
974 homebranch => $library->{branchcode},
975 holdingbranch => $library->{branchcode},
976 biblionumber => $biblionumber_1
980 my $item_2 = $builder->build(
984 homebranch => $library->{branchcode},
985 holdingbranch => $library->{branchcode},
986 biblionumber => $biblionumber_1
990 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
991 my $item_3 = $builder->build(
995 homebranch => $library->{branchcode},
996 holdingbranch => $library->{branchcode},
997 biblionumber => $biblionumber_2
1001 my $patron = $builder->build(
1003 source => 'Borrower',
1004 value => { branchcode => $library->{branchcode} }
1008 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1009 my $holds = $patron->holds;
1010 is( ref($holds), 'Koha::Holds',
1011 'Koha::Patron->holds should return a Koha::Holds objects' );
1012 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
1014 C4::Reserves::AddReserve(
1016 branchcode => $library->{branchcode},
1017 borrowernumber => $patron->borrowernumber,
1018 biblionumber => $biblionumber_1
1022 C4::Reserves::AddReserve(
1024 branchcode => $library->{branchcode},
1025 borrowernumber => $patron->borrowernumber,
1026 biblionumber => $biblionumber_2,
1027 expiration_date => dt_from_string->add( days => 2 )
1031 $holds = $patron->holds;
1032 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
1034 my $old_holds = $patron->old_holds;
1035 is( ref($old_holds), 'Koha::Old::Holds',
1036 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
1037 is( $old_holds->count, 0, 'There should not be any old holds yet');
1039 my $hold = $holds->next;
1042 $old_holds = $patron->old_holds;
1043 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
1050 subtest 'notice_email_address' => sub {
1053 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1055 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
1056 is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
1058 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
1059 is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
1064 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
1067 # TODO create a subroutine in t::lib::Mocks
1068 my $branch = $builder->build({ source => 'Branch' });
1069 my $userenv_patron = $builder->build_object({
1070 class => 'Koha::Patrons',
1071 value => { branchcode => $branch->{branchcode}, flags => 0 },
1073 t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
1075 my $anonymous = $builder->build( { source => 'Borrower', }, );
1077 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
1079 subtest 'patron privacy is 1 (default)' => sub {
1082 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1083 my $patron = $builder->build(
1084 { source => 'Borrower',
1085 value => { privacy => 1, }
1088 my $item_1 = $builder->build(
1096 my $issue_1 = $builder->build(
1097 { source => 'Issue',
1099 borrowernumber => $patron->{borrowernumber},
1100 itemnumber => $item_1->{itemnumber},
1104 my $item_2 = $builder->build(
1112 my $issue_2 = $builder->build(
1113 { source => 'Issue',
1115 borrowernumber => $patron->{borrowernumber},
1116 itemnumber => $item_2->{itemnumber},
1121 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1122 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, dt_from_string('2011-11-11') );
1123 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
1125 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
1126 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
1128 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
1129 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1131 $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1132 is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
1134 my $dbh = C4::Context->dbh;
1135 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
1136 $sth->execute($item_1->{itemnumber});
1137 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1138 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
1139 $sth->execute($item_2->{itemnumber});
1140 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1141 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
1143 $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
1144 $sth->execute($item_2->{itemnumber});
1145 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1146 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
1148 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
1149 $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
1150 $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
1151 $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
1152 $sth->execute($item_1->{itemnumber});
1153 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1154 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
1155 $sth->execute($item_2->{itemnumber});
1156 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1157 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
1159 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1162 subtest 'patron privacy is 0 (forever)' => sub {
1165 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1166 my $patron = $builder->build(
1167 { source => 'Borrower',
1168 value => { privacy => 0, }
1171 my $item = $builder->build(
1179 my $issue = $builder->build(
1180 { source => 'Issue',
1182 borrowernumber => $patron->{borrowernumber},
1183 itemnumber => $item->{itemnumber},
1188 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1189 is( $returned, 1, 'The item should have been returned' );
1191 my $dbh = C4::Context->dbh;
1192 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1193 SELECT borrowernumber FROM old_issues where itemnumber = ?
1194 |, undef, $item->{itemnumber});
1195 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1196 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1199 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1201 subtest 'AnonymousPatron is not defined' => sub {
1204 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1205 my $patron = $builder->build(
1206 { source => 'Borrower',
1207 value => { privacy => 1, }
1210 my $item = $builder->build(
1218 my $issue = $builder->build(
1219 { source => 'Issue',
1221 borrowernumber => $patron->{borrowernumber},
1222 itemnumber => $item->{itemnumber},
1227 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1228 is( $returned, 1, 'The item should have been returned' );
1229 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
1230 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1232 my $dbh = C4::Context->dbh;
1233 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1234 SELECT borrowernumber FROM old_issues where itemnumber = ?
1235 |, undef, $item->{itemnumber});
1236 is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
1237 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1240 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1242 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1243 my $patron = $builder->build(
1244 { source => 'Borrower',
1245 value => { privacy => 1 } # Another branchcode than the logged in librarian
1248 my $item = $builder->build(
1256 my $issue = $builder->build(
1257 { source => 'Issue',
1259 borrowernumber => $patron->{borrowernumber},
1260 itemnumber => $item->{itemnumber},
1265 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1266 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1267 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1270 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1271 $userenv_patron->delete;
1273 # Reset IndependentBranches for further tests
1274 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1277 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1285 $nb_of_patrons = Koha::Patrons->search->count;
1286 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1287 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1288 my $library_11 = $builder->build( { source => 'Branch' } );
1289 my $library_12 = $builder->build( { source => 'Branch' } );
1290 my $library_21 = $builder->build( { source => 'Branch' } );
1291 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1292 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1293 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1294 Koha::Library::Group->new(
1295 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1296 Koha::Library::Group->new(
1297 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1298 Koha::Library::Group->new(
1299 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1301 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1302 # 2 patrons from library_11 (group1)
1303 # patron_11_1 see patron's infos from outside its group
1304 # Setting flags => undef to not be considered as superlibrarian
1305 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1306 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1307 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1308 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1309 # patron_11_2 can only see patron's info from its group
1310 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1311 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1312 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1313 # 1 patron from library_12 (group1)
1314 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1315 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1316 # 1 patron from library_21 (group2) can only see patron's info from its group
1317 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1318 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1319 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1321 # Pfiou, we can start now!
1322 subtest 'libraries_where_can_see_patrons' => sub {
1327 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1328 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1329 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1331 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1332 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1333 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| );
1335 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1336 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1337 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| );
1339 subtest 'can_see_patron_infos' => sub {
1342 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1343 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1344 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1345 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1347 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1348 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1349 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1350 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1352 subtest 'search_limited' => sub {
1355 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1356 my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1357 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1358 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1360 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1361 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1362 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' );
1364 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1365 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1366 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1368 $patron_11_1->delete;
1369 $patron_11_2->delete;
1374 subtest 'account_locked' => sub {
1376 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1377 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1378 for my $value ( undef, '', 0 ) {
1379 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1380 $patron->login_attempts(0)->store;
1381 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1382 $patron->login_attempts(1)->store;
1383 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1384 $patron->login_attempts(-1)->store;
1385 is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1388 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1389 $patron->login_attempts(2)->store;
1390 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1391 $patron->login_attempts(3)->store;
1392 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1393 $patron->login_attempts(4)->store;
1394 is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1395 $patron->login_attempts(-1)->store;
1396 is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1401 subtest 'is_child | is_adult' => sub {
1403 my $category = $builder->build_object(
1405 class => 'Koha::Patron::Categories',
1406 value => { category_type => 'A' }
1409 my $patron_adult = $builder->build_object(
1411 class => 'Koha::Patrons',
1412 value => { categorycode => $category->categorycode }
1415 $category = $builder->build_object(
1417 class => 'Koha::Patron::Categories',
1418 value => { category_type => 'I' }
1421 my $patron_adult_i = $builder->build_object(
1423 class => 'Koha::Patrons',
1424 value => { categorycode => $category->categorycode }
1427 $category = $builder->build_object(
1429 class => 'Koha::Patron::Categories',
1430 value => { category_type => 'C' }
1433 my $patron_child = $builder->build_object(
1435 class => 'Koha::Patrons',
1436 value => { categorycode => $category->categorycode }
1439 $category = $builder->build_object(
1441 class => 'Koha::Patron::Categories',
1442 value => { category_type => 'O' }
1445 my $patron_other = $builder->build_object(
1447 class => 'Koha::Patrons',
1448 value => { categorycode => $category->categorycode }
1451 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1452 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1453 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1454 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1456 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1457 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1458 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1459 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1462 $patron_adult->delete;
1463 $patron_adult_i->delete;
1464 $patron_child->delete;
1465 $patron_other->delete;
1468 subtest 'get_overdues' => sub {
1471 my $library = $builder->build( { source => 'Branch' } );
1472 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1473 my $item_1 = $builder->build(
1477 homebranch => $library->{branchcode},
1478 holdingbranch => $library->{branchcode},
1479 biblionumber => $biblionumber_1
1483 my $item_2 = $builder->build(
1487 homebranch => $library->{branchcode},
1488 holdingbranch => $library->{branchcode},
1489 biblionumber => $biblionumber_1
1493 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1494 my $item_3 = $builder->build(
1498 homebranch => $library->{branchcode},
1499 holdingbranch => $library->{branchcode},
1500 biblionumber => $biblionumber_2
1504 my $patron = $builder->build(
1506 source => 'Borrower',
1507 value => { branchcode => $library->{branchcode} }
1511 t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1513 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1514 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1515 AddIssue( $patron, $item_3->{barcode} );
1517 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1518 my $overdues = $patron->get_overdues;
1519 is( $overdues->count, 2, 'Patron should have 2 overdues');
1520 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1521 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1523 my $o = $overdues->reset->next;
1524 my $unblessed_overdue = $o->unblessed_all_relateds;
1525 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1526 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1527 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1528 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1531 $patron->checkouts->delete;
1535 subtest 'userid_is_valid' => sub {
1538 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1539 my $patron_category = $builder->build_object(
1541 class => 'Koha::Patron::Categories',
1542 value => { category_type => 'P', enrolmentfee => 0 }
1546 cardnumber => "123456789",
1547 firstname => "Tomasito",
1549 categorycode => $patron_category->categorycode,
1550 branchcode => $library->branchcode,
1553 my $expected_userid_patron_1 = 'tomasito.none';
1554 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1555 my $patron_1 = Koha::Patrons->find($borrowernumber);
1556 is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1557 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1559 $patron_1->userid( 'tomasito.non' );
1560 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1561 1, 'recently created userid -> unique (borrowernumber passed)' );
1563 $patron_1->userid( 'tomasitoxxx' );
1564 is( $patron_1->has_valid_userid,
1565 1, 'non-existent userid -> unique (borrowernumber passed)' );
1566 $patron_1->discard_changes; # We compare with the original userid later
1568 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1569 is( $patron_not_in_storage->has_valid_userid,
1570 0, 'userid exists for another patron, patron is not in storage yet' );
1572 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1573 is( $patron_not_in_storage->has_valid_userid,
1574 1, 'non-existent userid, patron is not in storage yet' );
1576 # Regression tests for BZ12226
1577 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1578 is( $db_patron->has_valid_userid,
1579 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1581 # Add a new borrower with the same userid but different cardnumber
1582 $data{cardnumber} = "987654321";
1583 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1584 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1585 $patron_2->userid($patron_1->userid);
1586 is( $patron_2->has_valid_userid,
1587 0, 'The userid is already in used, it cannot be used for another patron' );
1589 my $new_userid = 'a_user_id';
1590 $data{cardnumber} = "234567890";
1591 $data{userid} = 'a_user_id';
1592 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1593 my $patron_3 = Koha::Patrons->find($borrowernumber);
1594 is( $patron_3->userid, $new_userid,
1595 'Koha::Patron->store should insert the given userid' );
1603 subtest 'generate_userid' => sub {
1606 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1607 my $patron_category = $builder->build_object(
1609 class => 'Koha::Patron::Categories',
1610 value => { category_type => 'P', enrolmentfee => 0 }
1614 cardnumber => "123456789",
1615 firstname => "Tômà sÃtó",
1616 surname => "Ñoné",
1617 categorycode => $patron_category->categorycode,
1618 branchcode => $library->branchcode,
1621 my $expected_userid_patron_1 = 'tomasito.none';
1622 my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1623 $new_patron->generate_userid;
1624 my $userid = $new_patron->userid;
1625 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1626 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1627 my $patron_1 = Koha::Patrons->find($borrowernumber);
1628 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1630 $new_patron->generate_userid;
1631 $userid = $new_patron->userid;
1632 is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1633 $data{cardnumber} = '987654321';
1634 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1635 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1636 isnt( $patron_2->userid, 'tomasito',
1637 "Patron with duplicate userid has new userid generated" );
1638 is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1639 "Patron with duplicate userid has new userid generated (1 is appened" );
1641 $new_patron->generate_userid;
1642 $userid = $new_patron->userid;
1643 is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1645 $patron_1 = Koha::Patrons->find($borrowernumber);
1646 $patron_1->userid(undef);
1647 $patron_1->generate_userid;
1648 $userid = $patron_1->userid;
1649 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1656 $nb_of_patrons = Koha::Patrons->search->count;
1657 $retrieved_patron_1->delete;
1658 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1660 subtest 'BorrowersLog tests' => sub {
1663 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1664 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1666 my $cardnumber = $patron->cardnumber;
1667 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1670 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1671 my $log_info = from_json( $logs[0]->info );
1672 is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1673 is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1674 is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1676 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1677 $patron->track_login();
1678 @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1679 is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1682 $schema->storage->txn_rollback;
1684 subtest 'Test Koha::Patrons::merge' => sub {
1687 my $schema = Koha::Database->new()->schema();
1689 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1691 $schema->storage->txn_begin;
1693 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1694 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1695 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1697 while (my ($r, $field) = each(%$resultsets)) {
1698 $builder->build({ source => $r, value => { $field => $keeper->id } });
1699 $builder->build({ source => $r, value => { $field => $loser_1 } });
1700 $builder->build({ source => $r, value => { $field => $loser_2 } });
1703 $schema->resultset($r)->search( { $field => $keeper->id } );
1704 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1707 $schema->resultset($r)->search( { $field => $loser_1 } );
1708 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1711 $schema->resultset($r)->search( { $field => $loser_2 } );
1712 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1715 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1717 while (my ($r, $field) = each(%$resultsets)) {
1719 $schema->resultset($r)->search( {$field => $keeper->id } );
1720 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1723 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1724 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1726 $schema->storage->txn_rollback;
1729 subtest '->store' => sub {
1731 my $schema = Koha::Database->new->schema;
1732 $schema->storage->txn_begin;
1734 my $print_error = $schema->storage->dbh->{PrintError};
1735 $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1737 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1738 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1741 { $patron_2->userid($patron_1->userid)->store; }
1742 'Koha::Exceptions::Object::DuplicateID',
1743 'Koha::Patron->store raises an exception on duplicate ID';
1746 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1747 my $password = 'password';
1748 $patron_1->set_password({ password => $password });
1749 like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1750 my $digest = $patron_1->password;
1751 $patron_1->surname('xxx')->store;
1752 is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1754 # Test uppercasesurnames
1755 t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 );
1756 my $surname = lc $patron_1->surname;
1757 $patron_1->surname($surname)->store;
1758 isnt( $patron_1->surname, $surname,
1759 'Surname converts to uppercase on store.');
1760 t::lib::Mocks::mock_preference( 'uppercasesurnames', 0 );
1761 $patron_1->surname($surname)->store;
1762 is( $patron_1->surname, $surname,
1763 'Surname remains unchanged on store.');
1766 $patron_1->relationship("")->store;
1767 is( $patron_1->relationship, undef, );
1769 $schema->storage->dbh->{PrintError} = $print_error;
1770 $schema->storage->txn_rollback;
1772 subtest 'skip updated_on for BorrowersLog' => sub {
1774 $schema->storage->txn_begin;
1775 t::lib::Mocks::mock_preference('BorrowersLog', 1);
1776 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1777 $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1778 my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1779 is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1780 $schema->storage->txn_rollback;
1784 subtest '->set_password' => sub {
1788 $schema->storage->txn_begin;
1790 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1792 # Disable logging password changes for this tests
1793 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1795 # Password-length tests
1796 t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1797 throws_ok { $patron->set_password({ password => 'ab' }); }
1798 'Koha::Exceptions::Password::TooShort',
1799 'minPasswordLength is undef, fall back to 3, fail test';
1801 'Password length (2) is shorter than required (3)',
1802 'Exception parameters passed correctly'
1805 t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1806 throws_ok { $patron->set_password({ password => 'ab' }); }
1807 'Koha::Exceptions::Password::TooShort',
1808 'minPasswordLength is 2, fall back to 3, fail test';
1810 t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1811 throws_ok { $patron->set_password({ password => 'abcb' }); }
1812 'Koha::Exceptions::Password::TooShort',
1813 'minPasswordLength is 5, fail test';
1815 # Trailing spaces tests
1816 throws_ok { $patron->set_password({ password => 'abcD12d ' }); }
1817 'Koha::Exceptions::Password::WhitespaceCharacters',
1818 'Password contains trailing spaces, exception is thrown';
1820 # Require strong password tests
1821 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1822 throws_ok { $patron->set_password({ password => 'abcd a' }); }
1823 'Koha::Exceptions::Password::TooWeak',
1824 'Password is too weak, exception is thrown';
1826 # Refresh patron from DB, just to make sure
1827 $patron->discard_changes;
1828 is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1830 $patron->set_password({ password => 'abcD12 34' });
1831 $patron->discard_changes;
1833 is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1835 lives_ok { $patron->set_password({ password => 'abcd a', skip_validation => 1 }) }
1836 'Password is weak, but skip_validation was passed, so no exception thrown';
1839 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1840 $patron->login_attempts(3)->store;
1841 my $old_digest = $patron->password;
1842 $patron->set_password({ password => 'abcd a' });
1843 $patron->discard_changes;
1845 isnt( $patron->password, $old_digest, 'Password has been updated' );
1846 ok( checkpw_hash('abcd a', $patron->password), 'Password hash is correct' );
1847 is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1849 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1850 is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1852 # Enable logging password changes
1853 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1854 $patron->set_password({ password => 'abcd b' });
1856 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1857 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1859 $schema->storage->txn_rollback;
1862 $schema->storage->txn_begin;
1863 subtest 'search_unsubscribed' => sub {
1866 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1867 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
1868 is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
1870 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1871 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1873 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
1874 Koha::Patron::Consents->delete; # for correct counts
1875 Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string })->store;
1876 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
1878 # Add another refusal but shift the period
1879 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
1880 Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string->subtract(days=>2) })->store;
1881 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
1883 # Try another (special) attempts setting
1884 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
1885 # Lockout is now disabled
1886 # Patron2 still matches: refused earlier, not locked
1887 is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
1890 subtest 'search_anonymize_candidates' => sub {
1892 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1893 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1894 $patron1->anonymized(0);
1895 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1896 $patron2->anonymized(0);
1897 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1899 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
1900 is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
1902 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
1903 my $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+2, 'Delay 0' );
1908 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
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+1, 'Delay 2' );
1916 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
1917 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1918 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1919 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1920 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1921 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1922 is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
1924 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1925 $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1926 $patron1->login_attempts(0)->store;
1927 $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1928 $patron2->login_attempts(0)->store;
1929 $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
1930 $patron1->login_attempts(3)->store;
1931 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1932 $cnt+1, 'Locked flag' );
1934 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1935 # Patron 1 still on 3 == locked
1936 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1937 $cnt+1, 'Still expect same number for FailedLoginAttempts empty' );
1938 $patron1->login_attempts(0)->store;
1940 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1941 $cnt, 'Patron 1 unlocked' );
1944 subtest 'search_anonymized' => sub {
1946 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1948 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
1949 is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
1951 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
1952 $patron1->dateexpiry( dt_from_string );
1953 $patron1->anonymized(0)->store;
1954 my $cnt = Koha::Patrons->search_anonymized->count;
1955 $patron1->anonymized(1)->store;
1956 is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
1957 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1958 is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
1961 subtest 'lock' => sub {
1964 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1965 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1966 my $hold = $builder->build_object({
1967 class => 'Koha::Holds',
1968 value => { borrowernumber => $patron1->borrowernumber },
1971 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1972 my $expiry = dt_from_string->add(days => 1);
1973 $patron1->dateexpiry( $expiry );
1975 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1976 is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
1977 is( $patron1->holds->count, 1, 'No holds removed' );
1979 $patron1->lock({ expire => 1, remove => 1});
1980 isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
1981 is( $patron1->holds->count, 0, 'Holds removed' );
1983 # Disable lockout feature
1984 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1985 $patron1->login_attempts(0);
1986 $patron1->dateexpiry( $expiry );
1989 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1991 # Trivial wrapper test (Koha::Patrons->lock)
1992 $patron1->login_attempts(0)->store;
1993 Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
1994 $patron1->discard_changes; # refresh
1995 $patron2->discard_changes;
1996 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
1997 is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
2000 subtest 'anonymize' => sub {
2003 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2004 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
2006 # First try patron with issues
2007 my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
2008 warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
2011 t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
2012 my $surname = $patron1->surname; # expect change, no clear
2013 my $branchcode = $patron1->branchcode; # expect skip
2014 $patron1->anonymize;
2015 is($patron1->anonymized, 1, 'Check flag' );
2017 is( $patron1->dateofbirth, undef, 'Birth date cleared' );
2018 is( $patron1->firstname, undef, 'First name cleared' );
2019 isnt( $patron1->surname, $surname, 'Surname changed' );
2020 ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
2021 is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
2022 is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
2024 # Test wrapper in Koha::Patrons
2025 $patron1->surname($surname)->store; # restore
2026 my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
2027 $patron1->discard_changes; # refresh
2028 isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
2029 $patron2->discard_changes; # refresh
2030 is( $patron2->firstname, undef, 'First name patron2 cleared' );
2032 $schema->storage->txn_rollback;
2034 subtest 'extended_attributes' => sub {
2036 my $schema = Koha::Database->new->schema;
2037 $schema->storage->txn_begin;
2039 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
2040 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
2042 t::lib::Mocks::mock_userenv({ patron => $patron_1 });
2044 my $attribute_type1 = Koha::Patron::Attribute::Type->new(
2047 description => 'my description1',
2051 my $attribute_type2 = Koha::Patron::Attribute::Type->new(
2054 description => 'my description2',
2056 staff_searchable => 1
2060 my $attribute_type3 = $builder->build_object({ class => 'Koha::Patron::Attribute::Types' });
2062 my $deleted_attribute_type = $builder->build_object({ class => 'Koha::Patron::Attribute::Types' });
2063 my $deleted_attribute_type_code = $deleted_attribute_type->code;
2064 $deleted_attribute_type->delete;
2066 my $new_library = $builder->build( { source => 'Branch' } );
2067 my $attribute_type_limited = Koha::Patron::Attribute::Type->new(
2068 { code => 'my code3', description => 'my description3' } )->store;
2069 $attribute_type_limited->library_limits( [ $new_library->{branchcode} ] );
2071 my $attributes_for_1 = [
2073 attribute => 'my attribute1',
2074 code => $attribute_type1->code(),
2077 attribute => 'my attribute2',
2078 code => $attribute_type2->code(),
2081 attribute => 'my attribute limited',
2082 code => $attribute_type_limited->code(),
2086 my $attributes_for_2 = [
2088 attribute => 'my attribute12',
2089 code => $attribute_type1->code(),
2092 attribute => 'my attribute limited 2',
2093 code => $attribute_type_limited->code(),
2096 attribute => 'my nonexistent attribute 2',
2097 code => $deleted_attribute_type_code,
2101 my $extended_attributes = $patron_1->extended_attributes;
2102 is( ref($extended_attributes), 'Koha::Patron::Attributes', 'Koha::Patron->extended_attributes must return a Koha::Patron::Attribute set' );
2103 is( $extended_attributes->count, 0, 'There should not be attribute yet');
2105 $patron_1->extended_attributes->filter_by_branch_limitations->delete;
2106 $patron_2->extended_attributes->filter_by_branch_limitations->delete;
2107 $patron_1->extended_attributes($attributes_for_1);
2110 $patron_2->extended_attributes($attributes_for_2);
2111 } [ qr/a foreign key constraint fails/ ], 'nonexistent attribute should have not exploded but print a warning';
2113 my $extended_attributes_for_1 = $patron_1->extended_attributes;
2114 is( $extended_attributes_for_1->count, 3, 'There should be 3 attributes now for patron 1');
2116 my $extended_attributes_for_2 = $patron_2->extended_attributes;
2117 is( $extended_attributes_for_2->count, 2, 'There should be 2 attributes now for patron 2');
2119 my $attribute_12 = $extended_attributes_for_2->search({ code => $attribute_type1->code });
2120 is( $attribute_12->next->attribute, 'my attribute12', 'search by code should return the correct attribute' );
2122 $attribute_12 = $patron_2->get_extended_attribute( $attribute_type1->code );
2123 is( $attribute_12->attribute, 'my attribute12', 'Koha::Patron->get_extended_attribute should return the correct attribute value' );
2126 $extended_attributes_for_2 = $patron_2->extended_attributes->merge_with(
2129 attribute => 'my attribute12 XXX',
2130 code => $attribute_type1->code(),
2133 attribute => 'my nonexistent attribute 2',
2134 code => $deleted_attribute_type_code,
2137 attribute => 'my attribute 3', # Adding a new attribute using merge_with
2138 code => $attribute_type3->code,
2143 "Cannot merge element: unrecognized code = '$deleted_attribute_type_code'",
2144 "Trying to merge_with using a nonexistent attribute code should display a warning";
2146 is( @$extended_attributes_for_2, 3, 'There should be 3 attributes now for patron 3');
2147 my $expected_attributes_for_2 = [
2149 code => $attribute_type1->code(),
2150 attribute => 'my attribute12 XXX',
2153 code => $attribute_type_limited->code(),
2154 attribute => 'my attribute limited 2',
2157 attribute => 'my attribute 3',
2158 code => $attribute_type3->code,
2161 # Sorting them by code
2162 $expected_attributes_for_2 = [ sort { $a->{code} cmp $b->{code} } @$expected_attributes_for_2 ];
2167 code => $extended_attributes_for_2->[0]->{code},
2168 attribute => $extended_attributes_for_2->[0]->{attribute}
2171 code => $extended_attributes_for_2->[1]->{code},
2172 attribute => $extended_attributes_for_2->[1]->{attribute}
2175 code => $extended_attributes_for_2->[2]->{code},
2176 attribute => $extended_attributes_for_2->[2]->{attribute}
2179 $expected_attributes_for_2
2182 # TODO - What about multiple? POD explains the problem
2183 my $non_existent = $patron_2->get_extended_attribute( 'not_exist' );
2184 is( $non_existent, undef, 'Koha::Patron->get_extended_attribute must return undef if the attribute does not exist' );
2186 # Test branch limitations
2187 t::lib::Mocks::mock_userenv({ patron => $patron_2 });
2189 $extended_attributes_for_1 = $patron_1->extended_attributes;
2190 is( $extended_attributes_for_1->count, 3, 'There should be 2 attributes for patron 1, the limited one should be returned');
2193 $extended_attributes_for_1 = $patron_1->extended_attributes->filter_by_branch_limitations;
2194 is( $extended_attributes_for_1->count, 2, 'There should be 2 attributes for patron 1, the limited one should be returned');
2197 my $limited_value = $patron_1->get_extended_attribute( $attribute_type_limited->code );
2198 is( $limited_value->attribute, 'my attribute limited', );
2200 ## Do we need a filtered?
2201 #$limited_value = $patron_1->get_extended_attribute( $attribute_type_limited->code );
2202 #is( $limited_value, undef, );
2204 $schema->storage->txn_rollback;