3 # Copyright 2015 Koha Development team
5 # This file is part of Koha
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22 use Test::More tests => 40;
32 use C4::Auth qw(checkpw_hash);
37 use Koha::Patron::Categories;
40 use Koha::Virtualshelves;
42 use t::lib::TestBuilder;
45 my $schema = Koha::Database->new->schema;
46 $schema->storage->txn_begin;
48 my $builder = t::lib::TestBuilder->new;
49 my $library = $builder->build({source => 'Branch' });
50 my $category = $builder->build({source => 'Category' });
51 my $nb_of_patrons = Koha::Patrons->search->count;
52 my $new_patron_1 = Koha::Patron->new(
53 { cardnumber => 'test_cn_1',
54 branchcode => $library->{branchcode},
55 categorycode => $category->{categorycode},
56 surname => 'surname for patron1',
57 firstname => 'firstname for patron1',
58 userid => 'a_nonexistent_userid_1',
59 flags => 1, # Is superlibrarian
62 my $new_patron_2 = Koha::Patron->new(
63 { cardnumber => 'test_cn_2',
64 branchcode => $library->{branchcode},
65 categorycode => $category->{categorycode},
66 surname => 'surname for patron2',
67 firstname => 'firstname for patron2',
68 userid => 'a_nonexistent_userid_2',
72 t::lib::Mocks::mock_userenv({ patron => $new_patron_1 });
74 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
76 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
77 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
79 subtest 'library' => sub {
81 is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
82 is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
85 subtest 'guarantees' => sub {
87 my $guarantees = $new_patron_1->guarantees;
88 is( ref($guarantees), 'Koha::Patrons', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
89 is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee' );
90 my @guarantees = $new_patron_1->guarantees;
91 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantees should return an array in a list context' );
92 is( scalar(@guarantees), 0, 'new_patron_1 should have 0 guarantee' );
94 my $guarantee_1 = $builder->build({ source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber }});
95 my $guarantee_2 = $builder->build({ source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber }});
97 $guarantees = $new_patron_1->guarantees;
98 is( ref($guarantees), 'Koha::Patrons', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
99 is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
100 @guarantees = $new_patron_1->guarantees;
101 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantees should return an array in a list context' );
102 is( scalar(@guarantees), 2, 'new_patron_1 should have 2 guarantees' );
103 $_->delete for @guarantees;
105 #Test return order of guarantees BZ 18635
106 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
107 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
109 my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
111 my $order_guarantee1 = $builder->build_object( { class => 'Koha::Patrons' , value => {
113 guarantorid => $guarantor->borrowernumber
117 my $order_guarantee2 = $builder->build_object( { class => 'Koha::Patrons' , value => {
119 guarantorid => $guarantor->borrowernumber
123 my $order_guarantee3 = $builder->build_object( { class => 'Koha::Patrons' , value => {
125 firstname => 'Walrus',
126 guarantorid => $guarantor->borrowernumber
130 my $order_guarantee4 = $builder->build_object( { class => 'Koha::Patrons' , value => {
132 firstname => 'Vulture',
133 guarantorid => $guarantor->borrowernumber
137 my $order_guarantee5 = $builder->build_object( { class => 'Koha::Patrons' , value => {
139 firstname => 'Unicorn',
140 guarantorid => $guarantor->borrowernumber
144 $guarantees = $guarantor->guarantees();
146 is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
147 is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
148 is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
149 is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
150 is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
153 subtest 'category' => sub {
155 my $patron_category = $new_patron_1->category;
156 is( ref( $patron_category), 'Koha::Patron::Category', );
157 is( $patron_category->categorycode, $category->{categorycode}, );
160 subtest 'siblings' => sub {
162 my $siblings = $new_patron_1->siblings;
163 is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
164 my $guarantee_1 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
165 my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
166 $siblings = $retrieved_guarantee_1->siblings;
167 is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
168 my @siblings = $retrieved_guarantee_1->siblings;
169 is( ref( \@siblings ), 'ARRAY', 'Koha::Patron->siblings should return an array in a list context' );
170 is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' );
171 my $guarantee_2 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
172 my $guarantee_3 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
173 $siblings = $retrieved_guarantee_1->siblings;
174 is( $siblings->count, 2, 'guarantee_1 should have 2 siblings' );
175 is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
176 is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
177 $_->delete for $retrieved_guarantee_1->siblings;
178 $retrieved_guarantee_1->delete;
181 subtest 'has_overdues' => sub {
184 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
185 my $item_1 = $builder->build(
188 homebranch => $library->{branchcode},
189 holdingbranch => $library->{branchcode},
193 biblionumber => $biblioitem_1->{biblionumber}
197 my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
198 is( $retrieved_patron->has_overdues, 0, );
200 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
201 my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
202 is( $retrieved_patron->has_overdues, 0, );
204 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
205 $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
206 $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
207 is( $retrieved_patron->has_overdues, 1, );
211 subtest 'is_expired' => sub {
213 my $patron = $builder->build({ source => 'Borrower' });
214 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
215 $patron->dateexpiry( undef )->store->discard_changes;
216 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
217 $patron->dateexpiry( dt_from_string )->store->discard_changes;
218 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
219 $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
220 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
221 $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
222 is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
227 subtest 'is_going_to_expire' => sub {
229 my $patron = $builder->build({ source => 'Borrower' });
230 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
231 $patron->dateexpiry( undef )->store->discard_changes;
232 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
234 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
235 $patron->dateexpiry( dt_from_string )->store->discard_changes;
236 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
238 $patron->dateexpiry( dt_from_string )->store->discard_changes;
239 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
241 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
242 $patron->dateexpiry( dt_from_string->add( days => 11 ) )->store->discard_changes;
243 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');
245 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
246 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
247 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');
249 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
250 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
251 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');
254 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
255 $patron->dateexpiry( dt_from_string->add( days => 20 ) )->store->discard_changes;
256 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');
258 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
259 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
260 is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
266 subtest 'renew_account' => sub {
269 for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
270 my $dt = dt_from_string( $date, 'iso' );
271 Time::Fake->offset( $dt->epoch );
272 my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
273 my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
274 my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
275 my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
276 my $a_year_later_plus_a_month = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
277 my $patron_category = $builder->build(
278 { source => 'Category',
280 enrolmentperiod => 12,
281 enrolmentperioddate => undef,
285 my $patron = $builder->build(
286 { source => 'Borrower',
288 dateexpiry => $a_month_ago,
289 categorycode => $patron_category->{categorycode},
290 date_renewed => undef, # Force builder to not populate the column for new patron
294 my $patron_2 = $builder->build(
295 { source => 'Borrower',
297 dateexpiry => $a_month_ago,
298 categorycode => $patron_category->{categorycode},
302 my $patron_3 = $builder->build(
303 { source => 'Borrower',
305 dateexpiry => $a_month_later,
306 categorycode => $patron_category->{categorycode},
310 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
311 my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
312 my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
314 is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
316 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
317 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
318 my $expiry_date = $retrieved_patron->renew_account;
319 is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
320 my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
321 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" );
322 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
323 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
325 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
326 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
327 $expiry_date = $retrieved_patron->renew_account;
328 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
329 $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
330 is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
331 $retrieved_expiry_date = $retrieved_patron->dateexpiry;
332 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
333 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
334 is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
336 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
337 $expiry_date = $retrieved_patron_2->renew_account;
338 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
339 $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
340 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
342 $expiry_date = $retrieved_patron_3->renew_account;
343 is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
344 $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
345 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" );
347 $retrieved_patron->delete;
348 $retrieved_patron_2->delete;
349 $retrieved_patron_3->delete;
354 subtest "move_to_deleted" => sub {
356 my $originally_updated_on = '2016-01-01 12:12:12';
357 my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
358 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
359 is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
360 ; # FIXME This should be Koha::Deleted::Patron
361 my $deleted_patron = $schema->resultset('Deletedborrower')
362 ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
364 ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
365 ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
366 isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
367 $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
368 is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
369 $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup
372 subtest "delete" => sub {
374 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
375 my $patron = $builder->build( { source => 'Borrower' } );
376 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
377 my $hold = $builder->build(
378 { source => 'Reserve',
379 value => { borrowernumber => $patron->{borrowernumber} }
382 my $list = $builder->build(
383 { source => 'Virtualshelve',
384 value => { owner => $patron->{borrowernumber} }
388 my $deleted = $retrieved_patron->delete;
389 is( $deleted, 1, 'Koha::Patron->delete should return 1 if the patron has been correctly deleted' );
391 is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
393 is (Koha::Old::Holds->search( { reserve_id => $hold->{ reserve_id } } )->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| );
395 is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's holds| );
397 is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
399 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
400 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
403 subtest 'Koha::Patrons->delete' => sub {
406 my $mod_patron = Test::MockModule->new( 'Koha::Patron' );
407 my $moved_to_deleted = 0;
408 $mod_patron->mock( 'move_to_deleted', sub { $moved_to_deleted++; } );
410 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
411 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
412 my $id1 = $patron1->borrowernumber;
413 my $set = Koha::Patrons->search({ borrowernumber => { '>=' => $id1 }});
414 is( $set->count, 2, 'Two patrons found as expected' );
415 is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
416 is( $moved_to_deleted, 2, 'Patrons moved to deletedborrowers' );
418 # Add again, test if we can raise an exception
419 $mod_patron->mock( 'delete', sub { return -1; } );
420 $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
421 $id1 = $patron1->borrowernumber;
422 $set = Koha::Patrons->search({ borrowernumber => { '>=' => $id1 }});
423 throws_ok { $set->delete } 'Koha::Exceptions::Patron::FailedDelete',
424 'Exception raised for deleting patron';
427 subtest 'add_enrolment_fee_if_needed' => sub {
430 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
431 foreach( keys %{$enrolmentfees} ) {
432 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
434 my $enrolmentfee_K = $enrolmentfees->{K};
435 my $enrolmentfee_J = $enrolmentfees->{J};
436 my $enrolmentfee_YA = $enrolmentfees->{YA};
438 my %borrower_data = (
439 firstname => 'my firstname',
440 surname => 'my surname',
442 branchcode => $library->{branchcode},
445 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
446 $borrower_data{borrowernumber} = $borrowernumber;
448 my $patron = Koha::Patrons->find( $borrowernumber );
449 my $total = $patron->account->balance;
450 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
452 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
453 $borrower_data{categorycode} = 'J';
454 $patron->set(\%borrower_data)->store;
455 $total = $patron->account->balance;
456 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
458 $borrower_data{categorycode} = 'K';
459 $patron->set(\%borrower_data)->store;
460 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
462 $borrower_data{categorycode} = 'J';
463 $patron->set(\%borrower_data)->store;
464 $total = $patron->account->balance;
465 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
467 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
468 $patron->categorycode('YA')->store;
469 $total = $patron->account->balance;
471 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
472 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
478 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
481 my $library = $builder->build( { source => 'Branch' } );
482 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
483 my $item_1 = $builder->build(
487 homebranch => $library->{branchcode},
488 holdingbranch => $library->{branchcode},
489 biblionumber => $biblionumber_1,
495 my $item_2 = $builder->build(
499 homebranch => $library->{branchcode},
500 holdingbranch => $library->{branchcode},
501 biblionumber => $biblionumber_1,
507 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
508 my $item_3 = $builder->build(
512 homebranch => $library->{branchcode},
513 holdingbranch => $library->{branchcode},
514 biblionumber => $biblionumber_2,
520 my $patron = $builder->build(
522 source => 'Borrower',
523 value => { branchcode => $library->{branchcode} }
527 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
528 my $checkouts = $patron->checkouts;
529 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
530 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
531 my $pending_checkouts = $patron->pending_checkouts;
532 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
533 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
534 my $old_checkouts = $patron->old_checkouts;
535 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
536 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
538 # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
539 $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
541 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
543 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
544 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
545 AddIssue( $patron, $item_3->{barcode} );
547 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
548 $checkouts = $patron->checkouts;
549 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
550 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
551 $pending_checkouts = $patron->pending_checkouts;
552 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
553 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
555 my $first_checkout = $pending_checkouts->next;
556 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
558 my $overdues = $patron->get_overdues;
559 is( $overdues->count, 2, 'Patron should have 2 overdues');
560 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
561 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
562 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
565 C4::Circulation::AddReturn( $item_1->{barcode} );
566 C4::Circulation::AddReturn( $item_2->{barcode} );
567 $old_checkouts = $patron->old_checkouts;
568 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
569 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
572 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
576 subtest 'get_routing_lists' => sub {
579 my $biblio = Koha::Biblio->new()->store();
580 my $subscription = Koha::Subscription->new({
581 biblionumber => $biblio->biblionumber,
585 my $patron = $builder->build( { source => 'Borrower' } );
586 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
588 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
590 my $routinglist_count = Koha::Subscription::Routinglists->count;
591 my $routinglist = Koha::Subscription::Routinglist->new({
592 borrowernumber => $patron->borrowernumber,
594 subscriptionid => $subscription->subscriptionid
597 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
599 my $routinglists = $patron->get_routing_lists;
600 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
601 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
603 my $subscription2 = Koha::Subscription->new({
604 biblionumber => $biblio->biblionumber,
607 my $routinglist2 = Koha::Subscription::Routinglist->new({
608 borrowernumber => $patron->borrowernumber,
610 subscriptionid => $subscription2->subscriptionid
613 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
615 $patron->delete; # Clean up for later tests
619 subtest 'get_age' => sub {
622 my $patron = $builder->build( { source => 'Borrower' } );
623 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
625 my $today = dt_from_string;
627 $patron->dateofbirth( undef );
628 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
629 $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1, end_of_month => 'limit' ) );
630 is( $patron->get_age, 12, 'Patron should be 12' );
631 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 1, end_of_month => 'limit' ) );
632 is( $patron->get_age, 17, 'Patron should be 17, happy birthday tomorrow!' );
633 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 0, end_of_month => 'limit' ) );
634 is( $patron->get_age, 18, 'Patron should be 18' );
635 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -31, end_of_month => 'limit' ) );
636 is( $patron->get_age, 19, 'Patron should be 19' );
637 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -30, end_of_month => 'limit' ) );
638 is( $patron->get_age, 19, 'Patron should be 19 again' );
639 $patron->dateofbirth( $today->clone->add( years => 0, months => -1, days => -1, end_of_month => 'limit' ) );
640 is( $patron->get_age, 0, 'Patron is a newborn child' );
645 subtest 'is_valid_age' => sub {
648 my $today = dt_from_string;
650 my $category = $builder->build({
651 source => 'Category',
653 categorycode => 'AGE_5_10',
654 dateofbirthrequired => 5,
658 $category = Koha::Patron::Categories->find( $category->{categorycode} );
660 my $patron = $builder->build({
661 source => 'Borrower',
663 categorycode => 'AGE_5_10'
666 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
669 $patron->dateofbirth( undef );
670 is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
672 $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1 ) );
673 is( $patron->is_valid_age, 0, 'Patron is 12, so the age is above allowed range 5-10 years');
675 $patron->dateofbirth( $today->clone->add( years => -3, months => -6, days => -1 ) );
676 is( $patron->is_valid_age, 0, 'Patron is 3, so the age is below allowed range 5-10 years');
678 $patron->dateofbirth( $today->clone->add( years => -7, months => -6, days => -1 ) );
679 is( $patron->is_valid_age, 1, 'Patron is 7, so the age perfectly suits allowed range 5-10 years');
681 $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => 0 ) );
682 is( $patron->is_valid_age, 1, 'Patron celebrates the 5th birthday today, so the age is allowed for this category');
684 $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => 1 ) );
685 is( $patron->is_valid_age, 0, 'Patron will celebrate the 5th birthday tomorrow, so the age is NOT allowed for this category');
687 $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => -1 ) );
688 is( $patron->is_valid_age, 1, 'Patron celebrated the 5th birthday yesterday, so the age is allowed for this category');
690 $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => 0 ) );
691 is( $patron->is_valid_age, 0, 'Patron celebrate the 11th birthday today, so the age is NOT allowed for this category');
693 $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => 1 ) );
694 is( $patron->is_valid_age, 1, 'Patron will celebrate the 11th birthday tomorrow, so the age is allowed for this category');
696 $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => -1 ) );
697 is( $patron->is_valid_age, 0, 'Patron celebrated the 11th birthday yesterday, so the age is NOT allowed for this category');
703 subtest 'account' => sub {
706 my $patron = $builder->build({source => 'Borrower'});
708 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
709 my $account = $patron->account;
710 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
715 subtest 'search_upcoming_membership_expires' => sub {
718 my $expiry_days = 15;
719 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
720 my $nb_of_days_before = 1;
721 my $nb_of_days_after = 2;
723 my $builder = t::lib::TestBuilder->new();
725 my $library = $builder->build({ source => 'Branch' });
727 # before we add borrowers to this branch, add the expires we have now
728 # note that this pertains to the current mocked setting of the pref
729 # for this reason we add the new branchcode to most of the tests
730 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
732 my $patron_1 = $builder->build({
733 source => 'Borrower',
735 branchcode => $library->{branchcode},
736 dateexpiry => dt_from_string->add( days => $expiry_days )
740 my $patron_2 = $builder->build({
741 source => 'Borrower',
743 branchcode => $library->{branchcode},
744 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
748 my $patron_3 = $builder->build({
749 source => 'Borrower',
751 branchcode => $library->{branchcode},
752 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
756 # Test without extra parameters
757 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
758 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
761 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
762 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
763 my $expired = $upcoming_mem_expires->next;
764 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
765 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
766 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
768 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
769 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
770 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
772 # Test MembershipExpiryDaysNotice == undef
773 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
774 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
775 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
777 # Test the before parameter
778 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
779 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
780 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
781 # Test after parameter also
782 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
783 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
784 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
787 subtest 'holds and old_holds' => sub {
790 my $library = $builder->build( { source => 'Branch' } );
791 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
792 my $item_1 = $builder->build(
796 homebranch => $library->{branchcode},
797 holdingbranch => $library->{branchcode},
798 biblionumber => $biblionumber_1
802 my $item_2 = $builder->build(
806 homebranch => $library->{branchcode},
807 holdingbranch => $library->{branchcode},
808 biblionumber => $biblionumber_1
812 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
813 my $item_3 = $builder->build(
817 homebranch => $library->{branchcode},
818 holdingbranch => $library->{branchcode},
819 biblionumber => $biblionumber_2
823 my $patron = $builder->build(
825 source => 'Borrower',
826 value => { branchcode => $library->{branchcode} }
830 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
831 my $holds = $patron->holds;
832 is( ref($holds), 'Koha::Holds',
833 'Koha::Patron->holds should return a Koha::Holds objects' );
834 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
836 C4::Reserves::AddReserve( $library->{branchcode},
837 $patron->borrowernumber, $biblionumber_1 );
839 C4::Reserves::AddReserve( $library->{branchcode},
840 $patron->borrowernumber, $biblionumber_2, undef, undef, dt_from_string->add( days => 2 ) );
842 $holds = $patron->holds;
843 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
845 my $old_holds = $patron->old_holds;
846 is( ref($old_holds), 'Koha::Old::Holds',
847 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
848 is( $old_holds->count, 0, 'There should not be any old holds yet');
850 my $hold = $holds->next;
853 $old_holds = $patron->old_holds;
854 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
861 subtest 'notice_email_address' => sub {
864 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
866 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
867 is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
869 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
870 is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
875 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
878 # TODO create a subroutine in t::lib::Mocks
879 my $branch = $builder->build({ source => 'Branch' });
880 my $userenv_patron = $builder->build_object({
881 class => 'Koha::Patrons',
882 value => { branchcode => $branch->{branchcode}, flags => 0 },
884 t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
886 my $anonymous = $builder->build( { source => 'Borrower', }, );
888 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
890 subtest 'patron privacy is 1 (default)' => sub {
893 t::lib::Mocks::mock_preference('IndependentBranches', 0);
894 my $patron = $builder->build(
895 { source => 'Borrower',
896 value => { privacy => 1, }
899 my $item_1 = $builder->build(
907 my $issue_1 = $builder->build(
910 borrowernumber => $patron->{borrowernumber},
911 itemnumber => $item_1->{itemnumber},
915 my $item_2 = $builder->build(
923 my $issue_2 = $builder->build(
926 borrowernumber => $patron->{borrowernumber},
927 itemnumber => $item_2->{itemnumber},
932 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, dt_from_string('2010-10-10') );
933 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, dt_from_string('2011-11-11') );
934 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
936 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
937 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
939 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
940 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
942 $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
943 is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
945 my $dbh = C4::Context->dbh;
946 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
947 $sth->execute($item_1->{itemnumber});
948 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
949 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
950 $sth->execute($item_2->{itemnumber});
951 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
952 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
954 $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
955 $sth->execute($item_2->{itemnumber});
956 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
957 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
959 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
960 $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
961 $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
962 $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
963 $sth->execute($item_1->{itemnumber});
964 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
965 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
966 $sth->execute($item_2->{itemnumber});
967 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
968 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
970 Koha::Patrons->find( $patron->{borrowernumber})->delete;
973 subtest 'patron privacy is 0 (forever)' => sub {
976 t::lib::Mocks::mock_preference('IndependentBranches', 0);
977 my $patron = $builder->build(
978 { source => 'Borrower',
979 value => { privacy => 0, }
982 my $item = $builder->build(
990 my $issue = $builder->build(
993 borrowernumber => $patron->{borrowernumber},
994 itemnumber => $item->{itemnumber},
999 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1000 is( $returned, 1, 'The item should have been returned' );
1002 my $dbh = C4::Context->dbh;
1003 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1004 SELECT borrowernumber FROM old_issues where itemnumber = ?
1005 |, undef, $item->{itemnumber});
1006 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1007 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1010 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1012 subtest 'AnonymousPatron is not defined' => sub {
1015 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1016 my $patron = $builder->build(
1017 { source => 'Borrower',
1018 value => { privacy => 1, }
1021 my $item = $builder->build(
1029 my $issue = $builder->build(
1030 { source => 'Issue',
1032 borrowernumber => $patron->{borrowernumber},
1033 itemnumber => $item->{itemnumber},
1038 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1039 is( $returned, 1, 'The item should have been returned' );
1040 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
1041 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1043 my $dbh = C4::Context->dbh;
1044 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1045 SELECT borrowernumber FROM old_issues where itemnumber = ?
1046 |, undef, $item->{itemnumber});
1047 is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
1048 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1051 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1053 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1054 my $patron = $builder->build(
1055 { source => 'Borrower',
1056 value => { privacy => 1 } # Another branchcode than the logged in librarian
1059 my $item = $builder->build(
1067 my $issue = $builder->build(
1068 { source => 'Issue',
1070 borrowernumber => $patron->{borrowernumber},
1071 itemnumber => $item->{itemnumber},
1076 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1077 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1078 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1081 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1082 $userenv_patron->delete;
1084 # Reset IndependentBranches for further tests
1085 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1088 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1096 $nb_of_patrons = Koha::Patrons->search->count;
1097 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1098 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1099 my $library_11 = $builder->build( { source => 'Branch' } );
1100 my $library_12 = $builder->build( { source => 'Branch' } );
1101 my $library_21 = $builder->build( { source => 'Branch' } );
1102 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1103 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1104 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1105 Koha::Library::Group->new(
1106 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1107 Koha::Library::Group->new(
1108 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1109 Koha::Library::Group->new(
1110 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1112 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1113 # 2 patrons from library_11 (group1)
1114 # patron_11_1 see patron's infos from outside its group
1115 # Setting flags => undef to not be considered as superlibrarian
1116 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1117 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1118 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1119 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1120 # patron_11_2 can only see patron's info from its group
1121 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1122 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1123 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1124 # 1 patron from library_12 (group1)
1125 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1126 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1127 # 1 patron from library_21 (group2) can only see patron's info from its group
1128 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1129 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1130 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1132 # Pfiou, we can start now!
1133 subtest 'libraries_where_can_see_patrons' => sub {
1138 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1139 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1140 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1142 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1143 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1144 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| );
1146 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1147 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1148 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| );
1150 subtest 'can_see_patron_infos' => sub {
1153 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1154 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1155 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1156 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1158 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1159 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1160 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1161 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1163 subtest 'search_limited' => sub {
1166 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1167 my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1168 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1169 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1171 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1172 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1173 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' );
1175 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1176 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1177 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1179 $patron_11_1->delete;
1180 $patron_11_2->delete;
1185 subtest 'account_locked' => sub {
1187 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1188 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1189 for my $value ( undef, '', 0 ) {
1190 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1191 $patron->login_attempts(0)->store;
1192 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1193 $patron->login_attempts(1)->store;
1194 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1195 $patron->login_attempts(-1)->store;
1196 is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1199 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1200 $patron->login_attempts(2)->store;
1201 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1202 $patron->login_attempts(3)->store;
1203 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1204 $patron->login_attempts(4)->store;
1205 is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1206 $patron->login_attempts(-1)->store;
1207 is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1212 subtest 'is_child | is_adult' => sub {
1214 my $category = $builder->build_object(
1216 class => 'Koha::Patron::Categories',
1217 value => { category_type => 'A' }
1220 my $patron_adult = $builder->build_object(
1222 class => 'Koha::Patrons',
1223 value => { categorycode => $category->categorycode }
1226 $category = $builder->build_object(
1228 class => 'Koha::Patron::Categories',
1229 value => { category_type => 'I' }
1232 my $patron_adult_i = $builder->build_object(
1234 class => 'Koha::Patrons',
1235 value => { categorycode => $category->categorycode }
1238 $category = $builder->build_object(
1240 class => 'Koha::Patron::Categories',
1241 value => { category_type => 'C' }
1244 my $patron_child = $builder->build_object(
1246 class => 'Koha::Patrons',
1247 value => { categorycode => $category->categorycode }
1250 $category = $builder->build_object(
1252 class => 'Koha::Patron::Categories',
1253 value => { category_type => 'O' }
1256 my $patron_other = $builder->build_object(
1258 class => 'Koha::Patrons',
1259 value => { categorycode => $category->categorycode }
1262 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1263 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1264 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1265 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1267 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1268 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1269 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1270 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1273 $patron_adult->delete;
1274 $patron_adult_i->delete;
1275 $patron_child->delete;
1276 $patron_other->delete;
1279 subtest 'get_overdues' => sub {
1282 my $library = $builder->build( { source => 'Branch' } );
1283 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1284 my $item_1 = $builder->build(
1288 homebranch => $library->{branchcode},
1289 holdingbranch => $library->{branchcode},
1290 biblionumber => $biblionumber_1
1294 my $item_2 = $builder->build(
1298 homebranch => $library->{branchcode},
1299 holdingbranch => $library->{branchcode},
1300 biblionumber => $biblionumber_1
1304 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1305 my $item_3 = $builder->build(
1309 homebranch => $library->{branchcode},
1310 holdingbranch => $library->{branchcode},
1311 biblionumber => $biblionumber_2
1315 my $patron = $builder->build(
1317 source => 'Borrower',
1318 value => { branchcode => $library->{branchcode} }
1322 t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1324 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1325 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1326 AddIssue( $patron, $item_3->{barcode} );
1328 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1329 my $overdues = $patron->get_overdues;
1330 is( $overdues->count, 2, 'Patron should have 2 overdues');
1331 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1332 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1334 my $o = $overdues->reset->next;
1335 my $unblessed_overdue = $o->unblessed_all_relateds;
1336 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1337 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1338 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1339 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1342 $patron->checkouts->delete;
1346 subtest 'userid_is_valid' => sub {
1349 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1350 my $patron_category = $builder->build_object(
1352 class => 'Koha::Patron::Categories',
1353 value => { category_type => 'P', enrolmentfee => 0 }
1357 cardnumber => "123456789",
1358 firstname => "Tomasito",
1360 categorycode => $patron_category->categorycode,
1361 branchcode => $library->branchcode,
1364 my $expected_userid_patron_1 = 'tomasito.none';
1365 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1366 my $patron_1 = Koha::Patrons->find($borrowernumber);
1367 is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1368 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1370 $patron_1->userid( 'tomasito.non' );
1371 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1372 1, 'recently created userid -> unique (borrowernumber passed)' );
1374 $patron_1->userid( 'tomasitoxxx' );
1375 is( $patron_1->has_valid_userid,
1376 1, 'non-existent userid -> unique (borrowernumber passed)' );
1377 $patron_1->discard_changes; # We compare with the original userid later
1379 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1380 is( $patron_not_in_storage->has_valid_userid,
1381 0, 'userid exists for another patron, patron is not in storage yet' );
1383 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1384 is( $patron_not_in_storage->has_valid_userid,
1385 1, 'non-existent userid, patron is not in storage yet' );
1387 # Regression tests for BZ12226
1388 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1389 is( $db_patron->has_valid_userid,
1390 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1392 # Add a new borrower with the same userid but different cardnumber
1393 $data{cardnumber} = "987654321";
1394 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1395 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1396 $patron_2->userid($patron_1->userid);
1397 is( $patron_2->has_valid_userid,
1398 0, 'The userid is already in used, it cannot be used for another patron' );
1400 my $new_userid = 'a_user_id';
1401 $data{cardnumber} = "234567890";
1402 $data{userid} = 'a_user_id';
1403 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1404 my $patron_3 = Koha::Patrons->find($borrowernumber);
1405 is( $patron_3->userid, $new_userid,
1406 'Koha::Patron->store should insert the given userid' );
1414 subtest 'generate_userid' => sub {
1417 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1418 my $patron_category = $builder->build_object(
1420 class => 'Koha::Patron::Categories',
1421 value => { category_type => 'P', enrolmentfee => 0 }
1425 cardnumber => "123456789",
1426 firstname => "Tomasito",
1428 categorycode => $patron_category->categorycode,
1429 branchcode => $library->branchcode,
1432 my $expected_userid_patron_1 = 'tomasito.none';
1433 my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1434 $new_patron->generate_userid;
1435 my $userid = $new_patron->userid;
1436 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1437 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1438 my $patron_1 = Koha::Patrons->find($borrowernumber);
1439 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1441 $new_patron->generate_userid;
1442 $userid = $new_patron->userid;
1443 is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1444 $data{cardnumber} = '987654321';
1445 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1446 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1447 isnt( $patron_2->userid, 'tomasito',
1448 "Patron with duplicate userid has new userid generated" );
1449 is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1450 "Patron with duplicate userid has new userid generated (1 is appened" );
1452 $new_patron->generate_userid;
1453 $userid = $new_patron->userid;
1454 is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1456 $patron_1 = Koha::Patrons->find($borrowernumber);
1457 $patron_1->userid(undef);
1458 $patron_1->generate_userid;
1459 $userid = $patron_1->userid;
1460 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1467 subtest 'attributes' => sub {
1470 my $library1 = Koha::Library->new({
1471 branchcode => 'LIBPATRON',
1472 branchname => 'Library of testing patron',
1475 my $library2 = Koha::Library->new({
1476 branchcode => 'LIBATTR',
1477 branchname => 'Library for testing attribute',
1480 my $category = Koha::Patron::Category->new({
1481 categorycode => 'CAT1',
1482 description => 'Category 1',
1485 my $patron = Koha::Patron->new({
1486 firstname => 'Patron',
1487 surname => 'with attributes',
1488 branchcode => 'LIBPATRON',
1489 categorycode => 'CAT1',
1492 my $attribute_type1 = Koha::Patron::Attribute::Type->new({
1494 description => 'Code A desciption',
1497 my $attribute_type2 = Koha::Patron::Attribute::Type->new({
1499 description => 'Code A desciption',
1502 $attribute_type2->library_limits ( [ $library2->branchcode ] );
1504 Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type1->code, attribute => 'value 1' } )->store();
1505 Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type2->code, attribute => 'value 2' } )->store();
1507 is( $patron->attributes->count, 1, 'There should be one attribute');
1509 $attribute_type2->library_limits ( [ $library1->branchcode ] );
1511 is( $patron->attributes->count, 2, 'There should be 2 attributes');
1516 $nb_of_patrons = Koha::Patrons->search->count;
1517 $retrieved_patron_1->delete;
1518 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1520 subtest 'BorrowersLog tests' => sub {
1523 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1524 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1526 my $cardnumber = $patron->cardnumber;
1527 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1530 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1531 my $log_info = from_json( $logs[0]->info );
1532 is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1533 is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1534 is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1536 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1537 $patron->track_login();
1538 @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1539 is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1542 $schema->storage->txn_rollback;
1544 subtest 'Test Koha::Patrons::merge' => sub {
1547 my $schema = Koha::Database->new()->schema();
1549 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1551 $schema->storage->txn_begin;
1553 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1554 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1555 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1557 while (my ($r, $field) = each(%$resultsets)) {
1558 $builder->build({ source => $r, value => { $field => $keeper->id } });
1559 $builder->build({ source => $r, value => { $field => $loser_1 } });
1560 $builder->build({ source => $r, value => { $field => $loser_2 } });
1563 $schema->resultset($r)->search( { $field => $keeper->id } );
1564 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1567 $schema->resultset($r)->search( { $field => $loser_1 } );
1568 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1571 $schema->resultset($r)->search( { $field => $loser_2 } );
1572 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1575 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1577 while (my ($r, $field) = each(%$resultsets)) {
1579 $schema->resultset($r)->search( {$field => $keeper->id } );
1580 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1583 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1584 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1586 $schema->storage->txn_rollback;
1589 subtest '->store' => sub {
1591 my $schema = Koha::Database->new->schema;
1592 $schema->storage->txn_begin;
1594 my $print_error = $schema->storage->dbh->{PrintError};
1595 $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1597 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1598 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1601 { $patron_2->userid($patron_1->userid)->store; }
1602 'Koha::Exceptions::Object::DuplicateID',
1603 'Koha::Patron->store raises an exception on duplicate ID';
1606 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1607 my $password = 'password';
1608 $patron_1->set_password({ password => $password });
1609 like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1610 my $digest = $patron_1->password;
1611 $patron_1->surname('xxx')->store;
1612 is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1614 # Test uppercasesurname
1615 t::lib::Mocks::mock_preference( 'uppercasesurname', 1 );
1616 my $surname = lc $patron_1->surname;
1617 $patron_1->surname($surname)->store;
1618 isnt( $patron_1->surname, $surname,
1619 'Surname converts to uppercase on store.');
1620 t::lib::Mocks::mock_preference( 'uppercasesurname', 0 );
1621 $patron_1->surname($surname)->store;
1622 is( $patron_1->surname, $surname,
1623 'Surname remains unchanged on store.');
1625 $schema->storage->dbh->{PrintError} = $print_error;
1626 $schema->storage->txn_rollback;
1629 subtest '->set_password' => sub {
1633 $schema->storage->txn_begin;
1635 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1637 # Disable logging password changes for this tests
1638 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1640 # Password-length tests
1641 t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1642 throws_ok { $patron->set_password({ password => 'ab' }); }
1643 'Koha::Exceptions::Password::TooShort',
1644 'minPasswordLength is undef, fall back to 3, fail test';
1646 'Password length (2) is shorter than required (3)',
1647 'Exception parameters passed correctly'
1650 t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1651 throws_ok { $patron->set_password({ password => 'ab' }); }
1652 'Koha::Exceptions::Password::TooShort',
1653 'minPasswordLength is 2, fall back to 3, fail test';
1655 t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1656 throws_ok { $patron->set_password({ password => 'abcb' }); }
1657 'Koha::Exceptions::Password::TooShort',
1658 'minPasswordLength is 5, fail test';
1660 # Trailing spaces tests
1661 throws_ok { $patron->set_password({ password => 'abcD12d ' }); }
1662 'Koha::Exceptions::Password::WhitespaceCharacters',
1663 'Password contains trailing spaces, exception is thrown';
1665 # Require strong password tests
1666 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1667 throws_ok { $patron->set_password({ password => 'abcd a' }); }
1668 'Koha::Exceptions::Password::TooWeak',
1669 'Password is too weak, exception is thrown';
1671 # Refresh patron from DB, just to make sure
1672 $patron->discard_changes;
1673 is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1675 $patron->set_password({ password => 'abcD12 34' });
1676 $patron->discard_changes;
1678 is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1680 lives_ok { $patron->set_password({ password => 'abcd a', skip_validation => 1 }) }
1681 'Password is weak, but skip_validation was passed, so no exception thrown';
1684 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1685 $patron->login_attempts(3)->store;
1686 my $old_digest = $patron->password;
1687 $patron->set_password({ password => 'abcd a' });
1688 $patron->discard_changes;
1690 isnt( $patron->password, $old_digest, 'Password has been updated' );
1691 ok( checkpw_hash('abcd a', $patron->password), 'Password hash is correct' );
1692 is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1694 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1695 is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1697 # Enable logging password changes
1698 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1699 $patron->set_password({ password => 'abcd b' });
1701 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1702 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1704 $schema->storage->txn_rollback;
1707 $schema->storage->txn_begin;
1708 subtest 'search_unsubscribed' => sub {
1711 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1712 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
1713 is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
1715 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1716 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1718 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
1719 Koha::Patron::Consents->delete; # for correct counts
1720 Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string })->store;
1721 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
1723 # Add another refusal but shift the period
1724 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
1725 Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string->subtract(days=>2) })->store;
1726 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
1728 # Try another (special) attempts setting
1729 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
1730 # Lockout is now disabled
1731 # Patron2 still matches: refused earlier, not locked
1732 is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
1735 subtest 'search_anonymize_candidates' => sub {
1737 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1738 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1739 $patron1->anonymized(0);
1740 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1741 $patron2->anonymized(0);
1742 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1744 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
1745 is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
1747 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
1748 my $cnt = Koha::Patrons->search_anonymize_candidates->count;
1749 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1750 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1751 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
1753 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
1754 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1755 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1756 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1757 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1758 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1759 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
1761 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
1762 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1763 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1764 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1765 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1766 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1767 is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
1769 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1770 $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1771 $patron1->login_attempts(0)->store;
1772 $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1773 $patron2->login_attempts(0)->store;
1774 $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
1775 $patron1->login_attempts(3)->store;
1776 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1777 $cnt+1, 'Locked flag' );
1780 subtest 'search_anonymized' => sub {
1782 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1784 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
1785 is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
1787 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
1788 $patron1->dateexpiry( dt_from_string );
1789 $patron1->anonymized(0)->store;
1790 my $cnt = Koha::Patrons->search_anonymized->count;
1791 $patron1->anonymized(1)->store;
1792 is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
1793 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1794 is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
1797 subtest 'lock' => sub {
1800 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1801 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1802 my $hold = $builder->build_object({
1803 class => 'Koha::Holds',
1804 value => { borrowernumber => $patron1->borrowernumber },
1807 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1808 my $expiry = dt_from_string->add(days => 1);
1809 $patron1->dateexpiry( $expiry );
1811 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1812 is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
1813 is( $patron1->holds->count, 1, 'No holds removed' );
1815 $patron1->lock({ expire => 1, remove => 1});
1816 isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
1817 is( $patron1->holds->count, 0, 'Holds removed' );
1819 # Disable lockout feature
1820 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1821 $patron1->login_attempts(0);
1822 $patron1->dateexpiry( $expiry );
1825 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1827 # Trivial wrapper test (Koha::Patrons->lock)
1828 $patron1->login_attempts(0)->store;
1829 Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
1830 $patron1->discard_changes; # refresh
1831 $patron2->discard_changes;
1832 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
1833 is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
1836 subtest 'anonymize' => sub {
1839 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1840 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1842 # First try patron with issues
1843 my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
1844 warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
1847 t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
1848 my $surname = $patron1->surname; # expect change, no clear
1849 my $branchcode = $patron1->branchcode; # expect skip
1850 $patron1->anonymize;
1851 is($patron1->anonymized, 1, 'Check flag' );
1853 is( $patron1->dateofbirth, undef, 'Birth date cleared' );
1854 is( $patron1->firstname, undef, 'First name cleared' );
1855 isnt( $patron1->surname, $surname, 'Surname changed' );
1856 ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
1857 is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
1858 is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
1860 # Test wrapper in Koha::Patrons
1861 $patron1->surname($surname)->store; # restore
1862 my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
1863 $patron1->discard_changes; # refresh
1864 isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
1865 $patron2->discard_changes; # refresh
1866 is( $patron2->firstname, undef, 'First name patron2 cleared' );
1868 $schema->storage->txn_rollback;