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 => 42;
32 use C4::Circulation qw( AddIssue AddReturn );
34 use C4::Auth qw( checkpw checkpw_hash );
40 use Koha::Old::Patrons;
41 use Koha::Patron::Attribute::Types;
42 use Koha::Patron::Categories;
43 use Koha::Patron::Relationship;
45 use Koha::DateUtils qw( dt_from_string output_pref );
46 use Koha::Virtualshelves;
47 use Koha::Notice::Messages;
49 use t::lib::TestBuilder;
52 my $schema = Koha::Database->new->schema;
53 $schema->storage->txn_begin;
55 my $builder = t::lib::TestBuilder->new;
56 my $library = $builder->build({source => 'Branch' });
57 my $category = $builder->build({source => 'Category' });
58 my $nb_of_patrons = Koha::Patrons->search->count;
59 my $new_patron_1 = Koha::Patron->new(
60 { cardnumber => 'test_cn_1',
61 branchcode => $library->{branchcode},
62 categorycode => $category->{categorycode},
63 surname => 'surname for patron1',
64 firstname => 'firstname for patron1',
65 userid => 'a_nonexistent_userid_1',
66 flags => 1, # Is superlibrarian
69 my $new_patron_2 = Koha::Patron->new(
70 { cardnumber => 'test_cn_2',
71 branchcode => $library->{branchcode},
72 categorycode => $category->{categorycode},
73 surname => 'surname for patron2',
74 firstname => 'firstname for patron2',
75 userid => 'a_nonexistent_userid_2',
79 t::lib::Mocks::mock_userenv({ patron => $new_patron_1 });
81 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
83 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
84 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
86 subtest 'library' => sub {
88 is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
89 is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
92 subtest 'sms_provider' => sub {
94 my $sms_provider = $builder->build({source => 'SmsProvider' });
95 is( $retrieved_patron_1->sms_provider, undef, '->sms_provider should return undef if none defined' );
96 $retrieved_patron_1->sms_provider_id( $sms_provider->{id} )->store;
97 is_deeply( $retrieved_patron_1->sms_provider->unblessed, $sms_provider, 'Koha::Patron->sms_provider returns the correct SMS provider' );
98 is( ref($retrieved_patron_1->sms_provider), 'Koha::SMS::Provider', 'Koha::Patron->sms_provider should return a Koha::SMS::Provider object' );
101 subtest 'guarantees' => sub {
104 t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test|test2' );
106 my $guarantees = $new_patron_1->guarantee_relationships;
107 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
108 is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee relationships' );
109 my @guarantees = $new_patron_1->guarantee_relationships;
110 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantee_relationships should return an array in a list context' );
111 is( scalar(@guarantees), 0, 'new_patron_1 should have 0 guarantee' );
113 my $guarantee_1 = $builder->build({ source => 'Borrower' });
114 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
115 my $guarantee_2 = $builder->build({ source => 'Borrower' });
116 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
118 $guarantees = $new_patron_1->guarantee_relationships;
119 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantee_relationships should return a Koha::Patrons result set in a scalar context' );
120 is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
121 @guarantees = $new_patron_1->guarantee_relationships;
122 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantee_relationships should return an array in a list context' );
123 is( scalar(@guarantees), 2, 'new_patron_1 should have 2 guarantees' );
124 $_->delete for @guarantees;
126 #Test return order of guarantees BZ 18635
127 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
128 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
130 my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
132 my $order_guarantee1 = $builder->build_object(
134 class => 'Koha::Patrons',
140 $builder->build_object(
142 class => 'Koha::Patron::Relationships',
144 guarantor_id => $guarantor->id,
145 guarantee_id => $order_guarantee1,
146 relationship => 'test',
151 my $order_guarantee2 = $builder->build_object(
153 class => 'Koha::Patrons',
159 $builder->build_object(
161 class => 'Koha::Patron::Relationships',
163 guarantor_id => $guarantor->id,
164 guarantee_id => $order_guarantee2,
165 relationship => 'test',
170 my $order_guarantee3 = $builder->build_object(
172 class => 'Koha::Patrons',
175 firstname => 'Walrus',
179 $builder->build_object(
181 class => 'Koha::Patron::Relationships',
183 guarantor_id => $guarantor->id,
184 guarantee_id => $order_guarantee3,
185 relationship => 'test',
190 my $order_guarantee4 = $builder->build_object(
192 class => 'Koha::Patrons',
195 firstname => 'Vulture',
196 guarantorid => $guarantor->borrowernumber
200 $builder->build_object(
202 class => 'Koha::Patron::Relationships',
204 guarantor_id => $guarantor->id,
205 guarantee_id => $order_guarantee4,
206 relationship => 'test',
211 my $order_guarantee5 = $builder->build_object(
213 class => 'Koha::Patrons',
216 firstname => 'Unicorn',
217 guarantorid => $guarantor->borrowernumber
221 my $r = $builder->build_object(
223 class => 'Koha::Patron::Relationships',
225 guarantor_id => $guarantor->id,
226 guarantee_id => $order_guarantee5,
227 relationship => 'test',
232 $guarantees = $guarantor->guarantee_relationships->guarantees;
234 is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
235 is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
236 is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
237 is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
238 is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
241 subtest 'category' => sub {
243 my $patron_category = $new_patron_1->category;
244 is( ref( $patron_category), 'Koha::Patron::Category', );
245 is( $patron_category->categorycode, $category->{categorycode}, );
248 subtest 'siblings' => sub {
250 my $siblings = $new_patron_1->siblings;
251 is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
252 my $guarantee_1 = $builder->build( { source => 'Borrower' } );
253 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
254 my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
255 $siblings = $retrieved_guarantee_1->siblings;
256 is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
257 my @siblings = $retrieved_guarantee_1->siblings;
258 is( ref( \@siblings ), 'ARRAY', 'Koha::Patron->siblings should return an array in a list context' );
259 is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' );
260 my $guarantee_2 = $builder->build( { source => 'Borrower' } );
261 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
262 my $guarantee_3 = $builder->build( { source => 'Borrower' } );
263 my $relationship_3 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_3->{borrowernumber}, relationship => 'test' } )->store();
264 $siblings = $retrieved_guarantee_1->siblings;
265 is( $siblings->count, 2, 'guarantee_1 should have 2 siblings' );
266 is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
267 is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
268 $_->delete for $retrieved_guarantee_1->siblings;
269 $retrieved_guarantee_1->delete;
272 subtest 'has_overdues' => sub {
275 my $item_1 = $builder->build_sample_item;
276 my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
277 is( $retrieved_patron->has_overdues, 0, );
279 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
280 my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->itemnumber, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
281 is( $retrieved_patron->has_overdues, 0, );
283 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
284 $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->itemnumber, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
285 $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
286 is( $retrieved_patron->has_overdues, 1, );
290 subtest 'is_expired' => sub {
292 my $patron = $builder->build({ source => 'Borrower' });
293 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
294 $patron->dateexpiry( undef )->store->discard_changes;
295 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
296 $patron->dateexpiry( dt_from_string )->store->discard_changes;
297 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
298 $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
299 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
300 $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
301 is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
306 subtest 'is_going_to_expire' => sub {
309 my $today = dt_from_string(undef, undef, 'floating');
310 my $patron = $builder->build({ source => 'Borrower' });
311 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
312 $patron->dateexpiry( undef )->store->discard_changes;
313 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
315 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
316 $patron->dateexpiry( $today )->store->discard_changes;
317 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
319 $patron->dateexpiry( $today )->store->discard_changes;
320 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
322 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
323 $patron->dateexpiry( $today->clone->add( days => 11 ) )->store->discard_changes;
324 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 11 days ahead and pref is 10');
326 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
327 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
328 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 10 days ahead and pref is 0');
330 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
331 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
332 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 10 days ahead and pref is 10');
335 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
336 $patron->dateexpiry( $today->clone->add( days => 20 ) )->store->discard_changes;
337 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 20 days ahead and pref is 10');
339 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
340 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
341 is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
343 { # Testing invalid is going to expiry date
344 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 30);
345 # mock_config does not work here, because of tz vs timezone subroutines
346 my $context = Test::MockModule->new('C4::Context');
347 $context->mock( 'tz', sub {
350 $patron->dateexpiry(DateTime->new( year => 2019, month => 12, day => 3 ))->store;
351 eval { $patron->is_going_to_expire };
352 is( $@, '', 'On invalid "is going to expire" date, the method should not crash with "Invalid local time for date in time zone"');
353 $context->unmock('tz');
360 subtest 'renew_account' => sub {
363 for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
364 my $dt = dt_from_string( $date, 'iso' );
365 Time::Fake->offset( $dt->epoch );
366 my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
367 my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
368 my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
369 my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
370 my $a_year_later_plus_a_month = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
371 my $patron_category = $builder->build(
372 { source => 'Category',
374 enrolmentperiod => 12,
375 enrolmentperioddate => undef,
379 my $patron = $builder->build(
380 { source => 'Borrower',
382 dateexpiry => $a_month_ago,
383 categorycode => $patron_category->{categorycode},
384 date_renewed => undef, # Force builder to not populate the column for new patron
388 my $patron_2 = $builder->build(
389 { source => 'Borrower',
391 dateexpiry => $a_month_ago,
392 categorycode => $patron_category->{categorycode},
396 my $patron_3 = $builder->build(
397 { source => 'Borrower',
399 dateexpiry => $a_month_later,
400 categorycode => $patron_category->{categorycode},
404 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
405 my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
406 my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
408 is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
410 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
411 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
412 my $expiry_date = $retrieved_patron->renew_account;
413 is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
414 my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
415 is( dt_from_string($retrieved_expiry_date), $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
416 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
417 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
419 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
420 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
421 $expiry_date = $retrieved_patron->renew_account;
422 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
423 $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
424 is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
425 $retrieved_expiry_date = $retrieved_patron->dateexpiry;
426 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
427 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
428 is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
430 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
431 $expiry_date = $retrieved_patron_2->renew_account;
432 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
433 $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
434 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
436 $expiry_date = $retrieved_patron_3->renew_account;
437 is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
438 $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
439 is( dt_from_string($retrieved_expiry_date), $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
441 $retrieved_patron->delete;
442 $retrieved_patron_2->delete;
443 $retrieved_patron_3->delete;
448 subtest "move_to_deleted" => sub {
450 my $originally_updated_on = '2016-01-01 12:12:12';
451 my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
452 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
453 is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
454 ; # FIXME This should be Koha::Deleted::Patron
455 my $deleted_patron = $schema->resultset('Deletedborrower')
456 ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
458 ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
459 ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
460 isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
461 $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
462 is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
463 $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup
466 subtest "delete" => sub {
468 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
469 my $patron = $builder->build( { source => 'Borrower' } );
470 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
471 my $hold = $builder->build(
472 { source => 'Reserve',
473 value => { borrowernumber => $patron->{borrowernumber} }
476 my $list = $builder->build(
477 { source => 'Virtualshelve',
478 value => { owner => $patron->{borrowernumber} }
481 my $modification = $builder->build_object({ class => 'Koha::Patron::Modifications', value => { borrowernumber => $patron->{borrowernumber} } });
483 my $deleted = $retrieved_patron->delete;
484 is( ref($deleted), 'Koha::Patron', 'Koha::Patron->delete should return the deleted patron object if the patron has been correctly deleted' );
486 is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
488 is (Koha::Old::Holds->search( { reserve_id => $hold->{ reserve_id } } )->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| );
490 is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have cancelled patron's holds 2| );
492 is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
494 is( Koha::Patron::Modifications->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's modifications| );
496 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
497 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
500 subtest 'Koha::Patrons->delete' => sub {
503 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
504 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
505 my $id1 = $patron1->borrowernumber;
506 my $set = Koha::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
507 is( $set->count, 2, 'Two patrons found as expected' );
508 is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
509 my $deleted_patrons = Koha::Old::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
510 is( $deleted_patrons->count, 2, 'Patrons moved to deletedborrowers' );
512 # See other tests in t/db_dependent/Koha/Objects.t
515 subtest 'add_enrolment_fee_if_needed' => sub {
518 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
519 foreach( keys %{$enrolmentfees} ) {
520 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
522 my $enrolmentfee_K = $enrolmentfees->{K};
523 my $enrolmentfee_J = $enrolmentfees->{J};
524 my $enrolmentfee_YA = $enrolmentfees->{YA};
526 my %borrower_data = (
527 firstname => 'my firstname',
528 surname => 'my surname',
530 branchcode => $library->{branchcode},
533 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
534 $borrower_data{borrowernumber} = $borrowernumber;
536 my $patron = Koha::Patrons->find( $borrowernumber );
537 my $total = $patron->account->balance;
538 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
540 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
541 $borrower_data{categorycode} = 'J';
542 $patron->set(\%borrower_data)->store;
543 $total = $patron->account->balance;
544 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
546 $borrower_data{categorycode} = 'K';
547 $patron->set(\%borrower_data)->store;
548 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
550 $borrower_data{categorycode} = 'J';
551 $patron->set(\%borrower_data)->store;
552 $total = $patron->account->balance;
553 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
555 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
556 $patron->categorycode('YA')->store;
557 $total = $patron->account->balance;
559 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
560 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
566 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
569 my $library = $builder->build( { source => 'Branch' } );
570 my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
571 my $item_1 = $builder->build_sample_item(
573 library => $library->{branchcode},
574 biblionumber => $biblionumber_1,
577 my $item_2 = $builder->build_sample_item(
579 library => $library->{branchcode},
580 biblionumber => $biblionumber_1,
583 my $biblionumber_2 = $builder->build_sample_biblio->biblionumber;
584 my $item_3 = $builder->build_sample_item(
586 library => $library->{branchcode},
587 biblionumber => $biblionumber_2,
590 my $patron = $builder->build(
592 source => 'Borrower',
593 value => { branchcode => $library->{branchcode} }
597 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
598 my $checkouts = $patron->checkouts;
599 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
600 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
601 my $pending_checkouts = $patron->pending_checkouts;
602 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
603 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
604 my $old_checkouts = $patron->old_checkouts;
605 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
606 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
608 # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
609 $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
611 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
613 AddIssue( $patron, $item_1->barcode, DateTime->now->subtract( days => 1 ) );
614 AddIssue( $patron, $item_2->barcode, DateTime->now->subtract( days => 5 ) );
615 AddIssue( $patron, $item_3->barcode );
617 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
618 $checkouts = $patron->checkouts;
619 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
620 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
621 $pending_checkouts = $patron->pending_checkouts;
622 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
623 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
625 my $first_checkout = $pending_checkouts->next;
626 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->biblionumber, 'pending_checkouts should prefetch values from other tables (here biblio)' );
628 my $overdues = $patron->get_overdues;
629 is( $overdues->count, 2, 'Patron should have 2 overdues');
630 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
631 is( $overdues->next->itemnumber, $item_1->itemnumber, 'The issue should be returned in the same order as they have been done, first is correct' );
632 is( $overdues->next->itemnumber, $item_2->itemnumber, 'The issue should be returned in the same order as they have been done, second is correct' );
635 C4::Circulation::AddReturn( $item_1->barcode );
636 C4::Circulation::AddReturn( $item_2->barcode );
637 $old_checkouts = $patron->old_checkouts;
638 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
639 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
642 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
646 subtest 'get_routing_lists' => sub {
649 my $biblio = Koha::Biblio->new()->store();
650 my $subscription = Koha::Subscription->new({
651 biblionumber => $biblio->biblionumber,
655 my $patron = $builder->build( { source => 'Borrower' } );
656 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
658 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
660 my $routinglist_count = Koha::Subscription::Routinglists->count;
661 my $routinglist = Koha::Subscription::Routinglist->new({
662 borrowernumber => $patron->borrowernumber,
664 subscriptionid => $subscription->subscriptionid
667 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
669 my $routinglists = $patron->get_routing_lists;
670 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
671 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
673 my $subscription2 = Koha::Subscription->new({
674 biblionumber => $biblio->biblionumber,
677 my $routinglist2 = Koha::Subscription::Routinglist->new({
678 borrowernumber => $patron->borrowernumber,
680 subscriptionid => $subscription2->subscriptionid
683 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
685 $patron->delete; # Clean up for later tests
689 subtest 'get_age' => sub {
692 my $patron = $builder->build( { source => 'Borrower' } );
693 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
697 today => '2020-02-28',
698 has_12 => { date => '2007-08-27', expected_age => 12 },
699 almost_18 => { date => '2002-03-01', expected_age => 17 },
700 has_18_today => { date => '2002-02-28', expected_age => 18 },
701 had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
702 almost_16 => { date => '2004-02-29', expected_age => 15 },
703 has_16_today => { date => '2004-02-28', expected_age => 16 },
704 had_16_yesterday => { date => '2004-02-27', expected_age => 16 },
705 new_born => { date => '2020-01-27', expected_age => 0 },
708 today => '2020-02-29',
709 has_12 => { date => '2007-08-27', expected_age => 12 },
710 almost_18 => { date => '2002-03-01', expected_age => 17 },
711 has_18_today => { date => '2002-02-28', expected_age => 18 },
712 had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
713 almost_16 => { date => '2004-03-01', expected_age => 15 },
714 has_16_today => { date => '2004-02-29', expected_age => 16 },
715 had_16_yesterday => { date => '2004-02-28', expected_age => 16 },
716 new_born => { date => '2020-01-27', expected_age => 0 },
719 today => '2020-03-01',
720 has_12 => { date => '2007-08-27', expected_age => 12 },
721 almost_18 => { date => '2002-03-02', expected_age => 17 },
722 has_18_today => { date => '2002-03-01', expected_age => 18 },
723 had_18_yesterday => { date => '2002-02-28', expected_age => 18 },
724 almost_16 => { date => '2004-03-02', expected_age => 15 },
725 has_16_today => { date => '2004-03-01', expected_age => 16 },
726 had_16_yesterday => { date => '2004-02-29', expected_age => 16 },
729 today => '2019-01-31',
730 has_12 => { date => '2006-08-27', expected_age => 12 },
731 almost_18 => { date => '2001-02-01', expected_age => 17 },
732 has_18_today => { date => '2001-01-31', expected_age => 18 },
733 had_18_yesterday => { date => '2001-01-30', expected_age => 18 },
734 almost_16 => { date => '2003-02-01', expected_age => 15 },
735 has_16_today => { date => '2003-01-31', expected_age => 16 },
736 had_16_yesterday => { date => '2003-01-30', expected_age => 16 },
740 $patron->dateofbirth( undef );
741 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
743 for my $date ( @dates ) {
745 my $dt = dt_from_string($date->{today});
747 Time::Fake->offset( $dt->epoch );
749 for my $k ( keys %$date ) {
750 next if $k eq 'today';
752 my $dob = $date->{$k};
753 $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
756 $dob->{expected_age},
758 "Today=%s, dob=%s, should be %d",
759 $date->{today}, $dob->{date}, $dob->{expected_age}
771 subtest 'is_valid_age' => sub {
774 my $dt = dt_from_string('2020-02-28');
776 Time::Fake->offset( $dt->epoch );
778 my $category = $builder->build({
779 source => 'Category',
781 categorycode => 'AGE_5_10',
782 dateofbirthrequired => 5,
786 $category = Koha::Patron::Categories->find( $category->{categorycode} );
788 my $patron = $builder->build({
789 source => 'Borrower',
791 categorycode => $category->categorycode
794 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
797 $patron->dateofbirth( undef );
798 is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
802 today => '2020-02-28',
804 { date => '2007-08-27', expected_age => 12, valid => 0 },
806 { date => '2016-08-27', expected_age => 3, valid => 0 },
808 { date => '2013-02-28', expected_age => 7, valid => 1 },
810 { date => '2015-02-28', expected_age => 5, valid => 1 },
812 { date => '2015-03-01', expected_age => 4, valid => 0 },
814 { date => '2015-02-27', expected_age => 5, valid => 1 },
816 { date => '2009-02-28', expected_age => 11, valid => 0 },
818 { date => '2009-03-01', expected_age => 10, valid => 1 },
820 { date => '2009-02-27', expected_age => 11, valid => 0 },
824 for my $date ( @dates ) {
826 my $dt = dt_from_string($date->{today});
828 Time::Fake->offset( $dt->epoch );
830 for my $k ( sort keys %$date ) {
831 next if $k eq 'today';
833 my $dob = $date->{$k};
834 $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
836 $patron->is_valid_age,
839 "Today=%s, dob=%s, is %s, should be valid=%s in category %s",
840 $date->{today}, $dob->{date}, $dob->{expected_age}, $dob->{valid}, $category->categorycode
853 subtest 'account' => sub {
856 my $patron = $builder->build({source => 'Borrower'});
858 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
859 my $account = $patron->account;
860 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
865 subtest 'search_upcoming_membership_expires' => sub {
868 my $expiry_days = 15;
869 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
870 my $nb_of_days_before = 1;
871 my $nb_of_days_after = 2;
873 my $builder = t::lib::TestBuilder->new();
875 my $library = $builder->build({ source => 'Branch' });
877 # before we add borrowers to this branch, add the expires we have now
878 # note that this pertains to the current mocked setting of the pref
879 # for this reason we add the new branchcode to most of the tests
880 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
882 my $patron_1 = $builder->build({
883 source => 'Borrower',
885 branchcode => $library->{branchcode},
886 dateexpiry => dt_from_string->add( days => $expiry_days )
890 my $patron_2 = $builder->build({
891 source => 'Borrower',
893 branchcode => $library->{branchcode},
894 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
898 my $patron_3 = $builder->build({
899 source => 'Borrower',
901 branchcode => $library->{branchcode},
902 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
906 # Test without extra parameters
907 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
908 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
911 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
912 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
913 my $expired = $upcoming_mem_expires->next;
914 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
915 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
916 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
918 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
919 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
920 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
922 # Test MembershipExpiryDaysNotice == undef
923 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
924 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
925 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
927 # Test the before parameter
928 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
929 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
930 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
931 # Test after parameter also
932 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
933 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
934 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
937 subtest 'holds and old_holds' => sub {
940 my $library = $builder->build( { source => 'Branch' } );
941 my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
942 my $item_1 = $builder->build_sample_item(
944 library => $library->{branchcode},
945 biblionumber => $biblionumber_1,
948 my $item_2 = $builder->build_sample_item(
950 library => $library->{branchcode},
951 biblionumber => $biblionumber_1,
954 my $biblionumber_2 = $builder->build_sample_biblio->biblionumber;
955 my $item_3 = $builder->build_sample_item(
957 library => $library->{branchcode},
958 biblionumber => $biblionumber_2,
962 my $patron = $builder->build(
964 source => 'Borrower',
965 value => { branchcode => $library->{branchcode} }
969 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
970 my $holds = $patron->holds;
971 is( ref($holds), 'Koha::Holds',
972 'Koha::Patron->holds should return a Koha::Holds objects' );
973 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
975 C4::Reserves::AddReserve(
977 branchcode => $library->{branchcode},
978 borrowernumber => $patron->borrowernumber,
979 biblionumber => $biblionumber_1
983 C4::Reserves::AddReserve(
985 branchcode => $library->{branchcode},
986 borrowernumber => $patron->borrowernumber,
987 biblionumber => $biblionumber_2,
988 expiration_date => dt_from_string->add( days => 2 )
992 $holds = $patron->holds;
993 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
995 my $old_holds = $patron->old_holds;
996 is( ref($old_holds), 'Koha::Old::Holds',
997 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
998 is( $old_holds->count, 0, 'There should not be any old holds yet');
1000 my $hold = $holds->next;
1003 $old_holds = $patron->old_holds;
1004 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
1011 subtest 'notice_email_address' => sub {
1014 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1016 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
1017 is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
1019 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
1020 is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
1025 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
1028 # TODO create a subroutine in t::lib::Mocks
1029 my $branch = $builder->build({ source => 'Branch' });
1030 my $userenv_patron = $builder->build_object({
1031 class => 'Koha::Patrons',
1032 value => { branchcode => $branch->{branchcode}, flags => 0 },
1034 t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
1036 my $anonymous = $builder->build( { source => 'Borrower', }, );
1038 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
1040 subtest 'Anonymous Patron should be undeleteable' => sub {
1043 my $anonymous_patron = Koha::Patrons->find( $anonymous->{borrowernumber} );
1044 throws_ok { $anonymous_patron->delete(); }
1045 'Koha::Exceptions::Patron::FailedDeleteAnonymousPatron',
1046 'Attempt to delete anonymous patron throws exception.';
1047 $anonymous_patron = Koha::Patrons->find( $anonymous->{borrowernumber} );
1048 is( $anonymous_patron->id, $anonymous->{borrowernumber}, "Anonymous Patron was not deleted" );
1051 subtest 'patron privacy is 1 (default)' => sub {
1054 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1055 my $patron = $builder->build(
1056 { source => 'Borrower',
1057 value => { privacy => 1, }
1060 my $item_1 = $builder->build_sample_item;
1061 my $issue_1 = $builder->build(
1062 { source => 'Issue',
1064 borrowernumber => $patron->{borrowernumber},
1065 itemnumber => $item_1->itemnumber,
1069 my $item_2 = $builder->build_sample_item;
1070 my $issue_2 = $builder->build(
1071 { source => 'Issue',
1073 borrowernumber => $patron->{borrowernumber},
1074 itemnumber => $item_2->itemnumber,
1079 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->barcode, undef, undef, dt_from_string('2010-10-10') );
1080 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->barcode, undef, undef, dt_from_string('2011-11-11') );
1081 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
1083 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
1084 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
1086 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
1087 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1089 $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1090 is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
1092 my $dbh = C4::Context->dbh;
1093 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
1094 $sth->execute($item_1->itemnumber);
1095 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1096 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
1097 $sth->execute($item_2->itemnumber);
1098 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1099 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
1101 $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
1102 $sth->execute($item_2->itemnumber);
1103 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1104 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
1106 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
1107 $sth_reset->execute( $patron->{borrowernumber}, $item_1->itemnumber );
1108 $sth_reset->execute( $patron->{borrowernumber}, $item_2->itemnumber );
1109 $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
1110 $sth->execute($item_1->itemnumber);
1111 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1112 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
1113 $sth->execute($item_2->itemnumber);
1114 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1115 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
1117 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1120 subtest 'patron privacy is 0 (forever)' => sub {
1123 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1124 my $patron = $builder->build(
1125 { source => 'Borrower',
1126 value => { privacy => 0, }
1129 my $item = $builder->build_sample_item;
1130 my $issue = $builder->build(
1131 { source => 'Issue',
1133 borrowernumber => $patron->{borrowernumber},
1134 itemnumber => $item->itemnumber,
1139 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1140 is( $returned, 1, 'The item should have been returned' );
1142 my $dbh = C4::Context->dbh;
1143 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1144 SELECT borrowernumber FROM old_issues where itemnumber = ?
1145 |, undef, $item->itemnumber);
1146 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1147 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1150 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1152 subtest 'AnonymousPatron is not defined' => sub {
1155 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1156 my $patron = $builder->build(
1157 { source => 'Borrower',
1158 value => { privacy => 1, }
1161 my $item = $builder->build_sample_item;
1162 my $issue = $builder->build(
1163 { source => 'Issue',
1165 borrowernumber => $patron->{borrowernumber},
1166 itemnumber => $item->itemnumber,
1171 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1172 is( $returned, 1, 'The item should have been returned' );
1173 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
1174 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1176 my $dbh = C4::Context->dbh;
1177 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1178 SELECT borrowernumber FROM old_issues where itemnumber = ?
1179 |, undef, $item->itemnumber);
1180 is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
1181 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1184 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1186 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1187 my $patron = $builder->build(
1188 { source => 'Borrower',
1189 value => { privacy => 1 } # Another branchcode than the logged in librarian
1192 my $item = $builder->build_sample_item;
1193 my $issue = $builder->build(
1194 { source => 'Issue',
1196 borrowernumber => $patron->{borrowernumber},
1197 itemnumber => $item->itemnumber,
1202 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1203 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1204 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1207 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1208 $userenv_patron->delete;
1210 # Reset IndependentBranches for further tests
1211 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1214 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1222 $nb_of_patrons = Koha::Patrons->search->count;
1223 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1224 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1225 my $library_11 = $builder->build( { source => 'Branch' } );
1226 my $library_12 = $builder->build( { source => 'Branch' } );
1227 my $library_21 = $builder->build( { source => 'Branch' } );
1228 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1229 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1230 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1231 Koha::Library::Group->new(
1232 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1233 Koha::Library::Group->new(
1234 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1235 Koha::Library::Group->new(
1236 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1238 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1239 # 2 patrons from library_11 (group1)
1240 # patron_11_1 see patron's infos from outside its group
1241 # Setting flags => undef to not be considered as superlibrarian
1242 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1243 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1244 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1245 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1246 # patron_11_2 can only see patron's info from its group
1247 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1248 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1249 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1250 # 1 patron from library_12 (group1)
1251 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1252 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1253 # 1 patron from library_21 (group2) can only see patron's info from its group
1254 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1255 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1256 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1258 # Pfiou, we can start now!
1259 subtest 'libraries_where_can_see_patrons' => sub {
1264 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1265 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1266 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1268 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1269 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1270 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| );
1272 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1273 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1274 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| );
1276 subtest 'can_see_patron_infos' => sub {
1279 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1280 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1281 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1282 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1284 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1285 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1286 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1287 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1289 subtest 'search_limited' => sub {
1292 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1293 my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1294 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1295 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1297 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1298 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1299 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' );
1301 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1302 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1303 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1305 $patron_11_1->delete;
1306 $patron_11_2->delete;
1311 subtest 'account_locked' => sub {
1313 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1314 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1315 for my $value ( undef, '', 0 ) {
1316 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1317 $patron->login_attempts(0)->store;
1318 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1319 $patron->login_attempts(1)->store;
1320 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1321 $patron->login_attempts(-1)->store;
1322 is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1325 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1326 $patron->login_attempts(2)->store;
1327 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1328 $patron->login_attempts(3)->store;
1329 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1330 $patron->login_attempts(4)->store;
1331 is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1332 $patron->login_attempts(-1)->store;
1333 is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1338 subtest 'is_child | is_adult' => sub {
1340 my $category = $builder->build_object(
1342 class => 'Koha::Patron::Categories',
1343 value => { category_type => 'A' }
1346 my $patron_adult = $builder->build_object(
1348 class => 'Koha::Patrons',
1349 value => { categorycode => $category->categorycode }
1352 $category = $builder->build_object(
1354 class => 'Koha::Patron::Categories',
1355 value => { category_type => 'I' }
1358 my $patron_adult_i = $builder->build_object(
1360 class => 'Koha::Patrons',
1361 value => { categorycode => $category->categorycode }
1364 $category = $builder->build_object(
1366 class => 'Koha::Patron::Categories',
1367 value => { category_type => 'C' }
1370 my $patron_child = $builder->build_object(
1372 class => 'Koha::Patrons',
1373 value => { categorycode => $category->categorycode }
1376 $category = $builder->build_object(
1378 class => 'Koha::Patron::Categories',
1379 value => { category_type => 'O' }
1382 my $patron_other = $builder->build_object(
1384 class => 'Koha::Patrons',
1385 value => { categorycode => $category->categorycode }
1388 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1389 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1390 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1391 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1393 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1394 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1395 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1396 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1399 $patron_adult->delete;
1400 $patron_adult_i->delete;
1401 $patron_child->delete;
1402 $patron_other->delete;
1405 subtest 'get_overdues' => sub {
1408 my $library = $builder->build( { source => 'Branch' } );
1409 my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
1410 my $item_1 = $builder->build_sample_item(
1412 library => $library->{branchcode},
1413 biblionumber => $biblionumber_1,
1416 my $item_2 = $builder->build_sample_item(
1418 library => $library->{branchcode},
1419 biblionumber => $biblionumber_1,
1422 my $item_3 = $builder->build_sample_item(
1424 library => $library->{branchcode},
1428 my $patron = $builder->build(
1430 source => 'Borrower',
1431 value => { branchcode => $library->{branchcode} }
1435 t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1437 AddIssue( $patron, $item_1->barcode, DateTime->now->subtract( days => 1 ) );
1438 AddIssue( $patron, $item_2->barcode, DateTime->now->subtract( days => 5 ) );
1439 AddIssue( $patron, $item_3->barcode );
1441 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1442 my $overdues = $patron->get_overdues;
1443 is( $overdues->count, 2, 'Patron should have 2 overdues');
1444 is( $overdues->next->itemnumber, $item_1->itemnumber, 'The issue should be returned in the same order as they have been done, first is correct' );
1445 is( $overdues->next->itemnumber, $item_2->itemnumber, 'The issue should be returned in the same order as they have been done, second is correct' );
1447 my $o = $overdues->reset->next;
1448 my $unblessed_overdue = $o->unblessed_all_relateds;
1449 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1450 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1451 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1452 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1455 $patron->checkouts->delete;
1459 subtest 'userid_is_valid' => sub {
1462 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1463 my $patron_category = $builder->build_object(
1465 class => 'Koha::Patron::Categories',
1466 value => { category_type => 'P', enrolmentfee => 0 }
1470 cardnumber => "123456789",
1471 firstname => "Tomasito",
1473 categorycode => $patron_category->categorycode,
1474 branchcode => $library->branchcode,
1477 my $expected_userid_patron_1 = 'tomasito.none';
1478 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1479 my $patron_1 = Koha::Patrons->find($borrowernumber);
1480 is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1481 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1483 $patron_1->userid( 'tomasito.non' );
1484 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1485 1, 'recently created userid -> unique (borrowernumber passed)' );
1487 $patron_1->userid( 'tomasitoxxx' );
1488 is( $patron_1->has_valid_userid,
1489 1, 'non-existent userid -> unique (borrowernumber passed)' );
1490 $patron_1->discard_changes; # We compare with the original userid later
1492 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1493 is( $patron_not_in_storage->has_valid_userid,
1494 0, 'userid exists for another patron, patron is not in storage yet' );
1496 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1497 is( $patron_not_in_storage->has_valid_userid,
1498 1, 'non-existent userid, patron is not in storage yet' );
1500 # Regression tests for BZ12226
1501 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1502 is( $db_patron->has_valid_userid,
1503 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1505 # Add a new borrower with the same userid but different cardnumber
1506 $data{cardnumber} = "987654321";
1507 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1508 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1509 $patron_2->userid($patron_1->userid);
1510 is( $patron_2->has_valid_userid,
1511 0, 'The userid is already in used, it cannot be used for another patron' );
1513 my $new_userid = 'a_user_id';
1514 $data{cardnumber} = "234567890";
1515 $data{userid} = 'a_user_id';
1516 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1517 my $patron_3 = Koha::Patrons->find($borrowernumber);
1518 is( $patron_3->userid, $new_userid,
1519 'Koha::Patron->store should insert the given userid' );
1527 subtest 'generate_userid' => 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 => "Tômà sÃtó",
1540 surname => "Ñoné",
1541 categorycode => $patron_category->categorycode,
1542 branchcode => $library->branchcode,
1545 my $expected_userid_patron_1 = 'tomasito.none';
1546 my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1547 $new_patron->generate_userid;
1548 my $userid = $new_patron->userid;
1549 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1550 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1551 my $patron_1 = Koha::Patrons->find($borrowernumber);
1552 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1554 $new_patron->generate_userid;
1555 $userid = $new_patron->userid;
1556 is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1557 $data{cardnumber} = '987654321';
1558 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1559 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1560 isnt( $patron_2->userid, 'tomasito',
1561 "Patron with duplicate userid has new userid generated" );
1562 is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1563 "Patron with duplicate userid has new userid generated (1 is appened" );
1565 $new_patron->generate_userid;
1566 $userid = $new_patron->userid;
1567 is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1569 $patron_1 = Koha::Patrons->find($borrowernumber);
1570 $patron_1->userid(undef);
1571 $patron_1->generate_userid;
1572 $userid = $patron_1->userid;
1573 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1580 $nb_of_patrons = Koha::Patrons->search->count;
1581 $retrieved_patron_1->delete;
1582 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1584 subtest 'BorrowersLog tests' => sub {
1587 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1588 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1590 my $cardnumber = $patron->cardnumber;
1591 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1594 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1595 my $log_info = from_json( $logs[0]->info );
1596 is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1597 is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1598 is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1600 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1601 $patron->track_login();
1602 @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1603 is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1606 $schema->storage->txn_rollback;
1608 subtest 'Test Koha::Patrons::merge' => sub {
1611 my $schema = Koha::Database->new()->schema();
1613 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1615 $schema->storage->txn_begin;
1617 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1618 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1619 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1621 my $anonymous_patron_orig = C4::Context->preference('AnonymousPatron');
1622 my $anonymous_patron = $builder->build({ source => 'Borrower' })->{borrowernumber};
1623 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron );
1625 while (my ($r, $field) = each(%$resultsets)) {
1626 $builder->build({ source => $r, value => { $field => $keeper->id } });
1627 $builder->build({ source => $r, value => { $field => $loser_1 } });
1628 $builder->build({ source => $r, value => { $field => $loser_2 } });
1631 $schema->resultset($r)->search( { $field => $keeper->id } );
1632 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1635 $schema->resultset($r)->search( { $field => $loser_1 } );
1636 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1639 $schema->resultset($r)->search( { $field => $loser_2 } );
1640 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1643 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1645 while (my ($r, $field) = each(%$resultsets)) {
1647 $schema->resultset($r)->search( {$field => $keeper->id } );
1648 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1651 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1652 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1653 is( ref Koha::Patrons->find($anonymous_patron), 'Koha::Patron', 'Anonymous Patron was not deleted' );
1655 $anonymous_patron = Koha::Patrons->find($anonymous_patron);
1656 $results = $anonymous_patron->merge_with( [ $keeper->id ] );
1657 is( $results, undef, "Anonymous patron cannot have other patrons merged into it" );
1658 is( Koha::Patrons->search( { borrowernumber => $keeper->id } )->count, 1, "Patron from attempted merge with AnonymousPatron still exists" );
1660 subtest 'extended attributes' => sub {
1664 $builder->build_object( { class => 'Koha::Patrons' } );
1666 $builder->build_object( { class => 'Koha::Patrons' } );
1668 my $attribute_type_normal_1 = $builder->build_object(
1670 class => 'Koha::Patron::Attribute::Types',
1671 value => { repeatable => 0, unique_id => 0 }
1674 my $attribute_type_normal_2 = $builder->build_object(
1676 class => 'Koha::Patron::Attribute::Types',
1677 value => { repeatable => 0, unique_id => 0 }
1681 my $attribute_type_repeatable = $builder->build_object(
1683 class => 'Koha::Patron::Attribute::Types',
1684 value => { repeatable => 1, unique_id => 0 }
1690 code => $attribute_type_normal_1->code,
1691 attribute => 'from attr 1'
1694 code => $attribute_type_repeatable->code,
1695 attribute => 'from attr repeatable'
1701 code => $attribute_type_normal_2->code,
1702 attribute => 'to attr 2'
1705 code => $attribute_type_repeatable->code,
1706 attribute => 'to attr repeatable'
1710 $keep_patron->extended_attributes($attr_keep);
1711 $merge_patron->extended_attributes($attr_merge);
1713 $keep_patron->merge_with( [ $merge_patron->borrowernumber ] );
1714 my $merged_attributes = $keep_patron->extended_attributes;
1715 is( $merged_attributes->count, 4 );
1717 sub compare_attributes {
1718 my ( $got, $expected, $code ) = @_;
1722 sort $got->search( { code => $code } )
1723 ->get_column('attribute')
1731 $attribute_type_normal_1->code
1736 $attribute_type_normal_2->code
1740 [ 'from attr repeatable', 'to attr repeatable' ],
1741 $attribute_type_repeatable->code
1745 $keep_patron->delete;
1746 $merge_patron->delete;
1748 # Recreate but expect an exception because 2 "normal" attributes will be in the resulting patron
1750 $builder->build_object( { class => 'Koha::Patrons' } );
1752 $builder->build_object( { class => 'Koha::Patrons' } );
1754 $keep_patron->extended_attributes($attr_keep);
1755 $merge_patron->extended_attributes(
1759 code => $attribute_type_normal_1->code,
1760 attribute => 'yet another attribute for non-repeatable'
1766 $keep_patron->merge_with( [ $merge_patron->borrowernumber ] );
1768 'Koha::Exceptions::Patron::Attribute::NonRepeatable',
1769 'Exception thrown trying to merge several non-repeatable attributes';
1772 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1773 $schema->storage->txn_rollback;
1776 subtest '->store' => sub {
1778 my $schema = Koha::Database->new->schema;
1779 $schema->storage->txn_begin;
1781 my $print_error = $schema->storage->dbh->{PrintError};
1782 $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1784 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1785 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1789 open STDERR, '>', '/dev/null';
1790 throws_ok { $patron_2->userid( $patron_1->userid )->store; }
1791 'Koha::Exceptions::Object::DuplicateID',
1792 'Koha::Patron->store raises an exception on duplicate ID';
1797 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1798 my $password = 'password';
1799 $patron_1->set_password({ password => $password });
1800 like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1801 my $digest = $patron_1->password;
1802 $patron_1->surname('xxx')->store;
1803 is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1805 # Test uppercasesurnames
1806 t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 );
1807 my $surname = lc $patron_1->surname;
1808 $patron_1->surname($surname)->store;
1809 isnt( $patron_1->surname, $surname,
1810 'Surname converts to uppercase on store.');
1811 t::lib::Mocks::mock_preference( 'uppercasesurnames', 0 );
1812 $patron_1->surname($surname)->store;
1813 is( $patron_1->surname, $surname,
1814 'Surname remains unchanged on store.');
1817 $patron_1->relationship("")->store;
1818 is( $patron_1->relationship, undef, );
1820 $schema->storage->dbh->{PrintError} = $print_error;
1821 $schema->storage->txn_rollback;
1823 subtest 'skip updated_on for BorrowersLog' => sub {
1825 $schema->storage->txn_begin;
1826 t::lib::Mocks::mock_preference('BorrowersLog', 1);
1827 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1828 $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1829 my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1830 is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1831 $schema->storage->txn_rollback;
1835 subtest '->set_password' => sub {
1839 $schema->storage->txn_begin;
1841 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1843 # Disable logging password changes for this tests
1844 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1846 # Password-length tests
1847 t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1848 throws_ok { $patron->set_password({ password => 'ab' }); }
1849 'Koha::Exceptions::Password::TooShort',
1850 'minPasswordLength is undef, fall back to 3, fail test';
1852 'Password length (2) is shorter than required (3)',
1853 'Exception parameters passed correctly'
1856 t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1857 throws_ok { $patron->set_password({ password => 'ab' }); }
1858 'Koha::Exceptions::Password::TooShort',
1859 'minPasswordLength is 2, fall back to 3, fail test';
1861 t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1862 throws_ok { $patron->set_password({ password => 'abcb' }); }
1863 'Koha::Exceptions::Password::TooShort',
1864 'minPasswordLength is 5, fail test';
1866 # Trailing spaces tests
1867 throws_ok { $patron->set_password({ password => 'abcD12d ' }); }
1868 'Koha::Exceptions::Password::WhitespaceCharacters',
1869 'Password contains trailing spaces, exception is thrown';
1871 # Require strong password tests
1872 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1873 throws_ok { $patron->set_password({ password => 'abcd a' }); }
1874 'Koha::Exceptions::Password::TooWeak',
1875 'Password is too weak, exception is thrown';
1877 # Refresh patron from DB, just to make sure
1878 $patron->discard_changes;
1879 is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1881 $patron->set_password({ password => 'abcD12 34' });
1882 $patron->discard_changes;
1884 is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1886 lives_ok { $patron->set_password({ password => 'abcd a', skip_validation => 1 }) }
1887 'Password is weak, but skip_validation was passed, so no exception thrown';
1890 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1891 $patron->login_attempts(3)->store;
1892 my $old_digest = $patron->password;
1893 $patron->set_password({ password => 'abcd a' });
1894 $patron->discard_changes;
1896 isnt( $patron->password, $old_digest, 'Password has been updated' );
1897 ok( checkpw_hash('abcd a', $patron->password), 'Password hash is correct' );
1898 is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1900 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1901 is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1903 # Enable logging password changes
1904 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1905 $patron->set_password({ password => 'abcd b' });
1907 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1908 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1910 $schema->storage->txn_rollback;
1913 $schema->storage->txn_begin;
1914 subtest 'filter_by_expiration_date' => sub {
1916 my $count1 = Koha::Patrons->filter_by_expiration_date({ days => 28 })->count;
1917 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1918 $patron1->dateexpiry( dt_from_string->subtract(days => 27) )->store;
1919 is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1, 'No more expired' );
1920 $patron1->dateexpiry( dt_from_string->subtract(days => 28) )->store;
1921 is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1 + 1, 'One more expired' );
1922 $patron1->dateexpiry( dt_from_string->subtract(days => 29) )->store;
1923 is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1 + 1, 'Same number again' );
1926 subtest 'search_unsubscribed' => sub {
1929 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1930 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
1931 is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
1933 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1934 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1936 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
1937 Koha::Patron::Consents->delete; # for correct counts
1938 Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string })->store;
1939 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
1941 # Add another refusal but shift the period
1942 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
1943 Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string->subtract(days=>2) })->store;
1944 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
1946 # Try another (special) attempts setting
1947 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
1948 # Lockout is now disabled
1949 # Patron2 still matches: refused earlier, not locked
1950 is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
1953 subtest 'search_anonymize_candidates' => sub {
1955 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1956 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1957 $patron1->anonymized(0);
1958 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1959 $patron2->anonymized(0);
1960 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1962 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
1963 is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
1965 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
1966 my $cnt = Koha::Patrons->search_anonymize_candidates->count;
1967 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1968 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1969 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
1971 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
1972 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1973 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1974 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1975 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1976 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1977 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
1979 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
1980 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1981 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1982 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1983 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1984 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1985 is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
1987 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1988 $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1989 $patron1->login_attempts(0)->store;
1990 $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1991 $patron2->login_attempts(0)->store;
1992 $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
1993 $patron1->login_attempts(3)->store;
1994 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1995 $cnt+1, 'Locked flag' );
1997 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1998 # Patron 1 still on 3 == locked
1999 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2000 $cnt+1, 'Still expect same number for FailedLoginAttempts empty' );
2001 $patron1->login_attempts(0)->store;
2003 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2004 $cnt, 'Patron 1 unlocked' );
2007 subtest 'search_anonymized' => sub {
2009 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2011 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
2012 is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
2014 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
2015 $patron1->dateexpiry( dt_from_string );
2016 $patron1->anonymized(0)->store;
2017 my $cnt = Koha::Patrons->search_anonymized->count;
2018 $patron1->anonymized(1)->store;
2019 is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
2020 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2021 is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
2024 subtest 'lock' => sub {
2027 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2028 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
2029 my $hold = $builder->build_object({
2030 class => 'Koha::Holds',
2031 value => { borrowernumber => $patron1->borrowernumber },
2034 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
2035 my $expiry = dt_from_string->add(days => 1);
2036 $patron1->dateexpiry( $expiry );
2038 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
2039 is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
2040 is( $patron1->holds->count, 1, 'No holds removed' );
2042 $patron1->lock({ expire => 1, remove => 1});
2043 isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
2044 is( $patron1->holds->count, 0, 'Holds removed' );
2046 # Disable lockout feature
2047 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
2048 $patron1->login_attempts(0);
2049 $patron1->dateexpiry( $expiry );
2052 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
2054 # Trivial wrapper test (Koha::Patrons->lock)
2055 $patron1->login_attempts(0)->store;
2056 Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
2057 $patron1->discard_changes; # refresh
2058 $patron2->discard_changes;
2059 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
2060 is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
2063 subtest 'anonymize' => sub {
2066 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2067 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
2069 # First try patron with issues
2070 my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
2071 warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
2074 t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
2075 my $surname = $patron1->surname; # expect change, no clear
2076 my $branchcode = $patron1->branchcode; # expect skip
2077 $patron1->anonymize;
2078 is($patron1->anonymized, 1, 'Check flag' );
2080 is( $patron1->dateofbirth, undef, 'Birth date cleared' );
2081 is( $patron1->firstname, undef, 'First name cleared' );
2082 isnt( $patron1->surname, $surname, 'Surname changed' );
2083 ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
2084 is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
2085 is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
2087 # Test wrapper in Koha::Patrons
2088 $patron1->surname($surname)->store; # restore
2089 my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
2090 $patron1->discard_changes; # refresh
2091 isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
2092 $patron2->discard_changes; # refresh
2093 is( $patron2->firstname, undef, 'First name patron2 cleared' );
2096 subtest 'queue_notice' => sub {
2099 my $dbh = C4::Context->dbh;
2100 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'email' );
2101 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2102 my $branch = $builder->build_object( { class => 'Koha::Libraries' } );
2103 my $letter_e = $builder->build_object( {
2104 class => 'Koha::Notice::Templates',
2106 branchcode => $branch->branchcode,
2107 message_transport_type => 'email',
2111 my $letter_p = $builder->build_object( {
2112 class => 'Koha::Notice::Templates',
2114 code => $letter_e->code,
2115 module => $letter_e->module,
2116 branchcode => $branch->branchcode,
2117 message_transport_type => 'print',
2121 my $letter_s = $builder->build_object( {
2122 class => 'Koha::Notice::Templates',
2124 code => $letter_e->code,
2125 module => $letter_e->module,
2126 branchcode => $branch->branchcode,
2127 message_transport_type => 'sms',
2132 my $letter_params = {
2133 letter_code => $letter_e->code,
2134 branchcode => $letter_e->branchcode,
2135 module => $letter_e->module,
2136 borrowernumber => $patron->borrowernumber,
2138 borrowers => $patron->borrowernumber,
2141 my @mtts = ('email');
2143 is( $patron->queue_notice(), undef, "Nothing is done if no params passed");
2144 is( $patron->queue_notice({ letter_params => $letter_params }),undef, "Nothing done if only letter");
2146 $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2147 {sent => ['email'] }, "Email sent"
2149 $patron->email("")->store;
2151 $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2152 {sent => ['print'],fallback => ['email']}, "Email fallsback to print if no email"
2156 $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2157 {sent => ['print','sms'],fallback => ['email']}, "Email fallsback to print if no email, sms sent"
2159 $patron->smsalertnumber("")->store;
2160 my $counter = Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count;
2162 $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2163 {sent => ['print'],fallback => ['email','sms']}, "Email fallsback to print if no emai, sms fallsback to print if no sms, only one print sent"
2165 is( Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count, $counter+1,"Count of queued notices went up by one");
2167 # Enable notification for Hold_Filled - Things are hardcoded here but should work with default data
2168 $dbh->do(q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ?)|, undef, $patron->borrowernumber, 4 );
2169 my $borrower_message_preference_id = $dbh->last_insert_id(undef, undef, "borrower_message_preferences", undef);
2170 $dbh->do(q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, undef, $borrower_message_preference_id, 'email' );
2172 is( $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts, message_name => 'Hold_Filled' }),undef, "Nothing done if transports and name sent");
2174 $patron->email(q|awesome@ismymiddle.name|)->store;
2176 $patron->queue_notice({ letter_params => $letter_params, message_name => 'Hold_Filled' }),
2177 {sent => ['email'] }, "Email sent when using borrower preferences"
2179 $counter = Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count;
2181 $patron->queue_notice({ letter_params => $letter_params, message_name => 'Hold_Filled', test_mode => 1 }),
2182 {sent => ['email'] }, "Report that email sent when using borrower preferences in test_mode"
2184 is( Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count, $counter,"Count of queued notices not increased in test mode");
2187 $schema->storage->txn_rollback;