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 => 43;
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::Virtualshelf;
46 use Koha::Virtualshelves;
47 use Koha::Notice::Messages;
49 use t::lib::TestBuilder;
52 my $schema = Koha::Database->new->schema;
53 $schema->storage->txn_begin;
55 my $builder = t::lib::TestBuilder->new;
56 my $library = $builder->build({source => 'Branch' });
57 my $category = $builder->build({source => 'Category' });
58 my $nb_of_patrons = Koha::Patrons->search->count;
59 my $new_patron_1 = Koha::Patron->new(
60 { cardnumber => 'test_cn_1',
61 branchcode => $library->{branchcode},
62 categorycode => $category->{categorycode},
63 surname => 'surname for patron1',
64 firstname => 'firstname for patron1',
65 userid => 'a_nonexistent_userid_1',
66 flags => 1, # Is superlibrarian
69 my $new_patron_2 = Koha::Patron->new(
70 { cardnumber => 'test_cn_2',
71 branchcode => $library->{branchcode},
72 categorycode => $category->{categorycode},
73 surname => 'surname for patron2',
74 firstname => 'firstname for patron2',
75 userid => 'a_nonexistent_userid_2',
79 t::lib::Mocks::mock_userenv({ patron => $new_patron_1 });
81 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
83 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
84 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
86 subtest 'library' => sub {
88 is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
89 is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
92 subtest 'sms_provider' => sub {
94 my $sms_provider = $builder->build({source => 'SmsProvider' });
95 is( $retrieved_patron_1->sms_provider, undef, '->sms_provider should return undef if none defined' );
96 $retrieved_patron_1->sms_provider_id( $sms_provider->{id} )->store;
97 is_deeply( $retrieved_patron_1->sms_provider->unblessed, $sms_provider, 'Koha::Patron->sms_provider returns the correct SMS provider' );
98 is( ref($retrieved_patron_1->sms_provider), 'Koha::SMS::Provider', 'Koha::Patron->sms_provider should return a Koha::SMS::Provider object' );
101 subtest 'guarantees' => sub {
105 t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test|test2' );
107 my $guarantees = $new_patron_1->guarantee_relationships;
108 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
109 is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee relationships' );
111 my $guarantee_1 = $builder->build({ source => 'Borrower' });
112 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
113 my $guarantee_2 = $builder->build({ source => 'Borrower' });
114 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
116 $guarantees = $new_patron_1->guarantee_relationships;
117 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantee_relationships should return a Koha::Patrons result set in a scalar context' );
118 is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
122 #Test return order of guarantees BZ 18635
123 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
124 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
126 my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
128 my $order_guarantee1 = $builder->build_object(
130 class => 'Koha::Patrons',
136 $builder->build_object(
138 class => 'Koha::Patron::Relationships',
140 guarantor_id => $guarantor->id,
141 guarantee_id => $order_guarantee1,
142 relationship => 'test',
147 my $order_guarantee2 = $builder->build_object(
149 class => 'Koha::Patrons',
155 $builder->build_object(
157 class => 'Koha::Patron::Relationships',
159 guarantor_id => $guarantor->id,
160 guarantee_id => $order_guarantee2,
161 relationship => 'test',
166 my $order_guarantee3 = $builder->build_object(
168 class => 'Koha::Patrons',
171 firstname => 'Walrus',
175 $builder->build_object(
177 class => 'Koha::Patron::Relationships',
179 guarantor_id => $guarantor->id,
180 guarantee_id => $order_guarantee3,
181 relationship => 'test',
186 my $order_guarantee4 = $builder->build_object(
188 class => 'Koha::Patrons',
191 firstname => 'Vulture',
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',
215 my $r = $builder->build_object(
217 class => 'Koha::Patron::Relationships',
219 guarantor_id => $guarantor->id,
220 guarantee_id => $order_guarantee5,
221 relationship => 'test',
226 $guarantees = $guarantor->guarantee_relationships->guarantees;
228 is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
229 is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
230 is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
231 is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
232 is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
235 subtest 'category' => sub {
237 my $patron_category = $new_patron_1->category;
238 is( ref( $patron_category), 'Koha::Patron::Category', );
239 is( $patron_category->categorycode, $category->{categorycode}, );
242 subtest 'siblings' => sub {
246 my $siblings = $new_patron_1->siblings;
247 is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
248 my $guarantee_1 = $builder->build( { source => 'Borrower' } );
249 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
250 my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
251 $siblings = $retrieved_guarantee_1->siblings;
252 is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
253 is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' );
254 my $guarantee_2 = $builder->build( { source => 'Borrower' } );
255 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
256 my $guarantee_3 = $builder->build( { source => 'Borrower' } );
257 my $relationship_3 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_3->{borrowernumber}, relationship => 'test' } )->store();
258 $siblings = $retrieved_guarantee_1->siblings;
259 is( $siblings->count, 2, 'guarantee_1 should have 2 siblings' );
260 is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
261 is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
262 $_->delete for $retrieved_guarantee_1->siblings;
263 $retrieved_guarantee_1->delete;
266 subtest 'has_overdues' => sub {
269 my $item_1 = $builder->build_sample_item;
270 my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
271 is( $retrieved_patron->has_overdues, 0, );
273 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
274 my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->itemnumber, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
275 is( $retrieved_patron->has_overdues, 0, );
277 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
278 $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->itemnumber, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
279 $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
280 is( $retrieved_patron->has_overdues, 1, );
284 subtest 'is_expired' => sub {
286 my $patron = $builder->build({ source => 'Borrower' });
287 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
288 $patron->dateexpiry( undef )->store->discard_changes;
289 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
290 $patron->dateexpiry( dt_from_string )->store->discard_changes;
291 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
292 $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
293 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
294 $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
295 is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
300 subtest 'is_going_to_expire' => sub {
303 my $today = dt_from_string(undef, undef, 'floating');
304 my $patron = $builder->build({ source => 'Borrower' });
305 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
306 $patron->dateexpiry( undef )->store->discard_changes;
307 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
309 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
310 $patron->dateexpiry( $today )->store->discard_changes;
311 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
313 $patron->dateexpiry( $today )->store->discard_changes;
314 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
316 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
317 $patron->dateexpiry( $today->clone->add( days => 11 ) )->store->discard_changes;
318 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');
320 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
321 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
322 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');
324 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
325 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
326 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');
329 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
330 $patron->dateexpiry( $today->clone->add( days => 20 ) )->store->discard_changes;
331 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');
333 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
334 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
335 is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
337 { # Testing invalid is going to expiry date
338 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 30);
339 # mock_config does not work here, because of tz vs timezone subroutines
340 my $context = Test::MockModule->new('C4::Context');
341 $context->mock( 'tz', sub {
344 $patron->dateexpiry(DateTime->new( year => 2019, month => 12, day => 3 ))->store;
345 eval { $patron->is_going_to_expire };
346 is( $@, '', 'On invalid "is going to expire" date, the method should not crash with "Invalid local time for date in time zone"');
347 $context->unmock('tz');
354 subtest 'renew_account' => sub {
357 for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
358 my $dt = dt_from_string( $date, 'iso' );
359 Time::Fake->offset( $dt->epoch );
360 my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
361 my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
362 my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
363 my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
364 my $a_year_later_plus_a_month = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
365 my $patron_category = $builder->build(
366 { source => 'Category',
368 enrolmentperiod => 12,
369 enrolmentperioddate => undef,
373 my $patron = $builder->build(
374 { source => 'Borrower',
376 dateexpiry => $a_month_ago,
377 categorycode => $patron_category->{categorycode},
378 date_renewed => undef, # Force builder to not populate the column for new patron
382 my $patron_2 = $builder->build(
383 { source => 'Borrower',
385 dateexpiry => $a_month_ago,
386 categorycode => $patron_category->{categorycode},
390 my $patron_3 = $builder->build(
391 { source => 'Borrower',
393 dateexpiry => $a_month_later,
394 categorycode => $patron_category->{categorycode},
398 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
399 my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
400 my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
402 is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
404 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
405 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
406 my $expiry_date = $retrieved_patron->renew_account;
407 is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
408 my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
409 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" );
410 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
411 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
413 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
414 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
415 $expiry_date = $retrieved_patron->renew_account;
416 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
417 $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
418 is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
419 $retrieved_expiry_date = $retrieved_patron->dateexpiry;
420 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
421 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
422 is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
424 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
425 $expiry_date = $retrieved_patron_2->renew_account;
426 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
427 $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
428 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
430 $expiry_date = $retrieved_patron_3->renew_account;
431 is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
432 $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
433 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" );
435 $retrieved_patron->delete;
436 $retrieved_patron_2->delete;
437 $retrieved_patron_3->delete;
442 subtest "move_to_deleted" => sub {
444 my $originally_updated_on = '2016-01-01 12:12:12';
445 my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
446 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
447 is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
448 ; # FIXME This should be Koha::Deleted::Patron
449 my $deleted_patron = $schema->resultset('Deletedborrower')
450 ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
452 ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
453 ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
454 isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
455 $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
456 is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
457 $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup
460 subtest "delete" => sub {
462 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
463 t::lib::Mocks::mock_preference( 'ListOwnershipUponPatronDeletion', 'transfer' );
464 t::lib::Mocks::mock_preference( 'ListOwnerDesignated', undef );
465 Koha::Virtualshelves->delete;
467 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
468 my $patron_for_sharing = $builder->build_object({ class => 'Koha::Patrons' });
469 my $staff_patron = $builder->build_object({ class => 'Koha::Patrons' });
470 t::lib::Mocks::mock_userenv({ patron => $staff_patron });
472 my $hold = $builder->build_object({ class => 'Koha::Holds', value => { borrowernumber => $patron->borrowernumber } });
473 my $modification = $builder->build_object({ class => 'Koha::Patron::Modifications', value => { borrowernumber => $patron->borrowernumber } });
474 my $private_list = Koha::Virtualshelf->new({
475 shelfname => "private",
476 owner => $patron->borrowernumber,
479 my $public_list = Koha::Virtualshelf->new({
480 shelfname => "public",
481 owner => $patron->borrowernumber,
484 my $list_to_share = Koha::Virtualshelf->new({
485 shelfname => "shared",
486 owner => $patron->borrowernumber,
490 $list_to_share->share("valid key")->accept( "valid key", $patron_for_sharing->borrowernumber );
491 $list_to_share->share("valid key")->accept( "valid key", $staff_patron->borrowernumber ); # this share should be removed at deletion too
492 my $deleted = $patron->delete;
493 is( ref($deleted), 'Koha::Patron', 'Koha::Patron->delete should return the deleted patron object if the patron has been correctly deleted' );
494 ok( $patron->borrowernumber, 'Still have the deleted borrowernumber' );
496 is( Koha::Patrons->find( $patron->borrowernumber ), undef, 'Koha::Patron->delete should have deleted the patron' );
498 is (Koha::Old::Holds->search({ reserve_id => $hold->reserve_id })->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| );
500 is( Koha::Holds->search( { borrowernumber => $patron->borrowernumber } )->count, 0, q|Koha::Patron->delete should have cancelled patron's holds 2| );
502 my $transferred_lists = Koha::Virtualshelves->search({ owner => $staff_patron->borrowernumber })->count;
503 is( $transferred_lists, 2, 'Public and shared lists should stay in database under a different owner with a unique name, while private lists delete, with ListOwnershipPatronDeletion set to Transfer');
504 is( Koha::Virtualshelfshares->search({ borrowernumber => $staff_patron->borrowernumber })->count, 0, "New owner of list should have shares removed" );
505 is( Koha::Virtualshelfshares->search({ borrowernumber => $patron_for_sharing->borrowernumber })->count, 1, "But the other share is still there" );
506 is( Koha::Virtualshelves->search({ owner => $patron->borrowernumber })->count, 0, q|Koha::Patron->delete should have deleted patron's lists/removed their ownership| );
508 is( Koha::Patron::Modifications->search( { borrowernumber => $patron->borrowernumber } )->count, 0, q|Koha::Patron->delete should have deleted patron's modifications| );
510 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $patron->borrowernumber } )->count;
511 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
513 # Test deletion with designated fallback owner
514 my $designated_owner = $builder->build_object({ class => 'Koha::Patrons' });
515 t::lib::Mocks::mock_preference( 'ListOwnerDesignated', $designated_owner->id );
516 $patron = $builder->build_object({ class => 'Koha::Patrons' });
517 $private_list = Koha::Virtualshelf->new({ shelfname => "PR1", owner => $patron->id })->store;
518 $public_list = Koha::Virtualshelf->new({ shelfname => "PU1", public => 1, owner => $patron->id })->store;
519 $list_to_share = Koha::Virtualshelf->new({ shelfname => "SH1", owner => $patron->id })->store;
520 $list_to_share->share("valid key")->accept( "valid key", $patron_for_sharing->id );
522 is( Koha::Virtualshelves->find( $private_list->id ), undef, 'Private list gone' );
523 is( $public_list->discard_changes->get_column('owner'), $designated_owner->id, 'Public list transferred' );
524 is( $list_to_share->discard_changes->get_column('owner'), $designated_owner->id, 'Shared list transferred' );
526 # Finally test deleting lists
527 t::lib::Mocks::mock_preference( 'ListOwnershipUponPatronDeletion', 'delete' );
528 Koha::Virtualshelves->delete;
529 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
530 my $private_list2 = Koha::Virtualshelf->new({
531 shelfname => "private",
532 owner => $patron2->borrowernumber,
535 my $public_list2 = Koha::Virtualshelf->new({
536 shelfname => "public",
537 owner => $patron2->borrowernumber,
540 my $list_to_share2 = Koha::Virtualshelf->new({
541 shelfname => "shared",
542 owner => $patron2->borrowernumber,
545 $list_to_share2->share("valid key")->accept( "valid key", $patron_for_sharing->borrowernumber );
547 # Delete patron2, check if shelves and shares are now empty
549 is( Koha::Virtualshelves->count, 0, 'All lists should be gone now' );
550 is( Koha::Virtualshelfshares->count, 0, 'All shares should be gone too' );
553 subtest 'Koha::Patrons->delete' => sub {
556 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
557 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
558 my $id1 = $patron1->borrowernumber;
559 my $set = Koha::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
560 is( $set->count, 2, 'Two patrons found as expected' );
561 is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
562 my $deleted_patrons = Koha::Old::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
563 is( $deleted_patrons->count, 2, 'Patrons moved to deletedborrowers' );
565 # See other tests in t/db_dependent/Koha/Objects.t
568 subtest 'add_enrolment_fee_if_needed' => sub {
571 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
572 foreach( keys %{$enrolmentfees} ) {
573 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
575 my $enrolmentfee_K = $enrolmentfees->{K};
576 my $enrolmentfee_J = $enrolmentfees->{J};
577 my $enrolmentfee_YA = $enrolmentfees->{YA};
579 my %borrower_data = (
580 firstname => 'my firstname',
581 surname => 'my surname',
583 branchcode => $library->{branchcode},
586 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
587 $borrower_data{borrowernumber} = $borrowernumber;
589 my $patron = Koha::Patrons->find( $borrowernumber );
590 my $total = $patron->account->balance;
591 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
593 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
594 $borrower_data{categorycode} = 'J';
595 $patron->set(\%borrower_data)->store;
596 $total = $patron->account->balance;
597 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
599 $borrower_data{categorycode} = 'K';
600 $patron->set(\%borrower_data)->store;
601 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
603 $borrower_data{categorycode} = 'J';
604 $patron->set(\%borrower_data)->store;
605 $total = $patron->account->balance;
606 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
608 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
609 $patron->categorycode('YA')->store;
610 $total = $patron->account->balance;
612 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
613 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
619 subtest 'checkouts + pending_checkouts + overdues + old_checkouts' => sub {
622 my $library = $builder->build( { source => 'Branch' } );
623 my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
624 my $item_1 = $builder->build_sample_item(
626 library => $library->{branchcode},
627 biblionumber => $biblionumber_1,
630 my $item_2 = $builder->build_sample_item(
632 library => $library->{branchcode},
633 biblionumber => $biblionumber_1,
636 my $biblionumber_2 = $builder->build_sample_biblio->biblionumber;
637 my $item_3 = $builder->build_sample_item(
639 library => $library->{branchcode},
640 biblionumber => $biblionumber_2,
643 my $patron = $builder->build(
645 source => 'Borrower',
646 value => { branchcode => $library->{branchcode} }
650 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
651 my $checkouts = $patron->checkouts;
652 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
653 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
654 my $pending_checkouts = $patron->pending_checkouts;
655 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
656 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
657 my $old_checkouts = $patron->old_checkouts;
658 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
659 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
661 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
663 AddIssue( $patron, $item_1->barcode, DateTime->now->subtract( days => 1 ) );
664 AddIssue( $patron, $item_2->barcode, DateTime->now->subtract( days => 5 ) );
665 AddIssue( $patron, $item_3->barcode );
667 $checkouts = $patron->checkouts;
668 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
669 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
670 $pending_checkouts = $patron->pending_checkouts;
671 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
672 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
674 my $first_checkout = $pending_checkouts->next;
675 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->biblionumber, 'pending_checkouts should prefetch values from other tables (here biblio)' );
677 my $overdues = $patron->overdues;
678 is( $overdues->count, 2, 'Patron should have 2 overdues');
679 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->overdues should return Koha::Checkouts' );
680 is( $overdues->next->itemnumber, $item_1->itemnumber, 'The issue should be returned in the same order as they have been done, first is correct' );
681 is( $overdues->next->itemnumber, $item_2->itemnumber, 'The issue should be returned in the same order as they have been done, second is correct' );
684 C4::Circulation::AddReturn( $item_1->barcode );
685 C4::Circulation::AddReturn( $item_2->barcode );
686 $old_checkouts = $patron->old_checkouts;
687 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
688 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
691 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
695 subtest 'get_routing_lists' => sub {
698 my $biblio = Koha::Biblio->new()->store();
699 my $subscription = Koha::Subscription->new({
700 biblionumber => $biblio->biblionumber,
704 my $patron = $builder->build( { source => 'Borrower' } );
705 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
707 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
709 my $routinglist_count = Koha::Subscription::Routinglists->count;
710 my $routinglist = Koha::Subscription::Routinglist->new({
711 borrowernumber => $patron->borrowernumber,
713 subscriptionid => $subscription->subscriptionid
716 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
718 my $routinglists = $patron->get_routing_lists;
719 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
720 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
722 my $subscription2 = Koha::Subscription->new({
723 biblionumber => $biblio->biblionumber,
726 my $routinglist2 = Koha::Subscription::Routinglist->new({
727 borrowernumber => $patron->borrowernumber,
729 subscriptionid => $subscription2->subscriptionid
732 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
734 $patron->delete; # Clean up for later tests
738 subtest 'get_age' => sub {
741 my $patron = $builder->build( { source => 'Borrower' } );
742 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
746 today => '2020-02-28',
747 has_12 => { date => '2007-08-27', expected_age => 12 },
748 almost_18 => { date => '2002-03-01', expected_age => 17 },
749 has_18_today => { date => '2002-02-28', expected_age => 18 },
750 had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
751 almost_16 => { date => '2004-02-29', expected_age => 15 },
752 has_16_today => { date => '2004-02-28', expected_age => 16 },
753 had_16_yesterday => { date => '2004-02-27', expected_age => 16 },
754 new_born => { date => '2020-01-27', expected_age => 0 },
757 today => '2020-02-29',
758 has_12 => { date => '2007-08-27', expected_age => 12 },
759 almost_18 => { date => '2002-03-01', expected_age => 17 },
760 has_18_today => { date => '2002-02-28', expected_age => 18 },
761 had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
762 almost_16 => { date => '2004-03-01', expected_age => 15 },
763 has_16_today => { date => '2004-02-29', expected_age => 16 },
764 had_16_yesterday => { date => '2004-02-28', expected_age => 16 },
765 new_born => { date => '2020-01-27', expected_age => 0 },
768 today => '2020-03-01',
769 has_12 => { date => '2007-08-27', expected_age => 12 },
770 almost_18 => { date => '2002-03-02', expected_age => 17 },
771 has_18_today => { date => '2002-03-01', expected_age => 18 },
772 had_18_yesterday => { date => '2002-02-28', expected_age => 18 },
773 almost_16 => { date => '2004-03-02', expected_age => 15 },
774 has_16_today => { date => '2004-03-01', expected_age => 16 },
775 had_16_yesterday => { date => '2004-02-29', expected_age => 16 },
778 today => '2019-01-31',
779 has_12 => { date => '2006-08-27', expected_age => 12 },
780 almost_18 => { date => '2001-02-01', expected_age => 17 },
781 has_18_today => { date => '2001-01-31', expected_age => 18 },
782 had_18_yesterday => { date => '2001-01-30', expected_age => 18 },
783 almost_16 => { date => '2003-02-01', expected_age => 15 },
784 has_16_today => { date => '2003-01-31', expected_age => 16 },
785 had_16_yesterday => { date => '2003-01-30', expected_age => 16 },
789 $patron->dateofbirth( undef );
790 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
792 for my $date ( @dates ) {
794 my $dt = dt_from_string($date->{today});
796 Time::Fake->offset( $dt->epoch );
798 for my $k ( keys %$date ) {
799 next if $k eq 'today';
801 my $dob = $date->{$k};
802 $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
805 $dob->{expected_age},
807 "Today=%s, dob=%s, should be %d",
808 $date->{today}, $dob->{date}, $dob->{expected_age}
820 subtest 'is_valid_age' => sub {
823 my $dt = dt_from_string('2020-02-28');
825 Time::Fake->offset( $dt->epoch );
827 my $category = $builder->build({
828 source => 'Category',
830 categorycode => 'AGE_5_10',
831 dateofbirthrequired => 5,
835 $category = Koha::Patron::Categories->find( $category->{categorycode} );
837 my $patron = $builder->build({
838 source => 'Borrower',
840 categorycode => $category->categorycode
843 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
846 $patron->dateofbirth( undef );
847 is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
851 today => '2020-02-28',
853 { date => '2007-08-27', expected_age => 12, valid => 0 },
855 { date => '2016-08-27', expected_age => 3, valid => 0 },
857 { date => '2013-02-28', expected_age => 7, valid => 1 },
859 { date => '2015-02-28', expected_age => 5, valid => 1 },
861 { date => '2015-03-01', expected_age => 4, valid => 0 },
863 { date => '2015-02-27', expected_age => 5, valid => 1 },
865 { date => '2009-02-28', expected_age => 11, valid => 0 },
867 { date => '2009-03-01', expected_age => 10, valid => 1 },
869 { date => '2009-02-27', expected_age => 11, valid => 0 },
873 for my $date ( @dates ) {
875 my $dt = dt_from_string($date->{today});
877 Time::Fake->offset( $dt->epoch );
879 for my $k ( sort keys %$date ) {
880 next if $k eq 'today';
882 my $dob = $date->{$k};
883 $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
885 $patron->is_valid_age,
888 "Today=%s, dob=%s, is %s, should be valid=%s in category %s",
889 $date->{today}, $dob->{date}, $dob->{expected_age}, $dob->{valid}, $category->categorycode
902 subtest 'account' => sub {
905 my $patron = $builder->build({source => 'Borrower'});
907 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
908 my $account = $patron->account;
909 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
914 subtest 'search_upcoming_membership_expires' => sub {
917 my $expiry_days = 15;
918 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
919 my $nb_of_days_before = 1;
920 my $nb_of_days_after = 2;
922 my $builder = t::lib::TestBuilder->new();
924 my $library = $builder->build({ source => 'Branch' });
926 # before we add borrowers to this branch, add the expires we have now
927 # note that this pertains to the current mocked setting of the pref
928 # for this reason we add the new branchcode to most of the tests
929 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
931 my $patron_1 = $builder->build({
932 source => 'Borrower',
934 branchcode => $library->{branchcode},
935 dateexpiry => dt_from_string->add( days => $expiry_days )
939 my $patron_2 = $builder->build({
940 source => 'Borrower',
942 branchcode => $library->{branchcode},
943 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
947 my $patron_3 = $builder->build({
948 source => 'Borrower',
950 branchcode => $library->{branchcode},
951 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
955 # Test without extra parameters
956 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
957 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
960 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
961 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
962 my $expired = $upcoming_mem_expires->next;
963 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
964 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
965 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
967 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
968 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
969 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
971 # Test MembershipExpiryDaysNotice == undef
972 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
973 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
974 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
976 # Test the before parameter
977 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
978 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
979 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
980 # Test after parameter also
981 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
982 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
983 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
986 subtest 'holds and old_holds' => sub {
989 my $library = $builder->build( { source => 'Branch' } );
990 my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
991 my $item_1 = $builder->build_sample_item(
993 library => $library->{branchcode},
994 biblionumber => $biblionumber_1,
997 my $item_2 = $builder->build_sample_item(
999 library => $library->{branchcode},
1000 biblionumber => $biblionumber_1,
1003 my $biblionumber_2 = $builder->build_sample_biblio->biblionumber;
1004 my $item_3 = $builder->build_sample_item(
1006 library => $library->{branchcode},
1007 biblionumber => $biblionumber_2,
1011 my $patron = $builder->build(
1013 source => 'Borrower',
1014 value => { branchcode => $library->{branchcode} }
1018 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1019 my $holds = $patron->holds;
1020 is( ref($holds), 'Koha::Holds',
1021 'Koha::Patron->holds should return a Koha::Holds objects' );
1022 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
1024 C4::Reserves::AddReserve(
1026 branchcode => $library->{branchcode},
1027 borrowernumber => $patron->borrowernumber,
1028 biblionumber => $biblionumber_1
1032 C4::Reserves::AddReserve(
1034 branchcode => $library->{branchcode},
1035 borrowernumber => $patron->borrowernumber,
1036 biblionumber => $biblionumber_2,
1037 expiration_date => dt_from_string->add( days => 2 )
1041 $holds = $patron->holds;
1042 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
1044 my $old_holds = $patron->old_holds;
1045 is( ref($old_holds), 'Koha::Old::Holds',
1046 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
1047 is( $old_holds->count, 0, 'There should not be any old holds yet');
1049 my $hold = $holds->next;
1052 $old_holds = $patron->old_holds;
1053 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
1060 subtest 'search_patrons_to_anonymise' => sub {
1064 # TODO create a subroutine in t::lib::Mocks
1065 my $branch = $builder->build({ source => 'Branch' });
1066 my $userenv_patron = $builder->build_object({
1067 class => 'Koha::Patrons',
1068 value => { branchcode => $branch->{branchcode}, flags => 0 },
1070 t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
1072 my $anonymous = $builder->build( { source => 'Borrower', }, );
1074 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
1076 subtest 'Anonymous Patron should be undeleteable' => sub {
1079 my $anonymous_patron = Koha::Patrons->find( $anonymous->{borrowernumber} );
1080 throws_ok { $anonymous_patron->delete(); }
1081 'Koha::Exceptions::Patron::FailedDeleteAnonymousPatron',
1082 'Attempt to delete anonymous patron throws exception.';
1083 $anonymous_patron = Koha::Patrons->find( $anonymous->{borrowernumber} );
1084 is( $anonymous_patron->id, $anonymous->{borrowernumber}, "Anonymous Patron was not deleted" );
1087 subtest 'patron privacy is 1 (default)' => sub {
1090 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1091 my $patron = $builder->build(
1092 { source => 'Borrower',
1093 value => { privacy => 1, }
1096 my $item_1 = $builder->build_sample_item;
1097 my $issue_1 = $builder->build(
1098 { source => 'Issue',
1100 borrowernumber => $patron->{borrowernumber},
1101 itemnumber => $item_1->itemnumber,
1105 my $item_2 = $builder->build_sample_item;
1106 my $issue_2 = $builder->build(
1107 { source => 'Issue',
1109 borrowernumber => $patron->{borrowernumber},
1110 itemnumber => $item_2->itemnumber,
1115 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->barcode, undef, undef, dt_from_string('2010-10-10') );
1116 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->barcode, undef, undef, dt_from_string('2011-11-11') );
1117 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
1119 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
1120 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
1122 my $rows_affected = Koha::Old::Checkouts->search(
1125 Koha::Patrons->search_patrons_to_anonymise(
1126 { before => '2011-11-12' }
1127 )->get_column('borrowernumber')
1129 returndate => { '<' => '2011-10-11', }
1132 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1134 $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1135 is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
1137 my $dbh = C4::Context->dbh;
1138 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
1139 $sth->execute($item_1->itemnumber);
1140 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1141 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
1142 $sth->execute($item_2->itemnumber);
1143 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1144 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
1146 $rows_affected = Koha::Old::Checkouts->search(
1149 Koha::Patrons->search_patrons_to_anonymise(
1150 { before => '2011-11-12' }
1151 )->get_column('borrowernumber')
1153 returndate => { '<' => '2011-11-12', }
1156 $sth->execute($item_2->itemnumber);
1157 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1158 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
1160 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
1161 $sth_reset->execute( $patron->{borrowernumber}, $item_1->itemnumber );
1162 $sth_reset->execute( $patron->{borrowernumber}, $item_2->itemnumber );
1163 $rows_affected = Koha::Old::Checkouts->search(
1166 Koha::Patrons->search_patrons_to_anonymise->get_column(
1171 $sth->execute($item_1->itemnumber);
1172 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1173 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
1174 $sth->execute($item_2->itemnumber);
1175 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1176 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
1178 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1181 subtest 'patron privacy is 0 (forever)' => sub {
1184 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1185 my $patron = $builder->build(
1186 { source => 'Borrower',
1187 value => { privacy => 0, }
1190 my $item = $builder->build_sample_item;
1191 my $issue = $builder->build(
1192 { source => 'Issue',
1194 borrowernumber => $patron->{borrowernumber},
1195 itemnumber => $item->itemnumber,
1200 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1201 is( $returned, 1, 'The item should have been returned' );
1203 my $dbh = C4::Context->dbh;
1204 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1205 SELECT borrowernumber FROM old_issues where itemnumber = ?
1206 |, undef, $item->itemnumber);
1207 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1208 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1211 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1213 subtest 'AnonymousPatron is not defined' => sub {
1217 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1218 my $patron = $builder->build(
1219 { source => 'Borrower',
1220 value => { privacy => 1, }
1223 my $item = $builder->build_sample_item;
1224 my $issue = $builder->build(
1225 { source => 'Issue',
1227 borrowernumber => $patron->{borrowernumber},
1228 itemnumber => $item->itemnumber,
1233 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1234 is( $returned, 1, 'The item should have been returned' );
1235 my $patrons_to_anonymize = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1236 ok( $patrons_to_anonymize->count > 0, 'search_patrons_to_anonymize' );
1238 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1241 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1243 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1244 my $patron = $builder->build(
1245 { source => 'Borrower',
1246 value => { privacy => 1 } # Another branchcode than the logged in librarian
1249 my $item = $builder->build_sample_item;
1250 my $issue = $builder->build(
1251 { source => 'Issue',
1253 borrowernumber => $patron->{borrowernumber},
1254 itemnumber => $item->itemnumber,
1259 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1260 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1261 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1264 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1265 $userenv_patron->delete;
1267 # Reset IndependentBranches for further tests
1268 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1271 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1279 $nb_of_patrons = Koha::Patrons->search->count;
1280 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1281 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1282 my $library_11 = $builder->build( { source => 'Branch' } );
1283 my $library_12 = $builder->build( { source => 'Branch' } );
1284 my $library_21 = $builder->build( { source => 'Branch' } );
1285 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1286 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1287 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1288 Koha::Library::Group->new(
1289 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1290 Koha::Library::Group->new(
1291 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1292 Koha::Library::Group->new(
1293 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1295 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1296 # 2 patrons from library_11 (group1)
1297 # patron_11_1 see patron's infos from outside its group
1298 # Setting flags => undef to not be considered as superlibrarian
1299 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1300 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1301 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1302 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1303 # patron_11_2 can only see patron's info from its group
1304 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1305 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1306 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1307 # 1 patron from library_12 (group1)
1308 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1309 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1310 # 1 patron from library_21 (group2) can only see patron's info from its group
1311 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1312 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1313 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1315 # Pfiou, we can start now!
1316 subtest 'libraries_where_can_see_patrons' => sub {
1321 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1322 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1323 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1325 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1326 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1327 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| );
1329 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1330 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1331 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| );
1333 subtest 'can_see_patron_infos' => sub {
1336 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1337 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1338 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1339 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1341 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1342 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1343 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1344 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1346 subtest 'search_limited' => sub {
1349 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1350 my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1351 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1352 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1354 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1355 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1356 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' );
1358 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1359 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1360 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1362 $patron_11_1->delete;
1363 $patron_11_2->delete;
1368 subtest 'account_locked' => sub {
1370 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1371 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1372 for my $value ( undef, '', 0 ) {
1373 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1374 $patron->login_attempts(0)->store;
1375 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1376 $patron->login_attempts(1)->store;
1377 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1378 $patron->login_attempts(-1)->store;
1379 is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1382 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1383 $patron->login_attempts(2)->store;
1384 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1385 $patron->login_attempts(3)->store;
1386 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1387 $patron->login_attempts(4)->store;
1388 is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1389 $patron->login_attempts(-1)->store;
1390 is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1395 subtest 'is_child | is_adult' => sub {
1397 my $category = $builder->build_object(
1399 class => 'Koha::Patron::Categories',
1400 value => { category_type => 'A' }
1403 my $patron_adult = $builder->build_object(
1405 class => 'Koha::Patrons',
1406 value => { categorycode => $category->categorycode }
1409 $category = $builder->build_object(
1411 class => 'Koha::Patron::Categories',
1412 value => { category_type => 'I' }
1415 my $patron_adult_i = $builder->build_object(
1417 class => 'Koha::Patrons',
1418 value => { categorycode => $category->categorycode }
1421 $category = $builder->build_object(
1423 class => 'Koha::Patron::Categories',
1424 value => { category_type => 'C' }
1427 my $patron_child = $builder->build_object(
1429 class => 'Koha::Patrons',
1430 value => { categorycode => $category->categorycode }
1433 $category = $builder->build_object(
1435 class => 'Koha::Patron::Categories',
1436 value => { category_type => 'O' }
1439 my $patron_other = $builder->build_object(
1441 class => 'Koha::Patrons',
1442 value => { categorycode => $category->categorycode }
1445 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1446 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1447 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1448 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1450 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1451 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1452 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1453 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1456 $patron_adult->delete;
1457 $patron_adult_i->delete;
1458 $patron_child->delete;
1459 $patron_other->delete;
1462 subtest 'overdues' => sub {
1465 my $library = $builder->build( { source => 'Branch' } );
1466 my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
1467 my $item_1 = $builder->build_sample_item(
1469 library => $library->{branchcode},
1470 biblionumber => $biblionumber_1,
1473 my $item_2 = $builder->build_sample_item(
1475 library => $library->{branchcode},
1476 biblionumber => $biblionumber_1,
1479 my $item_3 = $builder->build_sample_item(
1481 library => $library->{branchcode},
1485 my $patron = $builder->build(
1487 source => 'Borrower',
1488 value => { branchcode => $library->{branchcode} }
1492 t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1494 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1496 AddIssue( $patron, $item_1->barcode, DateTime->now->subtract( days => 1 ) );
1497 AddIssue( $patron, $item_2->barcode, DateTime->now->subtract( days => 5 ) );
1498 AddIssue( $patron, $item_3->barcode );
1500 my $overdues = $patron->overdues;
1501 is( $overdues->count, 2, 'Patron should have 2 overdues');
1502 is( $overdues->next->itemnumber, $item_1->itemnumber, 'The issue should be returned in the same order as they have been done, first is correct' );
1503 is( $overdues->next->itemnumber, $item_2->itemnumber, 'The issue should be returned in the same order as they have been done, second is correct' );
1505 my $o = $overdues->reset->next;
1506 my $unblessed_overdue = $o->unblessed_all_relateds;
1507 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1508 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1509 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1510 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1513 $patron->checkouts->delete;
1517 subtest 'userid_is_valid' => sub {
1520 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1521 my $patron_category = $builder->build_object(
1523 class => 'Koha::Patron::Categories',
1524 value => { category_type => 'P', enrolmentfee => 0 }
1528 cardnumber => "123456789",
1529 firstname => "Tomasito",
1531 categorycode => $patron_category->categorycode,
1532 branchcode => $library->branchcode,
1535 my $expected_userid_patron_1 = 'tomasito.none';
1536 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1537 my $patron_1 = Koha::Patrons->find($borrowernumber);
1538 is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1539 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1541 $patron_1->userid( 'tomasito.non' );
1542 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1543 1, 'recently created userid -> unique (borrowernumber passed)' );
1545 $patron_1->userid( 'tomasitoxxx' );
1546 is( $patron_1->has_valid_userid,
1547 1, 'non-existent userid -> unique (borrowernumber passed)' );
1548 $patron_1->discard_changes; # We compare with the original userid later
1550 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1551 is( $patron_not_in_storage->has_valid_userid,
1552 0, 'userid exists for another patron, patron is not in storage yet' );
1554 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1555 is( $patron_not_in_storage->has_valid_userid,
1556 1, 'non-existent userid, patron is not in storage yet' );
1558 # Regression tests for BZ12226
1559 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1560 is( $db_patron->has_valid_userid,
1561 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1563 # Add a new borrower with the same userid but different cardnumber
1564 $data{cardnumber} = "987654321";
1565 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1566 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1567 $patron_2->userid($patron_1->userid);
1568 is( $patron_2->has_valid_userid,
1569 0, 'The userid is already in used, it cannot be used for another patron' );
1571 my $new_userid = 'a_user_id';
1572 $data{cardnumber} = "234567890";
1573 $data{userid} = 'a_user_id';
1574 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1575 my $patron_3 = Koha::Patrons->find($borrowernumber);
1576 is( $patron_3->userid, $new_userid,
1577 'Koha::Patron->store should insert the given userid' );
1585 $nb_of_patrons = Koha::Patrons->search->count;
1586 $retrieved_patron_1->delete;
1587 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1589 subtest 'BorrowersLog tests' => sub {
1592 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1593 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1595 my $cardnumber = $patron->cardnumber;
1596 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1599 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1600 my $log_info = from_json( $logs[0]->info );
1601 is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1602 is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1603 is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1605 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1606 $patron->track_login();
1607 @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1608 is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1611 $schema->storage->txn_rollback;
1613 subtest 'Test Koha::Patrons::merge' => sub {
1616 my $schema = Koha::Database->new()->schema();
1618 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1620 $schema->storage->txn_begin;
1622 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1623 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1624 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1626 my $anonymous_patron_orig = C4::Context->preference('AnonymousPatron');
1627 my $anonymous_patron = $builder->build({ source => 'Borrower' })->{borrowernumber};
1628 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron );
1630 while (my ($r, $field) = each(%$resultsets)) {
1631 $builder->build({ source => $r, value => { $field => $keeper->id } });
1632 $builder->build({ source => $r, value => { $field => $loser_1 } });
1633 $builder->build({ source => $r, value => { $field => $loser_2 } });
1636 $schema->resultset($r)->search( { $field => $keeper->id } );
1637 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1640 $schema->resultset($r)->search( { $field => $loser_1 } );
1641 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1644 $schema->resultset($r)->search( { $field => $loser_2 } );
1645 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1648 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1650 while (my ($r, $field) = each(%$resultsets)) {
1652 $schema->resultset($r)->search( {$field => $keeper->id } );
1653 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1656 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1657 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1658 is( ref Koha::Patrons->find($anonymous_patron), 'Koha::Patron', 'Anonymous Patron was not deleted' );
1660 $anonymous_patron = Koha::Patrons->find($anonymous_patron);
1661 $results = $anonymous_patron->merge_with( [ $keeper->id ] );
1662 is( $results, undef, "Anonymous patron cannot have other patrons merged into it" );
1663 is( Koha::Patrons->search( { borrowernumber => $keeper->id } )->count, 1, "Patron from attempted merge with AnonymousPatron still exists" );
1665 subtest 'extended attributes' => sub {
1669 $builder->build_object( { class => 'Koha::Patrons' } );
1671 $builder->build_object( { class => 'Koha::Patrons' } );
1673 my $attribute_type_normal_1 = $builder->build_object(
1675 class => 'Koha::Patron::Attribute::Types',
1676 value => { repeatable => 0, unique_id => 0 }
1679 my $attribute_type_normal_2 = $builder->build_object(
1681 class => 'Koha::Patron::Attribute::Types',
1682 value => { repeatable => 0, unique_id => 0 }
1686 my $attribute_type_repeatable = $builder->build_object(
1688 class => 'Koha::Patron::Attribute::Types',
1689 value => { repeatable => 1, unique_id => 0 }
1695 code => $attribute_type_normal_1->code,
1696 attribute => 'from attr 1'
1699 code => $attribute_type_repeatable->code,
1700 attribute => 'from attr repeatable'
1706 code => $attribute_type_normal_2->code,
1707 attribute => 'to attr 2'
1710 code => $attribute_type_repeatable->code,
1711 attribute => 'to attr repeatable'
1715 $keep_patron->extended_attributes($attr_keep);
1716 $merge_patron->extended_attributes($attr_merge);
1718 $keep_patron->merge_with( [ $merge_patron->borrowernumber ] );
1719 my $merged_attributes = $keep_patron->extended_attributes;
1720 is( $merged_attributes->count, 4 );
1722 sub compare_attributes {
1723 my ( $got, $expected, $code ) = @_;
1727 sort $got->search( { code => $code } )
1728 ->get_column('attribute')
1736 $attribute_type_normal_1->code
1741 $attribute_type_normal_2->code
1745 [ 'from attr repeatable', 'to attr repeatable' ],
1746 $attribute_type_repeatable->code
1750 $keep_patron->delete;
1751 $merge_patron->delete;
1753 # Recreate but don't expect an exception if 2 non-repeatable attributes exist, pick the one from the patron we keep
1755 $builder->build_object( { class => 'Koha::Patrons' } );
1757 $builder->build_object( { class => 'Koha::Patrons' } );
1759 $keep_patron->extended_attributes($attr_keep);
1760 $merge_patron->extended_attributes(
1764 code => $attribute_type_normal_1->code,
1765 attribute => 'yet another attribute for non-repeatable'
1770 $keep_patron->merge_with( [ $merge_patron->borrowernumber ] );
1771 $merged_attributes = $keep_patron->extended_attributes;
1772 is( $merged_attributes->count, 4 );
1776 $attribute_type_normal_1->code
1781 $attribute_type_normal_2->code
1785 [ 'from attr repeatable', 'to attr repeatable' ],
1786 $attribute_type_repeatable->code
1791 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1792 $schema->storage->txn_rollback;
1795 subtest '->store' => sub {
1797 my $schema = Koha::Database->new->schema;
1798 $schema->storage->txn_begin;
1800 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1801 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1803 throws_ok { $patron_2->userid( $patron_1->userid )->store; }
1804 'Koha::Exceptions::Patron::InvalidUserid',
1805 'Koha::Patron->store raises an exception on duplicate ID';
1807 # Clear userid and check regeneration
1808 $patron_2->userid(undef)->store;
1809 like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid
1810 $patron_2->userid('')->store;
1811 like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid
1812 $patron_2->userid(0)->store;
1813 like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid
1816 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1817 my $password = 'password';
1818 $patron_1->set_password({ password => $password });
1819 like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1820 my $digest = $patron_1->password;
1821 $patron_1->surname('xxx')->store;
1822 is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1824 # Test uppercasesurnames
1825 t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 );
1826 my $surname = lc $patron_1->surname;
1827 $patron_1->surname($surname)->store;
1828 isnt( $patron_1->surname, $surname,
1829 'Surname converts to uppercase on store.');
1830 t::lib::Mocks::mock_preference( 'uppercasesurnames', 0 );
1831 $patron_1->surname($surname)->store;
1832 is( $patron_1->surname, $surname,
1833 'Surname remains unchanged on store.');
1836 $patron_1->relationship("")->store;
1837 is( $patron_1->relationship, undef, );
1839 $schema->storage->txn_rollback;
1841 subtest 'skip updated_on for BorrowersLog' => sub {
1843 $schema->storage->txn_begin;
1844 t::lib::Mocks::mock_preference('BorrowersLog', 1);
1845 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1846 $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1847 my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1848 is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1849 $schema->storage->txn_rollback;
1852 subtest 'create user usage' => sub {
1854 $schema->storage->txn_begin;
1856 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1857 my $patron_category = $builder->build_object(
1859 class => 'Koha::Patron::Categories',
1860 value => { category_type => 'P', enrolmentfee => 0 }
1864 cardnumber => "123456789",
1865 firstname => "Tômà sÃtó",
1866 surname => "Ñoné",
1867 password => 'Funk3y',
1868 categorycode => $patron_category->categorycode,
1869 branchcode => $library->branchcode,
1872 # Enable notifying patrons of password changes for these tests
1873 t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 1 );
1874 my $new_patron = Koha::Patron->new( \%data )->store();
1875 my $queued_notices = Koha::Notice::Messages->search(
1876 { borrowernumber => $new_patron->borrowernumber }
1879 $queued_notices->count, 0,
1880 "No notice queued when NotifyPasswordChange enabled and this is a new patron"
1883 $schema->storage->txn_rollback;
1887 subtest '->set_password' => sub {
1891 t::lib::Mocks::mock_preference( 'EmailFieldPrecedence', 'emailpro|email' );
1893 $schema->storage->txn_begin;
1895 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1897 # Disable logging password changes for these tests
1898 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1900 # Disable notifying patrons of password changes for these tests
1901 t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 0 );
1903 # Password-length tests
1904 t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1905 throws_ok { $patron->set_password({ password => 'ab' }); }
1906 'Koha::Exceptions::Password::TooShort',
1907 'minPasswordLength is undef, fall back to 3, fail test';
1909 'Password length (2) is shorter than required (3)',
1910 'Exception parameters passed correctly'
1913 t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1914 throws_ok { $patron->set_password({ password => 'ab' }); }
1915 'Koha::Exceptions::Password::TooShort',
1916 'minPasswordLength is 2, fall back to 3, fail test';
1918 t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1919 throws_ok { $patron->set_password({ password => 'abcb' }); }
1920 'Koha::Exceptions::Password::TooShort',
1921 'minPasswordLength is 5, fail test';
1923 # Trailing spaces tests
1924 throws_ok { $patron->set_password({ password => 'abcD12d ' }); }
1925 'Koha::Exceptions::Password::WhitespaceCharacters',
1926 'Password contains trailing spaces, exception is thrown';
1928 # Require strong password tests
1929 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1930 throws_ok { $patron->set_password({ password => 'abcd a' }); }
1931 'Koha::Exceptions::Password::TooWeak',
1932 'Password is too weak, exception is thrown';
1934 # Refresh patron from DB, just to make sure
1935 $patron->discard_changes;
1936 is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1938 $patron->set_password({ password => 'abcD12 34' });
1939 $patron->discard_changes;
1941 is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1943 lives_ok { $patron->set_password({ password => 'abcd a', skip_validation => 1 }) }
1944 'Password is weak, but skip_validation was passed, so no exception thrown';
1947 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1948 $patron->login_attempts(3)->store;
1949 my $old_digest = $patron->password;
1950 $patron->set_password({ password => 'abcd a' });
1951 $patron->discard_changes;
1953 isnt( $patron->password, $old_digest, 'Password has been updated' );
1954 ok( checkpw_hash('abcd a', $patron->password), 'Password hash is correct' );
1955 is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1957 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1958 is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1960 # Enable logging password changes
1961 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1962 $patron->set_password({ password => 'abcd b' });
1964 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1965 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1967 # Enable notifying patrons of password changes
1968 t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 1 );
1969 $patron->set_password({ password => 'abcd c' });
1970 my $queued_notices = Koha::Notice::Messages->search({ borrowernumber => $patron->borrowernumber });
1971 is( $queued_notices->count, 1, "One notice queued when NotifyPasswordChange enabled" );
1972 my $THE_notice = $queued_notices->next;
1973 is( $THE_notice->status, 'failed', "The notice was handled immediately and failed on wrong email address."); #FIXME Mock sending mail
1974 $schema->storage->txn_rollback;
1977 $schema->storage->txn_begin;
1978 subtest 'filter_by_expiration_date' => sub {
1980 my $count1 = Koha::Patrons->filter_by_expiration_date({ days => 28 })->count;
1981 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1982 $patron1->dateexpiry( dt_from_string->subtract(days => 27) )->store;
1983 is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1, 'No more expired' );
1984 $patron1->dateexpiry( dt_from_string->subtract(days => 28) )->store;
1985 is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1 + 1, 'One more expired' );
1986 $patron1->dateexpiry( dt_from_string->subtract(days => 29) )->store;
1987 is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1 + 1, 'Same number again' );
1990 subtest 'search_unsubscribed' => sub {
1993 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1994 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
1995 is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
1997 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1998 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2000 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
2001 Koha::Patron::Consents->delete; # for correct counts
2002 Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string })->store;
2003 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
2005 # Add another refusal but shift the period
2006 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
2007 Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string->subtract(days=>2) })->store;
2008 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
2010 # Try another (special) attempts setting
2011 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
2012 # Lockout is now disabled
2013 # Patron2 still matches: refused earlier, not locked
2014 is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
2017 subtest 'search_anonymize_candidates' => sub {
2019 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2020 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2021 $patron1->anonymized(0);
2022 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
2023 $patron2->anonymized(0);
2024 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
2026 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
2027 is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
2029 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
2030 my $cnt = Koha::Patrons->search_anonymize_candidates->count;
2031 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2032 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2033 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
2035 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
2036 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
2037 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
2038 $cnt = Koha::Patrons->search_anonymize_candidates->count;
2039 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2040 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2041 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
2043 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
2044 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
2045 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
2046 $cnt = Koha::Patrons->search_anonymize_candidates->count;
2047 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2048 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2049 is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
2051 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
2052 $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
2053 $patron1->login_attempts(0)->store;
2054 $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
2055 $patron2->login_attempts(0)->store;
2056 $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
2057 $patron1->login_attempts(3)->store;
2058 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2059 $cnt+1, 'Locked flag' );
2061 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
2062 # Patron 1 still on 3 == locked
2063 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2064 $cnt+1, 'Still expect same number for FailedLoginAttempts empty' );
2065 $patron1->login_attempts(0)->store;
2067 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2068 $cnt, 'Patron 1 unlocked' );
2071 subtest 'search_anonymized' => sub {
2073 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2075 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
2076 is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
2078 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
2079 $patron1->dateexpiry( dt_from_string );
2080 $patron1->anonymized(0)->store;
2081 my $cnt = Koha::Patrons->search_anonymized->count;
2082 $patron1->anonymized(1)->store;
2083 is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
2084 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2085 is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
2088 subtest 'lock' => sub {
2091 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2092 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
2093 my $hold = $builder->build_object({
2094 class => 'Koha::Holds',
2095 value => { borrowernumber => $patron1->borrowernumber },
2098 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
2099 my $expiry = dt_from_string->add(days => 1);
2100 $patron1->dateexpiry( $expiry );
2102 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
2103 is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
2104 is( $patron1->holds->count, 1, 'No holds removed' );
2106 $patron1->lock({ expire => 1, remove => 1});
2107 isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
2108 is( $patron1->holds->count, 0, 'Holds removed' );
2110 # Disable lockout feature
2111 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
2112 $patron1->login_attempts(0);
2113 $patron1->dateexpiry( $expiry );
2116 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
2118 # Trivial wrapper test (Koha::Patrons->lock)
2119 $patron1->login_attempts(0)->store;
2120 Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
2121 $patron1->discard_changes; # refresh
2122 $patron2->discard_changes;
2123 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
2124 is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
2127 subtest 'anonymize' => sub {
2130 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2131 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
2133 # First try patron with issues
2134 my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
2135 warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
2138 t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
2139 my $surname = $patron1->surname; # expect change, no clear
2140 my $branchcode = $patron1->branchcode; # expect skip
2141 $patron1->anonymize;
2142 is($patron1->anonymized, 1, 'Check flag' );
2144 is( $patron1->dateofbirth, undef, 'Birth date cleared' );
2145 is( $patron1->firstname, undef, 'First name cleared' );
2146 isnt( $patron1->surname, $surname, 'Surname changed' );
2147 ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
2148 is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
2149 is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
2151 # Test wrapper in Koha::Patrons
2152 $patron1->surname($surname)->store; # restore
2153 my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
2154 $patron1->discard_changes; # refresh
2155 isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
2156 $patron2->discard_changes; # refresh
2157 is( $patron2->firstname, undef, 'First name patron2 cleared' );
2160 subtest 'queue_notice' => sub {
2163 my $dbh = C4::Context->dbh;
2164 t::lib::Mocks::mock_preference( 'EmailFieldPrimary', 'email' );
2165 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2166 my $branch = $builder->build_object( { class => 'Koha::Libraries' } );
2167 my $letter_e = $builder->build_object( {
2168 class => 'Koha::Notice::Templates',
2170 branchcode => $branch->branchcode,
2171 message_transport_type => 'email',
2175 my $letter_p = $builder->build_object( {
2176 class => 'Koha::Notice::Templates',
2178 code => $letter_e->code,
2179 module => $letter_e->module,
2180 branchcode => $branch->branchcode,
2181 message_transport_type => 'print',
2185 my $letter_s = $builder->build_object( {
2186 class => 'Koha::Notice::Templates',
2188 code => $letter_e->code,
2189 module => $letter_e->module,
2190 branchcode => $branch->branchcode,
2191 message_transport_type => 'sms',
2196 my $letter_params = {
2197 letter_code => $letter_e->code,
2198 branchcode => $letter_e->branchcode,
2199 module => $letter_e->module,
2200 borrowernumber => $patron->borrowernumber,
2202 borrowers => $patron->borrowernumber,
2205 my @mtts = ('email');
2207 is( $patron->queue_notice(), undef, "Nothing is done if no params passed");
2208 is( $patron->queue_notice({ letter_params => $letter_params }),undef, "Nothing done if only letter");
2210 $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2211 {sent => ['email'] }, "Email sent"
2213 $patron->email("")->store;
2215 $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2216 {sent => ['print'],fallback => ['email']}, "Email fallsback to print if no email"
2220 $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2221 {sent => ['print','sms'],fallback => ['email']}, "Email fallsback to print if no email, sms sent"
2223 $patron->smsalertnumber("")->store;
2224 my $counter = Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count;
2226 $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2227 {sent => ['print'],fallback => ['email','sms']}, "Email fallsback to print if no emai, sms fallsback to print if no sms, only one print sent"
2229 is( Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count, $counter+1,"Count of queued notices went up by one");
2231 # Enable notification for Hold_Filled - Things are hardcoded here but should work with default data
2232 $dbh->do(q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ?)|, undef, $patron->borrowernumber, 4 );
2233 my $borrower_message_preference_id = $dbh->last_insert_id(undef, undef, "borrower_message_preferences", undef);
2234 $dbh->do(q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, undef, $borrower_message_preference_id, 'email' );
2236 is( $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts, message_name => 'Hold_Filled' }),undef, "Nothing done if transports and name sent");
2238 $patron->email(q|awesome@ismymiddle.name|)->store;
2240 $patron->queue_notice({ letter_params => $letter_params, message_name => 'Hold_Filled' }),
2241 {sent => ['email'] }, "Email sent when using borrower preferences"
2243 $counter = Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count;
2245 $patron->queue_notice({ letter_params => $letter_params, message_name => 'Hold_Filled', test_mode => 1 }),
2246 {sent => ['email'] }, "Report that email sent when using borrower preferences in test_mode"
2248 is( Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count, $counter,"Count of queued notices not increased in test mode");
2251 subtest 'filter_by_amount_owed' => sub {
2254 my $library = $builder->build({source => 'Branch' });
2255 my $category = $builder->build({source => 'Category' });
2257 my $new_patron_cf_1 = Koha::Patron->new(
2259 cardnumber => 'test_cn_cf_1',
2260 branchcode => $library->{branchcode},
2261 categorycode => $category->{categorycode},
2262 surname => 'surname for patron1',
2263 firstname => 'firstname for patron1',
2264 userid => 'a_nonexistent_userid_cf_1',
2267 my $new_patron_cf_2 = Koha::Patron->new(
2269 cardnumber => 'test_cn_cf_2',
2270 branchcode => $library->{branchcode},
2271 categorycode => $category->{categorycode},
2272 surname => 'surname for patron2',
2273 firstname => 'firstname for patron2',
2274 userid => 'a_nonexistent_userid_cf_2',
2277 my $new_patron_cf_3 = Koha::Patron->new(
2279 cardnumber => 'test_cn_cf_3',
2280 branchcode => $library->{branchcode},
2281 categorycode => $category->{categorycode},
2282 surname => 'surname for patron3',
2283 firstname => 'firstname for patron3',
2284 userid => 'a_nonexistent_userid_cf_3',
2288 my $results = Koha::Patrons->search(
2290 'me.borrowernumber' => [
2291 $new_patron_cf_1->borrowernumber,
2292 $new_patron_cf_2->borrowernumber,
2293 $new_patron_cf_3->borrowernumber
2298 my $fine1 = $builder->build(
2300 source => 'Accountline',
2302 borrowernumber => $new_patron_cf_1->borrowernumber,
2303 amountoutstanding => 12.00,
2305 debit_type_code => 'OVERDUE',
2306 branchcode => $library->{branchcode}
2310 my $fine2 = $builder->build(
2312 source => 'Accountline',
2314 borrowernumber => $new_patron_cf_2->borrowernumber,
2315 amountoutstanding => 8.00,
2317 debit_type_code => 'OVERDUE',
2318 branchcode => $library->{branchcode}
2323 my $fine3 = $builder->build(
2325 source => 'Accountline',
2327 borrowernumber => $new_patron_cf_2->borrowernumber,
2328 amountoutstanding => 10.00,
2330 debit_type_code => 'OVERDUE',
2331 branchcode => $library->{branchcode}
2336 my $filtered = $results->filter_by_amount_owed();
2337 is( ref($filtered), 'Koha::Patrons',
2338 'Koha::Patrons->filter_by_amount_owed should return a Koha::Patrons result set in a scalar context'
2341 my $lower_limit = 12.00;
2342 my $upper_limit = 16.00;
2344 # Catch user with 1 x 12.00 fine and user with no fines.
2346 $results->filter_by_amount_owed( { less_than => $upper_limit } );
2347 is( $filtered->_resultset->as_subselect_rs->count, 2,
2348 "filter_by_amount_owed({ less_than => $upper_limit }) found two patrons"
2351 # Catch user with 1 x 8.00 and 1 x 10.00 fine
2353 $results->filter_by_amount_owed( { more_than => $lower_limit } );
2354 is( $filtered->_resultset->as_subselect_rs->count, 1,
2355 "filter_by_amount_owed({ more_than => $lower_limit }) found two patrons"
2358 # User with 2 fines falls above upper limit - Excluded,
2359 # user with 1 fine falls below lower limit - Excluded
2360 # and user with no fines falls below lower limit - Excluded.
2361 $filtered = $results->filter_by_amount_owed(
2362 { more_than => $lower_limit, less_than => $upper_limit } );
2363 is( $filtered->_resultset->as_subselect_rs->count, 0,
2364 "filter_by_amount_owed({ more_than => $lower_limit, less_than => $upper_limit }) found zero patrons"
2367 my $library2 = $builder->build({source => 'Branch' });
2368 my $fine4 = $builder->build(
2370 source => 'Accountline',
2372 borrowernumber => $new_patron_cf_2->borrowernumber,
2373 amountoutstanding => 10.00,
2375 debit_type_code => 'HOLD',
2376 branchcode => $library2->{branchcode}
2381 # Catch only the user with a HOLD fee over 6.00
2382 $filtered = $results->filter_by_amount_owed( { more_than => 6.00, debit_type => 'HOLD' } );
2383 is( $filtered->_resultset->as_subselect_rs->count, 1,
2384 "filter_by_amount_owed({ more_than => 6.00, debit_type => 'HOLD' }) found one patron"
2387 # Catch only the user with a fee over 6.00 at the specified library
2388 $filtered = $results->filter_by_amount_owed( { more_than => 6.00, library => $library2->{branchcode} } );
2389 is( $filtered->_resultset->as_subselect_rs->count, 1,
2390 "filter_by_amount_owed({ more_than => 6.00, library => $library2->{branchcode} }) found one patron"
2394 subtest 'libraries_where_can_edit_items() and can_edit_items_from() tests' => sub {
2397 $schema->storage->txn_begin;
2398 my $dbh = $schema->storage->dbh;
2400 $dbh->do("DELETE FROM library_groups");
2407 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_limit_item_editing => 1 } )->store;
2408 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_limit_item_editing => 1 } )->store;
2409 my $library_1A = $builder->build( { source => 'Branch' } );
2410 my $library_1B = $builder->build( { source => 'Branch' } );
2411 my $library_2A = $builder->build( { source => 'Branch' } );
2412 $library_1A = Koha::Libraries->find( $library_1A->{branchcode} );
2413 $library_1B = Koha::Libraries->find( $library_1B->{branchcode} );
2414 $library_2A = Koha::Libraries->find( $library_2A->{branchcode} );
2415 Koha::Library::Group->new( { branchcode => $library_1A->branchcode, parent_id => $group_1->id } )->store;
2416 Koha::Library::Group->new( { branchcode => $library_1B->branchcode, parent_id => $group_1->id } )->store;
2417 Koha::Library::Group->new( { branchcode => $library_2A->branchcode, parent_id => $group_2->id } )->store;
2419 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 9, ?)|); # 9 for editcatalogue
2420 # 2 patrons from library_1A (group1)
2421 # patron_1A_1 see patron's infos from outside its group
2422 # Setting flags => undef to not be considered as superlibrarian
2423 my $patron_1A_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_1A->branchcode, flags => undef, }});
2424 $patron_1A_1 = Koha::Patrons->find( $patron_1A_1->{borrowernumber} );
2425 $sth->execute( $patron_1A_1->borrowernumber, 'edit_items' );
2426 $sth->execute( $patron_1A_1->borrowernumber, 'edit_any_item' );
2427 # patron_1A_2 can only see patron's info from its group
2428 my $patron_1A_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_1A->branchcode, flags => undef, }});
2429 $patron_1A_2 = Koha::Patrons->find( $patron_1A_2->{borrowernumber} );
2430 $sth->execute( $patron_1A_2->borrowernumber, 'edit_items' );
2431 # 1 patron from library_1B (group1)
2432 my $patron_1B = $builder->build({ source => 'Borrower', value => { branchcode => $library_1B->branchcode, flags => undef, }});
2433 $patron_1B = Koha::Patrons->find( $patron_1B->{borrowernumber} );
2434 # 1 patron from library_2A (group2) can only see patron's info from its group
2435 my $patron_2A = $builder->build({ source => 'Borrower', value => { branchcode => $library_2A->branchcode, flags => undef, }});
2436 $patron_2A = Koha::Patrons->find( $patron_2A->{borrowernumber} );
2437 $sth->execute( $patron_2A->borrowernumber, 'edit_items' );
2439 subtest 'libraries_where_can_edit_items' => sub {
2444 @branchcodes = $patron_1A_1->libraries_where_can_edit_items;
2445 is_deeply( \@branchcodes, [], "patron_1A_1 has edit_any_item => No restrictions" );
2447 @branchcodes = $patron_1A_2->libraries_where_can_edit_items;
2448 is_deeply( \@branchcodes, [ sort ( $library_1A->branchcode, $library_1B->branchcode ) ], "patron_1A_2 doesn't have edit_any_item => Can only edit items from its group" );
2450 @branchcodes = $patron_2A->libraries_where_can_edit_items;
2451 is_deeply( \@branchcodes, [$library_2A->branchcode], "patron_2A doesn't have edit_any_item => Can only see patron's from its group" );
2454 subtest 'can_edit_items_from' => sub {
2457 t::lib::Mocks::mock_userenv({ patron => $patron_1A_1 });
2458 is( $patron_1A_1->can_edit_items_from( $library_1A->id ), 1, "patron_1A_1 can see patron_1A_2, from its library" );
2459 is( $patron_1A_1->can_edit_items_from( $library_1B->id ), 1, "patron_1A_1 can see patron_1B, from its group" );
2460 is( $patron_1A_1->can_edit_items_from( $library_2A->id ), 1, "patron_1A_1 can see patron_1A_2, from another group" );
2462 t::lib::Mocks::mock_userenv({ patron => $patron_1A_2 });
2463 is( $patron_1A_2->can_edit_items_from( $library_1A->id ), 1, "patron_1A_2 can see patron_1A_1, from its library" );
2464 is( $patron_1A_2->can_edit_items_from( $library_1B->id ), 1, "patron_1A_2 can see patron_1B, from its group" );
2465 is( $patron_1A_2->can_edit_items_from( $library_2A->id ), 0, "patron_1A_2 can NOT see patron_2A, from another group" );
2469 subtest 'filter_by_have_permission' => sub {
2472 $schema->storage->txn_begin;
2474 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2475 my $patron_1 = $builder->build_object(
2477 class => 'Koha::Patrons',
2478 value => { flags => 1, branchcode => $library->branchcode }
2482 my $patron_2 = $builder->build_object( # 4096 = 1 << 12 for suggestions
2484 class => 'Koha::Patrons',
2485 value => { flags => 4096, branchcode => $library->branchcode }
2489 my $patron_3 = $builder->build_object(
2491 class => 'Koha::Patrons',
2492 value => { flags => 0, branchcode => $library->branchcode }
2497 source => 'UserPermission',
2499 borrowernumber => $patron_3->borrowernumber,
2501 code => 'order_manage',
2508 Koha::Patrons->search( { branchcode => $library->branchcode } )
2509 ->filter_by_have_permission('suggestions.suggestions_manage')
2510 ->get_column('borrowernumber')
2512 [ $patron_1->borrowernumber, $patron_2->borrowernumber ],
2513 'Superlibrarian and patron with suggestions.suggestions_manage'
2518 Koha::Patrons->search( { branchcode => $library->branchcode } )
2519 ->filter_by_have_permission('acquisition.order_manage')
2520 ->get_column('borrowernumber')
2522 [ $patron_1->borrowernumber, $patron_3->borrowernumber ],
2523 'Superlibrarian and patron with acquisition.order_manage'
2528 Koha::Patrons->search( { branchcode => $library->branchcode } )
2529 ->filter_by_have_permission('parameters.manage_cities')
2530 ->get_column('borrowernumber')
2532 [ $patron_1->borrowernumber ],
2533 'Only Superlibrarian is returned'
2538 Koha::Patrons->search( { branchcode => $library->branchcode } )
2539 ->filter_by_have_permission('suggestions')
2540 ->get_column('borrowernumber')
2542 [ $patron_1->borrowernumber, $patron_2->borrowernumber ],
2543 'Superlibrarian and patron with suggestions'
2547 Koha::Patrons->search( { branchcode => $library->branchcode } )
2548 ->filter_by_have_permission('dont_exist.subperm');
2549 } 'Koha::Exceptions::ObjectNotFound';
2552 $schema->storage->txn_rollback;
2555 $schema->storage->txn_rollback;