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 => 44;
31 use C4::Circulation qw( AddIssue AddReturn );
33 use C4::Auth qw( checkpw checkpw_hash );
39 use Koha::Old::Patrons;
40 use Koha::Patron::Attribute::Types;
41 use Koha::Patron::Categories;
42 use Koha::Patron::Relationship;
44 use Koha::DateUtils qw( dt_from_string output_pref );
45 use Koha::Virtualshelves;
46 use Koha::Notice::Messages;
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 is( $retrieved_patron_1->sms_provider, undef, '->sms_provider should return undef if none defined' );
95 $retrieved_patron_1->sms_provider_id( $sms_provider->{id} )->store;
96 is_deeply( $retrieved_patron_1->sms_provider->unblessed, $sms_provider, 'Koha::Patron->sms_provider returns the correct SMS provider' );
97 is( ref($retrieved_patron_1->sms_provider), 'Koha::SMS::Provider', 'Koha::Patron->sms_provider should return a Koha::SMS::Provider object' );
100 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' );
110 my $guarantee_1 = $builder->build({ source => 'Borrower' });
111 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
112 my $guarantee_2 = $builder->build({ source => 'Borrower' });
113 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
115 $guarantees = $new_patron_1->guarantee_relationships;
116 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantee_relationships should return a Koha::Patrons result set in a scalar context' );
117 is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
121 #Test return order of guarantees BZ 18635
122 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
123 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
125 my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
127 my $order_guarantee1 = $builder->build_object(
129 class => 'Koha::Patrons',
135 $builder->build_object(
137 class => 'Koha::Patron::Relationships',
139 guarantor_id => $guarantor->id,
140 guarantee_id => $order_guarantee1,
141 relationship => 'test',
146 my $order_guarantee2 = $builder->build_object(
148 class => 'Koha::Patrons',
154 $builder->build_object(
156 class => 'Koha::Patron::Relationships',
158 guarantor_id => $guarantor->id,
159 guarantee_id => $order_guarantee2,
160 relationship => 'test',
165 my $order_guarantee3 = $builder->build_object(
167 class => 'Koha::Patrons',
170 firstname => 'Walrus',
174 $builder->build_object(
176 class => 'Koha::Patron::Relationships',
178 guarantor_id => $guarantor->id,
179 guarantee_id => $order_guarantee3,
180 relationship => 'test',
185 my $order_guarantee4 = $builder->build_object(
187 class => 'Koha::Patrons',
190 firstname => 'Vulture',
191 guarantorid => $guarantor->borrowernumber
195 $builder->build_object(
197 class => 'Koha::Patron::Relationships',
199 guarantor_id => $guarantor->id,
200 guarantee_id => $order_guarantee4,
201 relationship => 'test',
206 my $order_guarantee5 = $builder->build_object(
208 class => 'Koha::Patrons',
211 firstname => 'Unicorn',
212 guarantorid => $guarantor->borrowernumber
216 my $r = $builder->build_object(
218 class => 'Koha::Patron::Relationships',
220 guarantor_id => $guarantor->id,
221 guarantee_id => $order_guarantee5,
222 relationship => 'test',
227 $guarantees = $guarantor->guarantee_relationships->guarantees;
229 is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
230 is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
231 is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
232 is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
233 is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
236 subtest 'category' => sub {
238 my $patron_category = $new_patron_1->category;
239 is( ref( $patron_category), 'Koha::Patron::Category', );
240 is( $patron_category->categorycode, $category->{categorycode}, );
243 subtest 'siblings' => sub {
247 my $siblings = $new_patron_1->siblings;
248 is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
249 my $guarantee_1 = $builder->build( { source => 'Borrower' } );
250 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
251 my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
252 $siblings = $retrieved_guarantee_1->siblings;
253 is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
254 is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' );
255 my $guarantee_2 = $builder->build( { source => 'Borrower' } );
256 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
257 my $guarantee_3 = $builder->build( { source => 'Borrower' } );
258 my $relationship_3 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_3->{borrowernumber}, relationship => 'test' } )->store();
259 $siblings = $retrieved_guarantee_1->siblings;
260 is( $siblings->count, 2, 'guarantee_1 should have 2 siblings' );
261 is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
262 is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
263 $_->delete for $retrieved_guarantee_1->siblings;
264 $retrieved_guarantee_1->delete;
267 subtest 'has_overdues' => sub {
270 my $item_1 = $builder->build_sample_item;
271 my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
272 is( $retrieved_patron->has_overdues, 0, );
274 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
275 my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->itemnumber, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
276 is( $retrieved_patron->has_overdues, 0, );
278 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
279 $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->itemnumber, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
280 $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
281 is( $retrieved_patron->has_overdues, 1, );
285 subtest 'is_expired' => sub {
287 my $patron = $builder->build({ source => 'Borrower' });
288 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
289 $patron->dateexpiry( undef )->store->discard_changes;
290 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
291 $patron->dateexpiry( dt_from_string )->store->discard_changes;
292 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
293 $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
294 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
295 $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
296 is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
301 subtest 'is_going_to_expire' => sub {
304 my $today = dt_from_string(undef, undef, 'floating');
305 my $patron = $builder->build({ source => 'Borrower' });
306 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
307 $patron->dateexpiry( undef )->store->discard_changes;
308 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
310 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
311 $patron->dateexpiry( $today )->store->discard_changes;
312 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
314 $patron->dateexpiry( $today )->store->discard_changes;
315 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
317 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
318 $patron->dateexpiry( $today->clone->add( days => 11 ) )->store->discard_changes;
319 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');
321 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
322 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
323 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');
325 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
326 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
327 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');
330 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
331 $patron->dateexpiry( $today->clone->add( days => 20 ) )->store->discard_changes;
332 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');
334 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
335 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
336 is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
338 { # Testing invalid is going to expiry date
339 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 30);
340 # mock_config does not work here, because of tz vs timezone subroutines
341 my $context = Test::MockModule->new('C4::Context');
342 $context->mock( 'tz', sub {
345 $patron->dateexpiry(DateTime->new( year => 2019, month => 12, day => 3 ))->store;
346 eval { $patron->is_going_to_expire };
347 is( $@, '', 'On invalid "is going to expire" date, the method should not crash with "Invalid local time for date in time zone"');
348 $context->unmock('tz');
355 subtest 'renew_account' => sub {
358 for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
359 my $dt = dt_from_string( $date, 'iso' );
360 Time::Fake->offset( $dt->epoch );
361 my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
362 my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
363 my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
364 my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
365 my $a_year_later_plus_a_month = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
366 my $patron_category = $builder->build(
367 { source => 'Category',
369 enrolmentperiod => 12,
370 enrolmentperioddate => undef,
374 my $patron = $builder->build(
375 { source => 'Borrower',
377 dateexpiry => $a_month_ago,
378 categorycode => $patron_category->{categorycode},
379 date_renewed => undef, # Force builder to not populate the column for new patron
383 my $patron_2 = $builder->build(
384 { source => 'Borrower',
386 dateexpiry => $a_month_ago,
387 categorycode => $patron_category->{categorycode},
391 my $patron_3 = $builder->build(
392 { source => 'Borrower',
394 dateexpiry => $a_month_later,
395 categorycode => $patron_category->{categorycode},
399 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
400 my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
401 my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
403 is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
405 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
406 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
407 my $expiry_date = $retrieved_patron->renew_account;
408 is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
409 my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
410 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" );
411 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
412 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
414 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
415 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
416 $expiry_date = $retrieved_patron->renew_account;
417 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
418 $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
419 is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
420 $retrieved_expiry_date = $retrieved_patron->dateexpiry;
421 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
422 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
423 is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
425 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
426 $expiry_date = $retrieved_patron_2->renew_account;
427 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
428 $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
429 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
431 $expiry_date = $retrieved_patron_3->renew_account;
432 is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
433 $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
434 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" );
436 $retrieved_patron->delete;
437 $retrieved_patron_2->delete;
438 $retrieved_patron_3->delete;
443 subtest "move_to_deleted" => sub {
445 my $originally_updated_on = '2016-01-01 12:12:12';
446 my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
447 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
448 is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
449 ; # FIXME This should be Koha::Deleted::Patron
450 my $deleted_patron = $schema->resultset('Deletedborrower')
451 ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
453 ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
454 ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
455 isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
456 $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
457 is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
458 $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup
461 subtest "delete" => sub {
463 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
464 my $patron = $builder->build( { source => 'Borrower' } );
465 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
466 my $hold = $builder->build(
467 { source => 'Reserve',
468 value => { borrowernumber => $patron->{borrowernumber} }
471 my $list = $builder->build(
472 { source => 'Virtualshelve',
473 value => { owner => $patron->{borrowernumber} }
476 my $modification = $builder->build_object({ class => 'Koha::Patron::Modifications', value => { borrowernumber => $patron->{borrowernumber} } });
478 my $deleted = $retrieved_patron->delete;
479 is( ref($deleted), 'Koha::Patron', 'Koha::Patron->delete should return the deleted patron object if the patron has been correctly deleted' );
481 is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
483 is (Koha::Old::Holds->search( { reserve_id => $hold->{ reserve_id } } )->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| );
485 is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have cancelled patron's holds 2| );
487 is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
489 is( Koha::Patron::Modifications->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's modifications| );
491 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
492 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
495 subtest 'Koha::Patrons->delete' => sub {
498 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
499 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
500 my $id1 = $patron1->borrowernumber;
501 my $set = Koha::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
502 is( $set->count, 2, 'Two patrons found as expected' );
503 is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
504 my $deleted_patrons = Koha::Old::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
505 is( $deleted_patrons->count, 2, 'Patrons moved to deletedborrowers' );
507 # See other tests in t/db_dependent/Koha/Objects.t
510 subtest 'add_enrolment_fee_if_needed' => sub {
513 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
514 foreach( keys %{$enrolmentfees} ) {
515 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
517 my $enrolmentfee_K = $enrolmentfees->{K};
518 my $enrolmentfee_J = $enrolmentfees->{J};
519 my $enrolmentfee_YA = $enrolmentfees->{YA};
521 my %borrower_data = (
522 firstname => 'my firstname',
523 surname => 'my surname',
525 branchcode => $library->{branchcode},
528 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
529 $borrower_data{borrowernumber} = $borrowernumber;
531 my $patron = Koha::Patrons->find( $borrowernumber );
532 my $total = $patron->account->balance;
533 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
535 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
536 $borrower_data{categorycode} = 'J';
537 $patron->set(\%borrower_data)->store;
538 $total = $patron->account->balance;
539 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
541 $borrower_data{categorycode} = 'K';
542 $patron->set(\%borrower_data)->store;
543 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
545 $borrower_data{categorycode} = 'J';
546 $patron->set(\%borrower_data)->store;
547 $total = $patron->account->balance;
548 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
550 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
551 $patron->categorycode('YA')->store;
552 $total = $patron->account->balance;
554 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
555 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
561 subtest 'checkouts + pending_checkouts + overdues + old_checkouts' => sub {
564 my $library = $builder->build( { source => 'Branch' } );
565 my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
566 my $item_1 = $builder->build_sample_item(
568 library => $library->{branchcode},
569 biblionumber => $biblionumber_1,
572 my $item_2 = $builder->build_sample_item(
574 library => $library->{branchcode},
575 biblionumber => $biblionumber_1,
578 my $biblionumber_2 = $builder->build_sample_biblio->biblionumber;
579 my $item_3 = $builder->build_sample_item(
581 library => $library->{branchcode},
582 biblionumber => $biblionumber_2,
585 my $patron = $builder->build(
587 source => 'Borrower',
588 value => { branchcode => $library->{branchcode} }
592 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
593 my $checkouts = $patron->checkouts;
594 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
595 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
596 my $pending_checkouts = $patron->pending_checkouts;
597 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
598 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
599 my $old_checkouts = $patron->old_checkouts;
600 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
601 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
603 # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
604 $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
606 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
608 AddIssue( $patron, $item_1->barcode, DateTime->now->subtract( days => 1 ) );
609 AddIssue( $patron, $item_2->barcode, DateTime->now->subtract( days => 5 ) );
610 AddIssue( $patron, $item_3->barcode );
612 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
613 $checkouts = $patron->checkouts;
614 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
615 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
616 $pending_checkouts = $patron->pending_checkouts;
617 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
618 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
620 my $first_checkout = $pending_checkouts->next;
621 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->biblionumber, 'pending_checkouts should prefetch values from other tables (here biblio)' );
623 my $overdues = $patron->overdues;
624 is( $overdues->count, 2, 'Patron should have 2 overdues');
625 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->overdues should return Koha::Checkouts' );
626 is( $overdues->next->itemnumber, $item_1->itemnumber, 'The issue should be returned in the same order as they have been done, first is correct' );
627 is( $overdues->next->itemnumber, $item_2->itemnumber, 'The issue should be returned in the same order as they have been done, second is correct' );
630 C4::Circulation::AddReturn( $item_1->barcode );
631 C4::Circulation::AddReturn( $item_2->barcode );
632 $old_checkouts = $patron->old_checkouts;
633 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
634 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
637 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
641 subtest 'get_routing_lists' => sub {
644 my $biblio = Koha::Biblio->new()->store();
645 my $subscription = Koha::Subscription->new({
646 biblionumber => $biblio->biblionumber,
650 my $patron = $builder->build( { source => 'Borrower' } );
651 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
653 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
655 my $routinglist_count = Koha::Subscription::Routinglists->count;
656 my $routinglist = Koha::Subscription::Routinglist->new({
657 borrowernumber => $patron->borrowernumber,
659 subscriptionid => $subscription->subscriptionid
662 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
664 my $routinglists = $patron->get_routing_lists;
665 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
666 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
668 my $subscription2 = Koha::Subscription->new({
669 biblionumber => $biblio->biblionumber,
672 my $routinglist2 = Koha::Subscription::Routinglist->new({
673 borrowernumber => $patron->borrowernumber,
675 subscriptionid => $subscription2->subscriptionid
678 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
680 $patron->delete; # Clean up for later tests
684 subtest 'get_age' => sub {
687 my $patron = $builder->build( { source => 'Borrower' } );
688 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
692 today => '2020-02-28',
693 has_12 => { date => '2007-08-27', expected_age => 12 },
694 almost_18 => { date => '2002-03-01', expected_age => 17 },
695 has_18_today => { date => '2002-02-28', expected_age => 18 },
696 had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
697 almost_16 => { date => '2004-02-29', expected_age => 15 },
698 has_16_today => { date => '2004-02-28', expected_age => 16 },
699 had_16_yesterday => { date => '2004-02-27', expected_age => 16 },
700 new_born => { date => '2020-01-27', expected_age => 0 },
703 today => '2020-02-29',
704 has_12 => { date => '2007-08-27', expected_age => 12 },
705 almost_18 => { date => '2002-03-01', expected_age => 17 },
706 has_18_today => { date => '2002-02-28', expected_age => 18 },
707 had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
708 almost_16 => { date => '2004-03-01', expected_age => 15 },
709 has_16_today => { date => '2004-02-29', expected_age => 16 },
710 had_16_yesterday => { date => '2004-02-28', expected_age => 16 },
711 new_born => { date => '2020-01-27', expected_age => 0 },
714 today => '2020-03-01',
715 has_12 => { date => '2007-08-27', expected_age => 12 },
716 almost_18 => { date => '2002-03-02', expected_age => 17 },
717 has_18_today => { date => '2002-03-01', expected_age => 18 },
718 had_18_yesterday => { date => '2002-02-28', expected_age => 18 },
719 almost_16 => { date => '2004-03-02', expected_age => 15 },
720 has_16_today => { date => '2004-03-01', expected_age => 16 },
721 had_16_yesterday => { date => '2004-02-29', expected_age => 16 },
724 today => '2019-01-31',
725 has_12 => { date => '2006-08-27', expected_age => 12 },
726 almost_18 => { date => '2001-02-01', expected_age => 17 },
727 has_18_today => { date => '2001-01-31', expected_age => 18 },
728 had_18_yesterday => { date => '2001-01-30', expected_age => 18 },
729 almost_16 => { date => '2003-02-01', expected_age => 15 },
730 has_16_today => { date => '2003-01-31', expected_age => 16 },
731 had_16_yesterday => { date => '2003-01-30', expected_age => 16 },
735 $patron->dateofbirth( undef );
736 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
738 for my $date ( @dates ) {
740 my $dt = dt_from_string($date->{today});
742 Time::Fake->offset( $dt->epoch );
744 for my $k ( keys %$date ) {
745 next if $k eq 'today';
747 my $dob = $date->{$k};
748 $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
751 $dob->{expected_age},
753 "Today=%s, dob=%s, should be %d",
754 $date->{today}, $dob->{date}, $dob->{expected_age}
766 subtest 'is_valid_age' => sub {
769 my $dt = dt_from_string('2020-02-28');
771 Time::Fake->offset( $dt->epoch );
773 my $category = $builder->build({
774 source => 'Category',
776 categorycode => 'AGE_5_10',
777 dateofbirthrequired => 5,
781 $category = Koha::Patron::Categories->find( $category->{categorycode} );
783 my $patron = $builder->build({
784 source => 'Borrower',
786 categorycode => $category->categorycode
789 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
792 $patron->dateofbirth( undef );
793 is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
797 today => '2020-02-28',
799 { date => '2007-08-27', expected_age => 12, valid => 0 },
801 { date => '2016-08-27', expected_age => 3, valid => 0 },
803 { date => '2013-02-28', expected_age => 7, valid => 1 },
805 { date => '2015-02-28', expected_age => 5, valid => 1 },
807 { date => '2015-03-01', expected_age => 4, valid => 0 },
809 { date => '2015-02-27', expected_age => 5, valid => 1 },
811 { date => '2009-02-28', expected_age => 11, valid => 0 },
813 { date => '2009-03-01', expected_age => 10, valid => 1 },
815 { date => '2009-02-27', expected_age => 11, valid => 0 },
819 for my $date ( @dates ) {
821 my $dt = dt_from_string($date->{today});
823 Time::Fake->offset( $dt->epoch );
825 for my $k ( sort keys %$date ) {
826 next if $k eq 'today';
828 my $dob = $date->{$k};
829 $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
831 $patron->is_valid_age,
834 "Today=%s, dob=%s, is %s, should be valid=%s in category %s",
835 $date->{today}, $dob->{date}, $dob->{expected_age}, $dob->{valid}, $category->categorycode
848 subtest 'account' => sub {
851 my $patron = $builder->build({source => 'Borrower'});
853 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
854 my $account = $patron->account;
855 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
860 subtest 'search_upcoming_membership_expires' => sub {
863 my $expiry_days = 15;
864 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
865 my $nb_of_days_before = 1;
866 my $nb_of_days_after = 2;
868 my $builder = t::lib::TestBuilder->new();
870 my $library = $builder->build({ source => 'Branch' });
872 # before we add borrowers to this branch, add the expires we have now
873 # note that this pertains to the current mocked setting of the pref
874 # for this reason we add the new branchcode to most of the tests
875 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
877 my $patron_1 = $builder->build({
878 source => 'Borrower',
880 branchcode => $library->{branchcode},
881 dateexpiry => dt_from_string->add( days => $expiry_days )
885 my $patron_2 = $builder->build({
886 source => 'Borrower',
888 branchcode => $library->{branchcode},
889 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
893 my $patron_3 = $builder->build({
894 source => 'Borrower',
896 branchcode => $library->{branchcode},
897 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
901 # Test without extra parameters
902 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
903 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
906 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
907 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
908 my $expired = $upcoming_mem_expires->next;
909 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
910 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
911 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
913 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
914 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
915 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
917 # Test MembershipExpiryDaysNotice == undef
918 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
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 without MembershipExpiryDaysNotice should not return new records.' );
922 # Test the before parameter
923 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
924 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
925 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
926 # Test after parameter also
927 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
928 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
929 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
932 subtest 'holds and old_holds' => sub {
935 my $library = $builder->build( { source => 'Branch' } );
936 my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
937 my $item_1 = $builder->build_sample_item(
939 library => $library->{branchcode},
940 biblionumber => $biblionumber_1,
943 my $item_2 = $builder->build_sample_item(
945 library => $library->{branchcode},
946 biblionumber => $biblionumber_1,
949 my $biblionumber_2 = $builder->build_sample_biblio->biblionumber;
950 my $item_3 = $builder->build_sample_item(
952 library => $library->{branchcode},
953 biblionumber => $biblionumber_2,
957 my $patron = $builder->build(
959 source => 'Borrower',
960 value => { branchcode => $library->{branchcode} }
964 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
965 my $holds = $patron->holds;
966 is( ref($holds), 'Koha::Holds',
967 'Koha::Patron->holds should return a Koha::Holds objects' );
968 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
970 C4::Reserves::AddReserve(
972 branchcode => $library->{branchcode},
973 borrowernumber => $patron->borrowernumber,
974 biblionumber => $biblionumber_1
978 C4::Reserves::AddReserve(
980 branchcode => $library->{branchcode},
981 borrowernumber => $patron->borrowernumber,
982 biblionumber => $biblionumber_2,
983 expiration_date => dt_from_string->add( days => 2 )
987 $holds = $patron->holds;
988 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
990 my $old_holds = $patron->old_holds;
991 is( ref($old_holds), 'Koha::Old::Holds',
992 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
993 is( $old_holds->count, 0, 'There should not be any old holds yet');
995 my $hold = $holds->next;
998 $old_holds = $patron->old_holds;
999 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
1006 subtest 'notice_email_address' => sub {
1009 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1011 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
1012 is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
1014 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
1015 is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
1020 subtest 'search_patrons_to_anonymise' => sub {
1024 # TODO create a subroutine in t::lib::Mocks
1025 my $branch = $builder->build({ source => 'Branch' });
1026 my $userenv_patron = $builder->build_object({
1027 class => 'Koha::Patrons',
1028 value => { branchcode => $branch->{branchcode}, flags => 0 },
1030 t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
1032 my $anonymous = $builder->build( { source => 'Borrower', }, );
1034 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
1036 subtest 'Anonymous Patron should be undeleteable' => sub {
1039 my $anonymous_patron = Koha::Patrons->find( $anonymous->{borrowernumber} );
1040 throws_ok { $anonymous_patron->delete(); }
1041 'Koha::Exceptions::Patron::FailedDeleteAnonymousPatron',
1042 'Attempt to delete anonymous patron throws exception.';
1043 $anonymous_patron = Koha::Patrons->find( $anonymous->{borrowernumber} );
1044 is( $anonymous_patron->id, $anonymous->{borrowernumber}, "Anonymous Patron was not deleted" );
1047 subtest 'patron privacy is 1 (default)' => sub {
1050 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1051 my $patron = $builder->build(
1052 { source => 'Borrower',
1053 value => { privacy => 1, }
1056 my $item_1 = $builder->build_sample_item;
1057 my $issue_1 = $builder->build(
1058 { source => 'Issue',
1060 borrowernumber => $patron->{borrowernumber},
1061 itemnumber => $item_1->itemnumber,
1065 my $item_2 = $builder->build_sample_item;
1066 my $issue_2 = $builder->build(
1067 { source => 'Issue',
1069 borrowernumber => $patron->{borrowernumber},
1070 itemnumber => $item_2->itemnumber,
1075 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->barcode, undef, undef, dt_from_string('2010-10-10') );
1076 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->barcode, undef, undef, dt_from_string('2011-11-11') );
1077 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
1079 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
1080 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
1082 my $rows_affected = Koha::Old::Checkouts->search(
1085 Koha::Patrons->search_patrons_to_anonymise(
1086 { before => '2011-11-12' }
1087 )->get_column('borrowernumber')
1089 returndate => { '<' => '2011-10-11', }
1092 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1094 $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1095 is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
1097 my $dbh = C4::Context->dbh;
1098 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
1099 $sth->execute($item_1->itemnumber);
1100 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1101 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
1102 $sth->execute($item_2->itemnumber);
1103 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1104 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
1106 $rows_affected = Koha::Old::Checkouts->search(
1109 Koha::Patrons->search_patrons_to_anonymise(
1110 { before => '2011-11-12' }
1111 )->get_column('borrowernumber')
1113 returndate => { '<' => '2011-11-12', }
1116 $sth->execute($item_2->itemnumber);
1117 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1118 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
1120 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
1121 $sth_reset->execute( $patron->{borrowernumber}, $item_1->itemnumber );
1122 $sth_reset->execute( $patron->{borrowernumber}, $item_2->itemnumber );
1123 $rows_affected = Koha::Old::Checkouts->search(
1126 Koha::Patrons->search_patrons_to_anonymise->get_column(
1131 $sth->execute($item_1->itemnumber);
1132 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1133 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
1134 $sth->execute($item_2->itemnumber);
1135 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1136 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
1138 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1141 subtest 'patron privacy is 0 (forever)' => sub {
1144 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1145 my $patron = $builder->build(
1146 { source => 'Borrower',
1147 value => { privacy => 0, }
1150 my $item = $builder->build_sample_item;
1151 my $issue = $builder->build(
1152 { source => 'Issue',
1154 borrowernumber => $patron->{borrowernumber},
1155 itemnumber => $item->itemnumber,
1160 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1161 is( $returned, 1, 'The item should have been returned' );
1163 my $dbh = C4::Context->dbh;
1164 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1165 SELECT borrowernumber FROM old_issues where itemnumber = ?
1166 |, undef, $item->itemnumber);
1167 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1168 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1171 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1173 subtest 'AnonymousPatron is not defined' => sub {
1177 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1178 my $patron = $builder->build(
1179 { source => 'Borrower',
1180 value => { privacy => 1, }
1183 my $item = $builder->build_sample_item;
1184 my $issue = $builder->build(
1185 { source => 'Issue',
1187 borrowernumber => $patron->{borrowernumber},
1188 itemnumber => $item->itemnumber,
1193 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1194 is( $returned, 1, 'The item should have been returned' );
1195 my $patrons_to_anonymize = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1196 ok( $patrons_to_anonymize->count > 0, 'search_patrons_to_anonymize' );
1198 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1201 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1203 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1204 my $patron = $builder->build(
1205 { source => 'Borrower',
1206 value => { privacy => 1 } # Another branchcode than the logged in librarian
1209 my $item = $builder->build_sample_item;
1210 my $issue = $builder->build(
1211 { source => 'Issue',
1213 borrowernumber => $patron->{borrowernumber},
1214 itemnumber => $item->itemnumber,
1219 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1220 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1221 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1224 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1225 $userenv_patron->delete;
1227 # Reset IndependentBranches for further tests
1228 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1231 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1239 $nb_of_patrons = Koha::Patrons->search->count;
1240 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1241 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1242 my $library_11 = $builder->build( { source => 'Branch' } );
1243 my $library_12 = $builder->build( { source => 'Branch' } );
1244 my $library_21 = $builder->build( { source => 'Branch' } );
1245 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1246 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1247 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1248 Koha::Library::Group->new(
1249 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1250 Koha::Library::Group->new(
1251 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1252 Koha::Library::Group->new(
1253 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1255 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1256 # 2 patrons from library_11 (group1)
1257 # patron_11_1 see patron's infos from outside its group
1258 # Setting flags => undef to not be considered as superlibrarian
1259 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1260 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1261 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1262 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1263 # patron_11_2 can only see patron's info from its group
1264 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1265 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1266 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1267 # 1 patron from library_12 (group1)
1268 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1269 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1270 # 1 patron from library_21 (group2) can only see patron's info from its group
1271 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1272 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1273 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1275 # Pfiou, we can start now!
1276 subtest 'libraries_where_can_see_patrons' => sub {
1281 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1282 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1283 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1285 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1286 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1287 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| );
1289 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1290 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1291 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| );
1293 subtest 'can_see_patron_infos' => sub {
1296 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1297 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1298 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1299 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1301 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1302 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1303 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1304 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1306 subtest 'search_limited' => sub {
1309 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1310 my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1311 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1312 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1314 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1315 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1316 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' );
1318 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1319 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1320 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1322 $patron_11_1->delete;
1323 $patron_11_2->delete;
1328 subtest 'account_locked' => sub {
1330 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1331 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1332 for my $value ( undef, '', 0 ) {
1333 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1334 $patron->login_attempts(0)->store;
1335 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1336 $patron->login_attempts(1)->store;
1337 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1338 $patron->login_attempts(-1)->store;
1339 is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1342 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1343 $patron->login_attempts(2)->store;
1344 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1345 $patron->login_attempts(3)->store;
1346 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1347 $patron->login_attempts(4)->store;
1348 is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1349 $patron->login_attempts(-1)->store;
1350 is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1355 subtest 'is_child | is_adult' => sub {
1357 my $category = $builder->build_object(
1359 class => 'Koha::Patron::Categories',
1360 value => { category_type => 'A' }
1363 my $patron_adult = $builder->build_object(
1365 class => 'Koha::Patrons',
1366 value => { categorycode => $category->categorycode }
1369 $category = $builder->build_object(
1371 class => 'Koha::Patron::Categories',
1372 value => { category_type => 'I' }
1375 my $patron_adult_i = $builder->build_object(
1377 class => 'Koha::Patrons',
1378 value => { categorycode => $category->categorycode }
1381 $category = $builder->build_object(
1383 class => 'Koha::Patron::Categories',
1384 value => { category_type => 'C' }
1387 my $patron_child = $builder->build_object(
1389 class => 'Koha::Patrons',
1390 value => { categorycode => $category->categorycode }
1393 $category = $builder->build_object(
1395 class => 'Koha::Patron::Categories',
1396 value => { category_type => 'O' }
1399 my $patron_other = $builder->build_object(
1401 class => 'Koha::Patrons',
1402 value => { categorycode => $category->categorycode }
1405 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1406 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1407 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1408 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1410 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1411 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1412 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1413 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1416 $patron_adult->delete;
1417 $patron_adult_i->delete;
1418 $patron_child->delete;
1419 $patron_other->delete;
1422 subtest 'overdues' => sub {
1425 my $library = $builder->build( { source => 'Branch' } );
1426 my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
1427 my $item_1 = $builder->build_sample_item(
1429 library => $library->{branchcode},
1430 biblionumber => $biblionumber_1,
1433 my $item_2 = $builder->build_sample_item(
1435 library => $library->{branchcode},
1436 biblionumber => $biblionumber_1,
1439 my $item_3 = $builder->build_sample_item(
1441 library => $library->{branchcode},
1445 my $patron = $builder->build(
1447 source => 'Borrower',
1448 value => { branchcode => $library->{branchcode} }
1452 t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1454 AddIssue( $patron, $item_1->barcode, DateTime->now->subtract( days => 1 ) );
1455 AddIssue( $patron, $item_2->barcode, DateTime->now->subtract( days => 5 ) );
1456 AddIssue( $patron, $item_3->barcode );
1458 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1459 my $overdues = $patron->overdues;
1460 is( $overdues->count, 2, 'Patron should have 2 overdues');
1461 is( $overdues->next->itemnumber, $item_1->itemnumber, 'The issue should be returned in the same order as they have been done, first is correct' );
1462 is( $overdues->next->itemnumber, $item_2->itemnumber, 'The issue should be returned in the same order as they have been done, second is correct' );
1464 my $o = $overdues->reset->next;
1465 my $unblessed_overdue = $o->unblessed_all_relateds;
1466 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1467 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1468 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1469 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1472 $patron->checkouts->delete;
1476 subtest 'userid_is_valid' => sub {
1479 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1480 my $patron_category = $builder->build_object(
1482 class => 'Koha::Patron::Categories',
1483 value => { category_type => 'P', enrolmentfee => 0 }
1487 cardnumber => "123456789",
1488 firstname => "Tomasito",
1490 categorycode => $patron_category->categorycode,
1491 branchcode => $library->branchcode,
1494 my $expected_userid_patron_1 = 'tomasito.none';
1495 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1496 my $patron_1 = Koha::Patrons->find($borrowernumber);
1497 is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1498 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1500 $patron_1->userid( 'tomasito.non' );
1501 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1502 1, 'recently created userid -> unique (borrowernumber passed)' );
1504 $patron_1->userid( 'tomasitoxxx' );
1505 is( $patron_1->has_valid_userid,
1506 1, 'non-existent userid -> unique (borrowernumber passed)' );
1507 $patron_1->discard_changes; # We compare with the original userid later
1509 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1510 is( $patron_not_in_storage->has_valid_userid,
1511 0, 'userid exists for another patron, patron is not in storage yet' );
1513 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1514 is( $patron_not_in_storage->has_valid_userid,
1515 1, 'non-existent userid, patron is not in storage yet' );
1517 # Regression tests for BZ12226
1518 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1519 is( $db_patron->has_valid_userid,
1520 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1522 # Add a new borrower with the same userid but different cardnumber
1523 $data{cardnumber} = "987654321";
1524 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1525 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1526 $patron_2->userid($patron_1->userid);
1527 is( $patron_2->has_valid_userid,
1528 0, 'The userid is already in used, it cannot be used for another patron' );
1530 my $new_userid = 'a_user_id';
1531 $data{cardnumber} = "234567890";
1532 $data{userid} = 'a_user_id';
1533 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1534 my $patron_3 = Koha::Patrons->find($borrowernumber);
1535 is( $patron_3->userid, $new_userid,
1536 'Koha::Patron->store should insert the given userid' );
1544 subtest 'generate_userid' => sub {
1547 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1548 my $patron_category = $builder->build_object(
1550 class => 'Koha::Patron::Categories',
1551 value => { category_type => 'P', enrolmentfee => 0 }
1555 cardnumber => "123456789",
1556 firstname => "Tômà sÃtó",
1557 surname => "Ñoné",
1558 categorycode => $patron_category->categorycode,
1559 branchcode => $library->branchcode,
1562 my $expected_userid_patron_1 = 'tomasito.none';
1563 my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1564 $new_patron->generate_userid;
1565 my $userid = $new_patron->userid;
1566 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1567 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1568 my $patron_1 = Koha::Patrons->find($borrowernumber);
1569 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1571 $new_patron->generate_userid;
1572 $userid = $new_patron->userid;
1573 is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1574 $data{cardnumber} = '987654321';
1575 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1576 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1577 isnt( $patron_2->userid, 'tomasito',
1578 "Patron with duplicate userid has new userid generated" );
1579 is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1580 "Patron with duplicate userid has new userid generated (1 is appened" );
1582 $new_patron->generate_userid;
1583 $userid = $new_patron->userid;
1584 is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1586 $patron_1 = Koha::Patrons->find($borrowernumber);
1587 $patron_1->userid(undef);
1588 $patron_1->generate_userid;
1589 $userid = $patron_1->userid;
1590 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1597 $nb_of_patrons = Koha::Patrons->search->count;
1598 $retrieved_patron_1->delete;
1599 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1601 subtest 'BorrowersLog tests' => sub {
1604 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1605 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1607 my $cardnumber = $patron->cardnumber;
1608 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1611 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1612 my $log_info = from_json( $logs[0]->info );
1613 is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1614 is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1615 is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1617 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1618 $patron->track_login();
1619 @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1620 is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1623 $schema->storage->txn_rollback;
1625 subtest 'Test Koha::Patrons::merge' => sub {
1628 my $schema = Koha::Database->new()->schema();
1630 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1632 $schema->storage->txn_begin;
1634 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1635 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1636 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1638 my $anonymous_patron_orig = C4::Context->preference('AnonymousPatron');
1639 my $anonymous_patron = $builder->build({ source => 'Borrower' })->{borrowernumber};
1640 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron );
1642 while (my ($r, $field) = each(%$resultsets)) {
1643 $builder->build({ source => $r, value => { $field => $keeper->id } });
1644 $builder->build({ source => $r, value => { $field => $loser_1 } });
1645 $builder->build({ source => $r, value => { $field => $loser_2 } });
1648 $schema->resultset($r)->search( { $field => $keeper->id } );
1649 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1652 $schema->resultset($r)->search( { $field => $loser_1 } );
1653 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1656 $schema->resultset($r)->search( { $field => $loser_2 } );
1657 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1660 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1662 while (my ($r, $field) = each(%$resultsets)) {
1664 $schema->resultset($r)->search( {$field => $keeper->id } );
1665 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1668 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1669 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1670 is( ref Koha::Patrons->find($anonymous_patron), 'Koha::Patron', 'Anonymous Patron was not deleted' );
1672 $anonymous_patron = Koha::Patrons->find($anonymous_patron);
1673 $results = $anonymous_patron->merge_with( [ $keeper->id ] );
1674 is( $results, undef, "Anonymous patron cannot have other patrons merged into it" );
1675 is( Koha::Patrons->search( { borrowernumber => $keeper->id } )->count, 1, "Patron from attempted merge with AnonymousPatron still exists" );
1677 subtest 'extended attributes' => sub {
1681 $builder->build_object( { class => 'Koha::Patrons' } );
1683 $builder->build_object( { class => 'Koha::Patrons' } );
1685 my $attribute_type_normal_1 = $builder->build_object(
1687 class => 'Koha::Patron::Attribute::Types',
1688 value => { repeatable => 0, unique_id => 0 }
1691 my $attribute_type_normal_2 = $builder->build_object(
1693 class => 'Koha::Patron::Attribute::Types',
1694 value => { repeatable => 0, unique_id => 0 }
1698 my $attribute_type_repeatable = $builder->build_object(
1700 class => 'Koha::Patron::Attribute::Types',
1701 value => { repeatable => 1, unique_id => 0 }
1707 code => $attribute_type_normal_1->code,
1708 attribute => 'from attr 1'
1711 code => $attribute_type_repeatable->code,
1712 attribute => 'from attr repeatable'
1718 code => $attribute_type_normal_2->code,
1719 attribute => 'to attr 2'
1722 code => $attribute_type_repeatable->code,
1723 attribute => 'to attr repeatable'
1727 $keep_patron->extended_attributes($attr_keep);
1728 $merge_patron->extended_attributes($attr_merge);
1730 $keep_patron->merge_with( [ $merge_patron->borrowernumber ] );
1731 my $merged_attributes = $keep_patron->extended_attributes;
1732 is( $merged_attributes->count, 4 );
1734 sub compare_attributes {
1735 my ( $got, $expected, $code ) = @_;
1739 sort $got->search( { code => $code } )
1740 ->get_column('attribute')
1748 $attribute_type_normal_1->code
1753 $attribute_type_normal_2->code
1757 [ 'from attr repeatable', 'to attr repeatable' ],
1758 $attribute_type_repeatable->code
1762 $keep_patron->delete;
1763 $merge_patron->delete;
1765 # Recreate but don't expect an exception if 2 non-repeatable attributes exist, pick the one from the patron we keep
1767 $builder->build_object( { class => 'Koha::Patrons' } );
1769 $builder->build_object( { class => 'Koha::Patrons' } );
1771 $keep_patron->extended_attributes($attr_keep);
1772 $merge_patron->extended_attributes(
1776 code => $attribute_type_normal_1->code,
1777 attribute => 'yet another attribute for non-repeatable'
1782 $keep_patron->merge_with( [ $merge_patron->borrowernumber ] );
1783 $merged_attributes = $keep_patron->extended_attributes;
1784 is( $merged_attributes->count, 4 );
1788 $attribute_type_normal_1->code
1793 $attribute_type_normal_2->code
1797 [ 'from attr repeatable', 'to attr repeatable' ],
1798 $attribute_type_repeatable->code
1803 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1804 $schema->storage->txn_rollback;
1807 subtest '->store' => sub {
1809 my $schema = Koha::Database->new->schema;
1810 $schema->storage->txn_begin;
1812 my $print_error = $schema->storage->dbh->{PrintError};
1813 $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1815 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1816 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1820 open STDERR, '>', '/dev/null';
1821 throws_ok { $patron_2->userid( $patron_1->userid )->store; }
1822 'Koha::Exceptions::Object::DuplicateID',
1823 'Koha::Patron->store raises an exception on duplicate ID';
1828 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1829 my $password = 'password';
1830 $patron_1->set_password({ password => $password });
1831 like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1832 my $digest = $patron_1->password;
1833 $patron_1->surname('xxx')->store;
1834 is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1836 # Test uppercasesurnames
1837 t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 );
1838 my $surname = lc $patron_1->surname;
1839 $patron_1->surname($surname)->store;
1840 isnt( $patron_1->surname, $surname,
1841 'Surname converts to uppercase on store.');
1842 t::lib::Mocks::mock_preference( 'uppercasesurnames', 0 );
1843 $patron_1->surname($surname)->store;
1844 is( $patron_1->surname, $surname,
1845 'Surname remains unchanged on store.');
1848 $patron_1->relationship("")->store;
1849 is( $patron_1->relationship, undef, );
1851 $schema->storage->dbh->{PrintError} = $print_error;
1852 $schema->storage->txn_rollback;
1854 subtest 'skip updated_on for BorrowersLog' => sub {
1856 $schema->storage->txn_begin;
1857 t::lib::Mocks::mock_preference('BorrowersLog', 1);
1858 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1859 $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1860 my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1861 is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1862 $schema->storage->txn_rollback;
1866 subtest '->set_password' => sub {
1870 $schema->storage->txn_begin;
1872 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1874 # Disable logging password changes for this tests
1875 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1877 # Password-length tests
1878 t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1879 throws_ok { $patron->set_password({ password => 'ab' }); }
1880 'Koha::Exceptions::Password::TooShort',
1881 'minPasswordLength is undef, fall back to 3, fail test';
1883 'Password length (2) is shorter than required (3)',
1884 'Exception parameters passed correctly'
1887 t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1888 throws_ok { $patron->set_password({ password => 'ab' }); }
1889 'Koha::Exceptions::Password::TooShort',
1890 'minPasswordLength is 2, fall back to 3, fail test';
1892 t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1893 throws_ok { $patron->set_password({ password => 'abcb' }); }
1894 'Koha::Exceptions::Password::TooShort',
1895 'minPasswordLength is 5, fail test';
1897 # Trailing spaces tests
1898 throws_ok { $patron->set_password({ password => 'abcD12d ' }); }
1899 'Koha::Exceptions::Password::WhitespaceCharacters',
1900 'Password contains trailing spaces, exception is thrown';
1902 # Require strong password tests
1903 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1904 throws_ok { $patron->set_password({ password => 'abcd a' }); }
1905 'Koha::Exceptions::Password::TooWeak',
1906 'Password is too weak, exception is thrown';
1908 # Refresh patron from DB, just to make sure
1909 $patron->discard_changes;
1910 is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1912 $patron->set_password({ password => 'abcD12 34' });
1913 $patron->discard_changes;
1915 is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1917 lives_ok { $patron->set_password({ password => 'abcd a', skip_validation => 1 }) }
1918 'Password is weak, but skip_validation was passed, so no exception thrown';
1921 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1922 $patron->login_attempts(3)->store;
1923 my $old_digest = $patron->password;
1924 $patron->set_password({ password => 'abcd a' });
1925 $patron->discard_changes;
1927 isnt( $patron->password, $old_digest, 'Password has been updated' );
1928 ok( checkpw_hash('abcd a', $patron->password), 'Password hash is correct' );
1929 is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1931 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1932 is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1934 # Enable logging password changes
1935 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1936 $patron->set_password({ password => 'abcd b' });
1938 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1939 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1941 $schema->storage->txn_rollback;
1944 $schema->storage->txn_begin;
1945 subtest 'filter_by_expiration_date' => sub {
1947 my $count1 = Koha::Patrons->filter_by_expiration_date({ days => 28 })->count;
1948 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1949 $patron1->dateexpiry( dt_from_string->subtract(days => 27) )->store;
1950 is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1, 'No more expired' );
1951 $patron1->dateexpiry( dt_from_string->subtract(days => 28) )->store;
1952 is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1 + 1, 'One more expired' );
1953 $patron1->dateexpiry( dt_from_string->subtract(days => 29) )->store;
1954 is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1 + 1, 'Same number again' );
1957 subtest 'search_unsubscribed' => sub {
1960 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1961 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
1962 is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
1964 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1965 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1967 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
1968 Koha::Patron::Consents->delete; # for correct counts
1969 Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string })->store;
1970 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
1972 # Add another refusal but shift the period
1973 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
1974 Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string->subtract(days=>2) })->store;
1975 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
1977 # Try another (special) attempts setting
1978 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
1979 # Lockout is now disabled
1980 # Patron2 still matches: refused earlier, not locked
1981 is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
1984 subtest 'search_anonymize_candidates' => sub {
1986 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1987 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1988 $patron1->anonymized(0);
1989 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1990 $patron2->anonymized(0);
1991 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1993 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
1994 is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
1996 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
1997 my $cnt = Koha::Patrons->search_anonymize_candidates->count;
1998 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1999 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2000 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
2002 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
2003 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
2004 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
2005 $cnt = Koha::Patrons->search_anonymize_candidates->count;
2006 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2007 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2008 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
2010 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
2011 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
2012 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
2013 $cnt = Koha::Patrons->search_anonymize_candidates->count;
2014 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2015 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2016 is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
2018 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
2019 $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
2020 $patron1->login_attempts(0)->store;
2021 $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
2022 $patron2->login_attempts(0)->store;
2023 $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
2024 $patron1->login_attempts(3)->store;
2025 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2026 $cnt+1, 'Locked flag' );
2028 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
2029 # Patron 1 still on 3 == locked
2030 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2031 $cnt+1, 'Still expect same number for FailedLoginAttempts empty' );
2032 $patron1->login_attempts(0)->store;
2034 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2035 $cnt, 'Patron 1 unlocked' );
2038 subtest 'search_anonymized' => sub {
2040 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2042 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
2043 is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
2045 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
2046 $patron1->dateexpiry( dt_from_string );
2047 $patron1->anonymized(0)->store;
2048 my $cnt = Koha::Patrons->search_anonymized->count;
2049 $patron1->anonymized(1)->store;
2050 is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
2051 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2052 is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
2055 subtest 'lock' => sub {
2058 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2059 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
2060 my $hold = $builder->build_object({
2061 class => 'Koha::Holds',
2062 value => { borrowernumber => $patron1->borrowernumber },
2065 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
2066 my $expiry = dt_from_string->add(days => 1);
2067 $patron1->dateexpiry( $expiry );
2069 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
2070 is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
2071 is( $patron1->holds->count, 1, 'No holds removed' );
2073 $patron1->lock({ expire => 1, remove => 1});
2074 isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
2075 is( $patron1->holds->count, 0, 'Holds removed' );
2077 # Disable lockout feature
2078 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
2079 $patron1->login_attempts(0);
2080 $patron1->dateexpiry( $expiry );
2083 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
2085 # Trivial wrapper test (Koha::Patrons->lock)
2086 $patron1->login_attempts(0)->store;
2087 Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
2088 $patron1->discard_changes; # refresh
2089 $patron2->discard_changes;
2090 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
2091 is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
2094 subtest 'anonymize' => sub {
2097 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2098 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
2100 # First try patron with issues
2101 my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
2102 warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
2105 t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
2106 my $surname = $patron1->surname; # expect change, no clear
2107 my $branchcode = $patron1->branchcode; # expect skip
2108 $patron1->anonymize;
2109 is($patron1->anonymized, 1, 'Check flag' );
2111 is( $patron1->dateofbirth, undef, 'Birth date cleared' );
2112 is( $patron1->firstname, undef, 'First name cleared' );
2113 isnt( $patron1->surname, $surname, 'Surname changed' );
2114 ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
2115 is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
2116 is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
2118 # Test wrapper in Koha::Patrons
2119 $patron1->surname($surname)->store; # restore
2120 my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
2121 $patron1->discard_changes; # refresh
2122 isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
2123 $patron2->discard_changes; # refresh
2124 is( $patron2->firstname, undef, 'First name patron2 cleared' );
2127 subtest 'queue_notice' => sub {
2130 my $dbh = C4::Context->dbh;
2131 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'email' );
2132 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2133 my $branch = $builder->build_object( { class => 'Koha::Libraries' } );
2134 my $letter_e = $builder->build_object( {
2135 class => 'Koha::Notice::Templates',
2137 branchcode => $branch->branchcode,
2138 message_transport_type => 'email',
2142 my $letter_p = $builder->build_object( {
2143 class => 'Koha::Notice::Templates',
2145 code => $letter_e->code,
2146 module => $letter_e->module,
2147 branchcode => $branch->branchcode,
2148 message_transport_type => 'print',
2152 my $letter_s = $builder->build_object( {
2153 class => 'Koha::Notice::Templates',
2155 code => $letter_e->code,
2156 module => $letter_e->module,
2157 branchcode => $branch->branchcode,
2158 message_transport_type => 'sms',
2163 my $letter_params = {
2164 letter_code => $letter_e->code,
2165 branchcode => $letter_e->branchcode,
2166 module => $letter_e->module,
2167 borrowernumber => $patron->borrowernumber,
2169 borrowers => $patron->borrowernumber,
2172 my @mtts = ('email');
2174 is( $patron->queue_notice(), undef, "Nothing is done if no params passed");
2175 is( $patron->queue_notice({ letter_params => $letter_params }),undef, "Nothing done if only letter");
2177 $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2178 {sent => ['email'] }, "Email sent"
2180 $patron->email("")->store;
2182 $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2183 {sent => ['print'],fallback => ['email']}, "Email fallsback to print if no email"
2187 $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2188 {sent => ['print','sms'],fallback => ['email']}, "Email fallsback to print if no email, sms sent"
2190 $patron->smsalertnumber("")->store;
2191 my $counter = Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count;
2193 $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2194 {sent => ['print'],fallback => ['email','sms']}, "Email fallsback to print if no emai, sms fallsback to print if no sms, only one print sent"
2196 is( Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count, $counter+1,"Count of queued notices went up by one");
2198 # Enable notification for Hold_Filled - Things are hardcoded here but should work with default data
2199 $dbh->do(q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ?)|, undef, $patron->borrowernumber, 4 );
2200 my $borrower_message_preference_id = $dbh->last_insert_id(undef, undef, "borrower_message_preferences", undef);
2201 $dbh->do(q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, undef, $borrower_message_preference_id, 'email' );
2203 is( $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts, message_name => 'Hold_Filled' }),undef, "Nothing done if transports and name sent");
2205 $patron->email(q|awesome@ismymiddle.name|)->store;
2207 $patron->queue_notice({ letter_params => $letter_params, message_name => 'Hold_Filled' }),
2208 {sent => ['email'] }, "Email sent when using borrower preferences"
2210 $counter = Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count;
2212 $patron->queue_notice({ letter_params => $letter_params, message_name => 'Hold_Filled', test_mode => 1 }),
2213 {sent => ['email'] }, "Report that email sent when using borrower preferences in test_mode"
2215 is( Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count, $counter,"Count of queued notices not increased in test mode");
2218 subtest 'filter_by_amount_owed' => sub {
2221 my $library = $builder->build({source => 'Branch' });
2222 my $category = $builder->build({source => 'Category' });
2224 my $new_patron_cf_1 = Koha::Patron->new(
2226 cardnumber => 'test_cn_cf_1',
2227 branchcode => $library->{branchcode},
2228 categorycode => $category->{categorycode},
2229 surname => 'surname for patron1',
2230 firstname => 'firstname for patron1',
2231 userid => 'a_nonexistent_userid_cf_1',
2234 my $new_patron_cf_2 = Koha::Patron->new(
2236 cardnumber => 'test_cn_cf_2',
2237 branchcode => $library->{branchcode},
2238 categorycode => $category->{categorycode},
2239 surname => 'surname for patron2',
2240 firstname => 'firstname for patron2',
2241 userid => 'a_nonexistent_userid_cf_2',
2244 my $new_patron_cf_3 = Koha::Patron->new(
2246 cardnumber => 'test_cn_cf_3',
2247 branchcode => $library->{branchcode},
2248 categorycode => $category->{categorycode},
2249 surname => 'surname for patron3',
2250 firstname => 'firstname for patron3',
2251 userid => 'a_nonexistent_userid_cf_3',
2255 my $results = Koha::Patrons->search(
2257 'me.borrowernumber' => [
2258 $new_patron_cf_1->borrowernumber,
2259 $new_patron_cf_2->borrowernumber,
2260 $new_patron_cf_3->borrowernumber
2265 my $fine1 = $builder->build(
2267 source => 'Accountline',
2269 borrowernumber => $new_patron_cf_1->borrowernumber,
2270 amountoutstanding => 12.00,
2272 debit_type_code => 'OVERDUE',
2273 branchcode => $library->{branchcode}
2277 my $fine2 = $builder->build(
2279 source => 'Accountline',
2281 borrowernumber => $new_patron_cf_2->borrowernumber,
2282 amountoutstanding => 8.00,
2284 debit_type_code => 'OVERDUE',
2285 branchcode => $library->{branchcode}
2290 my $fine3 = $builder->build(
2292 source => 'Accountline',
2294 borrowernumber => $new_patron_cf_2->borrowernumber,
2295 amountoutstanding => 10.00,
2297 debit_type_code => 'OVERDUE',
2298 branchcode => $library->{branchcode}
2303 my $filtered = $results->filter_by_amount_owed();
2304 is( ref($filtered), 'Koha::Patrons',
2305 'Koha::Patrons->filter_by_amount_owed should return a Koha::Patrons result set in a scalar context'
2308 my $lower_limit = 12.00;
2309 my $upper_limit = 16.00;
2311 # Catch user with 1 x 12.00 fine and user with no fines.
2313 $results->filter_by_amount_owed( { less_than => $upper_limit } );
2314 is( $filtered->_resultset->as_subselect_rs->count, 2,
2315 "filter_by_amount_owed({ less_than => $upper_limit }) found two patrons"
2318 # Catch user with 1 x 8.00 and 1 x 10.00 fine
2320 $results->filter_by_amount_owed( { more_than => $lower_limit } );
2321 is( $filtered->_resultset->as_subselect_rs->count, 1,
2322 "filter_by_amount_owed({ more_than => $lower_limit }) found two patrons"
2325 # User with 2 fines falls above upper limit - Excluded,
2326 # user with 1 fine falls below lower limit - Excluded
2327 # and user with no fines falls below lower limit - Excluded.
2328 $filtered = $results->filter_by_amount_owed(
2329 { more_than => $lower_limit, less_than => $upper_limit } );
2330 is( $filtered->_resultset->as_subselect_rs->count, 0,
2331 "filter_by_amount_owed({ more_than => $lower_limit, less_than => $upper_limit }) found zero patrons"
2334 my $library2 = $builder->build({source => 'Branch' });
2335 my $fine4 = $builder->build(
2337 source => 'Accountline',
2339 borrowernumber => $new_patron_cf_2->borrowernumber,
2340 amountoutstanding => 10.00,
2342 debit_type_code => 'HOLD',
2343 branchcode => $library2->{branchcode}
2348 # Catch only the user with a HOLD fee over 6.00
2349 $filtered = $results->filter_by_amount_owed( { more_than => 6.00, debit_type => 'HOLD' } );
2350 is( $filtered->_resultset->as_subselect_rs->count, 1,
2351 "filter_by_amount_owed({ more_than => 6.00, debit_type => 'HOLD' }) found one patron"
2354 # Catch only the user with a fee over 6.00 at the specified library
2355 $filtered = $results->filter_by_amount_owed( { more_than => 6.00, library => $library2->{branchcode} } );
2356 is( $filtered->_resultset->as_subselect_rs->count, 1,
2357 "filter_by_amount_owed({ more_than => 6.00, library => $library2->{branchcode} }) found one patron"
2362 subtest 'filter_by_have_subpermission' => sub {
2365 $schema->storage->txn_begin;
2367 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2368 my $patron_1 = $builder->build_object(
2370 class => 'Koha::Patrons',
2371 value => { flags => 1, branchcode => $library->branchcode }
2375 my $patron_2 = $builder->build_object( # 4096 = 1 << 12 for suggestions
2377 class => 'Koha::Patrons',
2378 value => { flags => 4096, branchcode => $library->branchcode }
2382 my $patron_3 = $builder->build_object(
2384 class => 'Koha::Patrons',
2385 value => { flags => 0, branchcode => $library->branchcode }
2390 source => 'UserPermission',
2392 borrowernumber => $patron_3->borrowernumber,
2394 code => 'order_manage',
2401 Koha::Patrons->search( { branchcode => $library->branchcode } )
2402 ->filter_by_have_subpermission('suggestions.suggestions_manage')
2403 ->get_column('borrowernumber')
2405 [ $patron_1->borrowernumber, $patron_2->borrowernumber ],
2406 'Superlibrarian and patron with suggestions.suggestions_manage'
2411 Koha::Patrons->search( { branchcode => $library->branchcode } )
2412 ->filter_by_have_subpermission('acquisition.order_manage')
2413 ->get_column('borrowernumber')
2415 [ $patron_1->borrowernumber, $patron_3->borrowernumber ],
2416 'Superlibrarian and patron with acquisition.order_manage'
2421 Koha::Patrons->search( { branchcode => $library->branchcode } )
2422 ->filter_by_have_subpermission('parameters.manage_cities')
2423 ->get_column('borrowernumber')
2425 [ $patron_1->borrowernumber ],
2426 'Only Superlibrarian is returned'
2430 Koha::Patrons->search( { branchcode => $library->branchcode } )
2431 ->filter_by_have_subpermission('dont_exist.subperm');
2432 } 'Koha::Exceptions::ObjectNotFound';
2435 $schema->storage->txn_rollback;
2438 $schema->storage->txn_rollback;