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 => 39;
33 use C4::Auth qw(checkpw_hash);
38 use Koha::Patron::Categories;
41 use Koha::Virtualshelves;
43 use t::lib::TestBuilder;
46 my $schema = Koha::Database->new->schema;
47 $schema->storage->txn_begin;
49 my $builder = t::lib::TestBuilder->new;
50 my $library = $builder->build({source => 'Branch' });
51 my $category = $builder->build({source => 'Category' });
52 my $nb_of_patrons = Koha::Patrons->search->count;
53 my $new_patron_1 = Koha::Patron->new(
54 { cardnumber => 'test_cn_1',
55 branchcode => $library->{branchcode},
56 categorycode => $category->{categorycode},
57 surname => 'surname for patron1',
58 firstname => 'firstname for patron1',
59 userid => 'a_nonexistent_userid_1',
60 flags => 1, # Is superlibrarian
63 my $new_patron_2 = Koha::Patron->new(
64 { cardnumber => 'test_cn_2',
65 branchcode => $library->{branchcode},
66 categorycode => $category->{categorycode},
67 surname => 'surname for patron2',
68 firstname => 'firstname for patron2',
69 userid => 'a_nonexistent_userid_2',
73 t::lib::Mocks::mock_userenv({ patron => $new_patron_1 });
75 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
77 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
78 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
80 subtest 'library' => sub {
82 is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
83 is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
86 subtest 'guarantees' => sub {
88 my $guarantees = $new_patron_1->guarantees;
89 is( ref($guarantees), 'Koha::Patrons', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
90 is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee' );
91 my @guarantees = $new_patron_1->guarantees;
92 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantees should return an array in a list context' );
93 is( scalar(@guarantees), 0, 'new_patron_1 should have 0 guarantee' );
95 my $guarantee_1 = $builder->build({ source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber }});
96 my $guarantee_2 = $builder->build({ source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber }});
98 $guarantees = $new_patron_1->guarantees;
99 is( ref($guarantees), 'Koha::Patrons', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
100 is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
101 @guarantees = $new_patron_1->guarantees;
102 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantees should return an array in a list context' );
103 is( scalar(@guarantees), 2, 'new_patron_1 should have 2 guarantees' );
104 $_->delete for @guarantees;
106 #Test return order of guarantees BZ 18635
107 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
108 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
110 my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
112 my $order_guarantee1 = $builder->build_object( { class => 'Koha::Patrons' , value => {
114 guarantorid => $guarantor->borrowernumber
118 my $order_guarantee2 = $builder->build_object( { class => 'Koha::Patrons' , value => {
120 guarantorid => $guarantor->borrowernumber
124 my $order_guarantee3 = $builder->build_object( { class => 'Koha::Patrons' , value => {
126 firstname => 'Walrus',
127 guarantorid => $guarantor->borrowernumber
131 my $order_guarantee4 = $builder->build_object( { class => 'Koha::Patrons' , value => {
133 firstname => 'Vulture',
134 guarantorid => $guarantor->borrowernumber
138 my $order_guarantee5 = $builder->build_object( { class => 'Koha::Patrons' , value => {
140 firstname => 'Unicorn',
141 guarantorid => $guarantor->borrowernumber
145 $guarantees = $guarantor->guarantees();
147 is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
148 is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
149 is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
150 is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
151 is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
154 subtest 'category' => sub {
156 my $patron_category = $new_patron_1->category;
157 is( ref( $patron_category), 'Koha::Patron::Category', );
158 is( $patron_category->categorycode, $category->{categorycode}, );
161 subtest 'siblings' => sub {
163 my $siblings = $new_patron_1->siblings;
164 is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
165 my $guarantee_1 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
166 my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
167 $siblings = $retrieved_guarantee_1->siblings;
168 is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
169 my @siblings = $retrieved_guarantee_1->siblings;
170 is( ref( \@siblings ), 'ARRAY', 'Koha::Patron->siblings should return an array in a list context' );
171 is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' );
172 my $guarantee_2 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
173 my $guarantee_3 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
174 $siblings = $retrieved_guarantee_1->siblings;
175 is( $siblings->count, 2, 'guarantee_1 should have 2 siblings' );
176 is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
177 is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
178 $_->delete for $retrieved_guarantee_1->siblings;
179 $retrieved_guarantee_1->delete;
182 subtest 'has_overdues' => sub {
185 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
186 my $item_1 = $builder->build(
189 homebranch => $library->{branchcode},
190 holdingbranch => $library->{branchcode},
194 biblionumber => $biblioitem_1->{biblionumber}
198 my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
199 is( $retrieved_patron->has_overdues, 0, );
201 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
202 my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
203 is( $retrieved_patron->has_overdues, 0, );
205 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
206 $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
207 $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
208 is( $retrieved_patron->has_overdues, 1, );
212 subtest 'is_expired' => sub {
214 my $patron = $builder->build({ source => 'Borrower' });
215 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
216 $patron->dateexpiry( undef )->store->discard_changes;
217 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
218 $patron->dateexpiry( dt_from_string )->store->discard_changes;
219 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
220 $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
221 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
222 $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
223 is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
228 subtest 'is_going_to_expire' => sub {
231 my $today = dt_from_string(undef, undef, 'floating');
232 my $patron = $builder->build({ source => 'Borrower' });
233 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
234 $patron->dateexpiry( undef )->store->discard_changes;
235 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
237 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
238 $patron->dateexpiry( $today )->store->discard_changes;
239 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
241 $patron->dateexpiry( $today )->store->discard_changes;
242 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
244 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
245 $patron->dateexpiry( $today->clone->add( days => 11 ) )->store->discard_changes;
246 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');
248 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
249 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
250 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');
252 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
253 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
254 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');
257 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
258 $patron->dateexpiry( $today->clone->add( days => 20 ) )->store->discard_changes;
259 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');
261 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
262 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
263 is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
265 { # Testing invalid is going to expiry date
266 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 30);
267 # mock_config does not work here, because of tz vs timezone subroutines
268 my $context = new Test::MockModule('C4::Context');
269 $context->mock( 'tz', sub {
272 $patron->dateexpiry(DateTime->new( year => 2019, month => 12, day => 3 ))->store;
273 eval { $patron->is_going_to_expire };
274 is( $@, '', 'On invalid "is going to expire" date, the method should not crash with "Invalid local time for date in time zone"');
275 $context->unmock('tz');
282 subtest 'renew_account' => sub {
285 for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
286 my $dt = dt_from_string( $date, 'iso' );
287 Time::Fake->offset( $dt->epoch );
288 my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
289 my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
290 my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
291 my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
292 my $a_year_later_plus_a_month = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
293 my $patron_category = $builder->build(
294 { source => 'Category',
296 enrolmentperiod => 12,
297 enrolmentperioddate => undef,
301 my $patron = $builder->build(
302 { source => 'Borrower',
304 dateexpiry => $a_month_ago,
305 categorycode => $patron_category->{categorycode},
306 date_renewed => undef, # Force builder to not populate the column for new patron
310 my $patron_2 = $builder->build(
311 { source => 'Borrower',
313 dateexpiry => $a_month_ago,
314 categorycode => $patron_category->{categorycode},
318 my $patron_3 = $builder->build(
319 { source => 'Borrower',
321 dateexpiry => $a_month_later,
322 categorycode => $patron_category->{categorycode},
326 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
327 my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
328 my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
330 is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
332 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
333 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
334 my $expiry_date = $retrieved_patron->renew_account;
335 is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
336 my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
337 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" );
338 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
339 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
341 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
342 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
343 $expiry_date = $retrieved_patron->renew_account;
344 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
345 $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
346 is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
347 $retrieved_expiry_date = $retrieved_patron->dateexpiry;
348 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
349 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
350 is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
352 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
353 $expiry_date = $retrieved_patron_2->renew_account;
354 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
355 $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
356 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
358 $expiry_date = $retrieved_patron_3->renew_account;
359 is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
360 $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
361 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" );
363 $retrieved_patron->delete;
364 $retrieved_patron_2->delete;
365 $retrieved_patron_3->delete;
370 subtest "move_to_deleted" => sub {
372 my $originally_updated_on = '2016-01-01 12:12:12';
373 my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
374 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
375 is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
376 ; # FIXME This should be Koha::Deleted::Patron
377 my $deleted_patron = $schema->resultset('Deletedborrower')
378 ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
380 ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
381 ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
382 isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
383 $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
384 is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
385 $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup
388 subtest "delete" => sub {
390 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
391 my $patron = $builder->build( { source => 'Borrower' } );
392 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
393 my $hold = $builder->build(
394 { source => 'Reserve',
395 value => { borrowernumber => $patron->{borrowernumber} }
398 my $list = $builder->build(
399 { source => 'Virtualshelve',
400 value => { owner => $patron->{borrowernumber} }
404 my $deleted = $retrieved_patron->delete;
405 is( $deleted, 1, 'Koha::Patron->delete should return 1 if the patron has been correctly deleted' );
407 is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
409 is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's holds| );
411 is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
413 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
414 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
417 subtest 'Koha::Patrons->delete' => sub {
420 my $mod_patron = Test::MockModule->new( 'Koha::Patron' );
421 my $moved_to_deleted = 0;
422 $mod_patron->mock( 'move_to_deleted', sub { $moved_to_deleted++; } );
424 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
425 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
426 my $id1 = $patron1->borrowernumber;
427 my $set = Koha::Patrons->search({ borrowernumber => { '>=' => $id1 }});
428 is( $set->count, 2, 'Two patrons found as expected' );
429 is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
430 is( $moved_to_deleted, 2, 'Patrons moved to deletedborrowers' );
432 # Add again, test if we can raise an exception
433 $mod_patron->mock( 'delete', sub { return -1; } );
434 $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
435 $id1 = $patron1->borrowernumber;
436 $set = Koha::Patrons->search({ borrowernumber => { '>=' => $id1 }});
437 throws_ok { $set->delete } 'Koha::Exceptions::Patron::FailedDelete',
438 'Exception raised for deleting patron';
441 subtest 'add_enrolment_fee_if_needed' => sub {
444 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
445 foreach( keys %{$enrolmentfees} ) {
446 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
448 my $enrolmentfee_K = $enrolmentfees->{K};
449 my $enrolmentfee_J = $enrolmentfees->{J};
450 my $enrolmentfee_YA = $enrolmentfees->{YA};
452 my %borrower_data = (
453 firstname => 'my firstname',
454 surname => 'my surname',
456 branchcode => $library->{branchcode},
459 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
460 $borrower_data{borrowernumber} = $borrowernumber;
462 my $patron = Koha::Patrons->find( $borrowernumber );
463 my $total = $patron->account->balance;
464 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
466 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
467 $borrower_data{categorycode} = 'J';
468 $patron->set(\%borrower_data)->store;
469 $total = $patron->account->balance;
470 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
472 $borrower_data{categorycode} = 'K';
473 $patron->set(\%borrower_data)->store;
474 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
476 $borrower_data{categorycode} = 'J';
477 $patron->set(\%borrower_data)->store;
478 $total = $patron->account->balance;
479 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
481 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
482 $patron->categorycode('YA')->store;
483 $total = $patron->account->balance;
485 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
486 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
492 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
495 my $library = $builder->build( { source => 'Branch' } );
496 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
497 my $item_1 = $builder->build(
501 homebranch => $library->{branchcode},
502 holdingbranch => $library->{branchcode},
503 biblionumber => $biblionumber_1,
509 my $item_2 = $builder->build(
513 homebranch => $library->{branchcode},
514 holdingbranch => $library->{branchcode},
515 biblionumber => $biblionumber_1,
521 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
522 my $item_3 = $builder->build(
526 homebranch => $library->{branchcode},
527 holdingbranch => $library->{branchcode},
528 biblionumber => $biblionumber_2,
534 my $patron = $builder->build(
536 source => 'Borrower',
537 value => { branchcode => $library->{branchcode} }
541 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
542 my $checkouts = $patron->checkouts;
543 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
544 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
545 my $pending_checkouts = $patron->pending_checkouts;
546 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
547 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
548 my $old_checkouts = $patron->old_checkouts;
549 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
550 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
552 # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
553 $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
555 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
557 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
558 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
559 AddIssue( $patron, $item_3->{barcode} );
561 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
562 $checkouts = $patron->checkouts;
563 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
564 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
565 $pending_checkouts = $patron->pending_checkouts;
566 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
567 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
569 my $first_checkout = $pending_checkouts->next;
570 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
572 my $overdues = $patron->get_overdues;
573 is( $overdues->count, 2, 'Patron should have 2 overdues');
574 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
575 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
576 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
579 C4::Circulation::AddReturn( $item_1->{barcode} );
580 C4::Circulation::AddReturn( $item_2->{barcode} );
581 $old_checkouts = $patron->old_checkouts;
582 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
583 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
586 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
590 subtest 'get_routing_lists' => sub {
593 my $biblio = Koha::Biblio->new()->store();
594 my $subscription = Koha::Subscription->new({
595 biblionumber => $biblio->biblionumber,
599 my $patron = $builder->build( { source => 'Borrower' } );
600 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
602 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
604 my $routinglist_count = Koha::Subscription::Routinglists->count;
605 my $routinglist = Koha::Subscription::Routinglist->new({
606 borrowernumber => $patron->borrowernumber,
608 subscriptionid => $subscription->subscriptionid
611 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
613 my $routinglists = $patron->get_routing_lists;
614 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
615 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
617 my $subscription2 = Koha::Subscription->new({
618 biblionumber => $biblio->biblionumber,
621 my $routinglist2 = Koha::Subscription::Routinglist->new({
622 borrowernumber => $patron->borrowernumber,
624 subscriptionid => $subscription2->subscriptionid
627 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
629 $patron->delete; # Clean up for later tests
633 subtest 'get_age' => sub {
636 my $patron = $builder->build( { source => 'Borrower' } );
637 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
639 my $today = dt_from_string;
641 $patron->dateofbirth( undef );
642 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
643 $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1, end_of_month => 'limit' ) );
644 is( $patron->get_age, 12, 'Patron should be 12' );
645 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 1, end_of_month => 'limit' ) );
646 is( $patron->get_age, 17, 'Patron should be 17, happy birthday tomorrow!' );
647 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 0, end_of_month => 'limit' ) );
648 is( $patron->get_age, 18, 'Patron should be 18' );
649 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -31, end_of_month => 'limit' ) );
650 is( $patron->get_age, 19, 'Patron should be 19' );
651 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -30, end_of_month => 'limit' ) );
652 is( $patron->get_age, 19, 'Patron should be 19 again' );
653 $patron->dateofbirth( $today->clone->add( years => 0, months => -1, days => -1, end_of_month => 'limit' ) );
654 is( $patron->get_age, 0, 'Patron is a newborn child' );
659 subtest 'account' => sub {
662 my $patron = $builder->build({source => 'Borrower'});
664 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
665 my $account = $patron->account;
666 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
671 subtest 'search_upcoming_membership_expires' => sub {
674 my $expiry_days = 15;
675 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
676 my $nb_of_days_before = 1;
677 my $nb_of_days_after = 2;
679 my $builder = t::lib::TestBuilder->new();
681 my $library = $builder->build({ source => 'Branch' });
683 # before we add borrowers to this branch, add the expires we have now
684 # note that this pertains to the current mocked setting of the pref
685 # for this reason we add the new branchcode to most of the tests
686 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
688 my $patron_1 = $builder->build({
689 source => 'Borrower',
691 branchcode => $library->{branchcode},
692 dateexpiry => dt_from_string->add( days => $expiry_days )
696 my $patron_2 = $builder->build({
697 source => 'Borrower',
699 branchcode => $library->{branchcode},
700 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
704 my $patron_3 = $builder->build({
705 source => 'Borrower',
707 branchcode => $library->{branchcode},
708 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
712 # Test without extra parameters
713 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
714 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
717 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
718 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
719 my $expired = $upcoming_mem_expires->next;
720 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
721 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
722 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
724 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
725 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
726 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
728 # Test MembershipExpiryDaysNotice == undef
729 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
730 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
731 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
733 # Test the before parameter
734 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
735 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
736 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
737 # Test after parameter also
738 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
739 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
740 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
743 subtest 'holds and old_holds' => sub {
746 my $library = $builder->build( { source => 'Branch' } );
747 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
748 my $item_1 = $builder->build(
752 homebranch => $library->{branchcode},
753 holdingbranch => $library->{branchcode},
754 biblionumber => $biblionumber_1
758 my $item_2 = $builder->build(
762 homebranch => $library->{branchcode},
763 holdingbranch => $library->{branchcode},
764 biblionumber => $biblionumber_1
768 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
769 my $item_3 = $builder->build(
773 homebranch => $library->{branchcode},
774 holdingbranch => $library->{branchcode},
775 biblionumber => $biblionumber_2
779 my $patron = $builder->build(
781 source => 'Borrower',
782 value => { branchcode => $library->{branchcode} }
786 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
787 my $holds = $patron->holds;
788 is( ref($holds), 'Koha::Holds',
789 'Koha::Patron->holds should return a Koha::Holds objects' );
790 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
792 C4::Reserves::AddReserve( $library->{branchcode},
793 $patron->borrowernumber, $biblionumber_1 );
795 C4::Reserves::AddReserve( $library->{branchcode},
796 $patron->borrowernumber, $biblionumber_2, undef, undef, dt_from_string->add( days => 2 ) );
798 $holds = $patron->holds;
799 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
801 my $old_holds = $patron->old_holds;
802 is( ref($old_holds), 'Koha::Old::Holds',
803 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
804 is( $old_holds->count, 0, 'There should not be any old holds yet');
806 my $hold = $holds->next;
809 $old_holds = $patron->old_holds;
810 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
817 subtest 'notice_email_address' => sub {
820 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
822 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
823 is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
825 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
826 is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
831 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
834 # TODO create a subroutine in t::lib::Mocks
835 my $branch = $builder->build({ source => 'Branch' });
836 my $userenv_patron = $builder->build_object({
837 class => 'Koha::Patrons',
838 value => { branchcode => $branch->{branchcode}, flags => 0 },
840 t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
842 my $anonymous = $builder->build( { source => 'Borrower', }, );
844 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
846 subtest 'patron privacy is 1 (default)' => sub {
849 t::lib::Mocks::mock_preference('IndependentBranches', 0);
850 my $patron = $builder->build(
851 { source => 'Borrower',
852 value => { privacy => 1, }
855 my $item_1 = $builder->build(
863 my $issue_1 = $builder->build(
866 borrowernumber => $patron->{borrowernumber},
867 itemnumber => $item_1->{itemnumber},
871 my $item_2 = $builder->build(
879 my $issue_2 = $builder->build(
882 borrowernumber => $patron->{borrowernumber},
883 itemnumber => $item_2->{itemnumber},
888 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, dt_from_string('2010-10-10') );
889 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, dt_from_string('2011-11-11') );
890 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
892 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
893 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
895 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
896 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
898 $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
899 is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
901 my $dbh = C4::Context->dbh;
902 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
903 $sth->execute($item_1->{itemnumber});
904 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
905 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
906 $sth->execute($item_2->{itemnumber});
907 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
908 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
910 $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
911 $sth->execute($item_2->{itemnumber});
912 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
913 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
915 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
916 $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
917 $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
918 $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
919 $sth->execute($item_1->{itemnumber});
920 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
921 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
922 $sth->execute($item_2->{itemnumber});
923 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
924 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
926 Koha::Patrons->find( $patron->{borrowernumber})->delete;
929 subtest 'patron privacy is 0 (forever)' => sub {
932 t::lib::Mocks::mock_preference('IndependentBranches', 0);
933 my $patron = $builder->build(
934 { source => 'Borrower',
935 value => { privacy => 0, }
938 my $item = $builder->build(
946 my $issue = $builder->build(
949 borrowernumber => $patron->{borrowernumber},
950 itemnumber => $item->{itemnumber},
955 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
956 is( $returned, 1, 'The item should have been returned' );
958 my $dbh = C4::Context->dbh;
959 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
960 SELECT borrowernumber FROM old_issues where itemnumber = ?
961 |, undef, $item->{itemnumber});
962 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
963 Koha::Patrons->find( $patron->{borrowernumber})->delete;
966 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
968 subtest 'AnonymousPatron is not defined' => sub {
971 t::lib::Mocks::mock_preference('IndependentBranches', 0);
972 my $patron = $builder->build(
973 { source => 'Borrower',
974 value => { privacy => 1, }
977 my $item = $builder->build(
985 my $issue = $builder->build(
988 borrowernumber => $patron->{borrowernumber},
989 itemnumber => $item->{itemnumber},
994 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
995 is( $returned, 1, 'The item should have been returned' );
996 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
997 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
999 my $dbh = C4::Context->dbh;
1000 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1001 SELECT borrowernumber FROM old_issues where itemnumber = ?
1002 |, undef, $item->{itemnumber});
1003 is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
1004 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1007 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1009 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1010 my $patron = $builder->build(
1011 { source => 'Borrower',
1012 value => { privacy => 1 } # Another branchcode than the logged in librarian
1015 my $item = $builder->build(
1023 my $issue = $builder->build(
1024 { source => 'Issue',
1026 borrowernumber => $patron->{borrowernumber},
1027 itemnumber => $item->{itemnumber},
1032 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1033 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1034 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1037 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1038 $userenv_patron->delete;
1040 # Reset IndependentBranches for further tests
1041 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1044 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1052 $nb_of_patrons = Koha::Patrons->search->count;
1053 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1054 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1055 my $library_11 = $builder->build( { source => 'Branch' } );
1056 my $library_12 = $builder->build( { source => 'Branch' } );
1057 my $library_21 = $builder->build( { source => 'Branch' } );
1058 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1059 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1060 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1061 Koha::Library::Group->new(
1062 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1063 Koha::Library::Group->new(
1064 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1065 Koha::Library::Group->new(
1066 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1068 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1069 # 2 patrons from library_11 (group1)
1070 # patron_11_1 see patron's infos from outside its group
1071 # Setting flags => undef to not be considered as superlibrarian
1072 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1073 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1074 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1075 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1076 # patron_11_2 can only see patron's info from its group
1077 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1078 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1079 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1080 # 1 patron from library_12 (group1)
1081 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1082 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1083 # 1 patron from library_21 (group2) can only see patron's info from its group
1084 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1085 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1086 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1088 # Pfiou, we can start now!
1089 subtest 'libraries_where_can_see_patrons' => sub {
1094 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1095 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1096 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1098 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1099 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1100 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| );
1102 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1103 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1104 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| );
1106 subtest 'can_see_patron_infos' => sub {
1109 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1110 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1111 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1112 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1114 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1115 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1116 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1117 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1119 subtest 'search_limited' => sub {
1122 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1123 my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1124 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1125 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1127 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1128 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1129 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' );
1131 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1132 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1133 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1135 $patron_11_1->delete;
1136 $patron_11_2->delete;
1141 subtest 'account_locked' => sub {
1143 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1144 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1145 for my $value ( undef, '', 0 ) {
1146 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1147 $patron->login_attempts(0)->store;
1148 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1149 $patron->login_attempts(1)->store;
1150 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1151 $patron->login_attempts(-1)->store;
1152 is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1155 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1156 $patron->login_attempts(2)->store;
1157 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1158 $patron->login_attempts(3)->store;
1159 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1160 $patron->login_attempts(4)->store;
1161 is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1162 $patron->login_attempts(-1)->store;
1163 is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1168 subtest 'is_child | is_adult' => sub {
1170 my $category = $builder->build_object(
1172 class => 'Koha::Patron::Categories',
1173 value => { category_type => 'A' }
1176 my $patron_adult = $builder->build_object(
1178 class => 'Koha::Patrons',
1179 value => { categorycode => $category->categorycode }
1182 $category = $builder->build_object(
1184 class => 'Koha::Patron::Categories',
1185 value => { category_type => 'I' }
1188 my $patron_adult_i = $builder->build_object(
1190 class => 'Koha::Patrons',
1191 value => { categorycode => $category->categorycode }
1194 $category = $builder->build_object(
1196 class => 'Koha::Patron::Categories',
1197 value => { category_type => 'C' }
1200 my $patron_child = $builder->build_object(
1202 class => 'Koha::Patrons',
1203 value => { categorycode => $category->categorycode }
1206 $category = $builder->build_object(
1208 class => 'Koha::Patron::Categories',
1209 value => { category_type => 'O' }
1212 my $patron_other = $builder->build_object(
1214 class => 'Koha::Patrons',
1215 value => { categorycode => $category->categorycode }
1218 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1219 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1220 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1221 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1223 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1224 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1225 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1226 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1229 $patron_adult->delete;
1230 $patron_adult_i->delete;
1231 $patron_child->delete;
1232 $patron_other->delete;
1235 subtest 'get_overdues' => sub {
1238 my $library = $builder->build( { source => 'Branch' } );
1239 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1240 my $item_1 = $builder->build(
1244 homebranch => $library->{branchcode},
1245 holdingbranch => $library->{branchcode},
1246 biblionumber => $biblionumber_1
1250 my $item_2 = $builder->build(
1254 homebranch => $library->{branchcode},
1255 holdingbranch => $library->{branchcode},
1256 biblionumber => $biblionumber_1
1260 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1261 my $item_3 = $builder->build(
1265 homebranch => $library->{branchcode},
1266 holdingbranch => $library->{branchcode},
1267 biblionumber => $biblionumber_2
1271 my $patron = $builder->build(
1273 source => 'Borrower',
1274 value => { branchcode => $library->{branchcode} }
1278 t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1280 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1281 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1282 AddIssue( $patron, $item_3->{barcode} );
1284 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1285 my $overdues = $patron->get_overdues;
1286 is( $overdues->count, 2, 'Patron should have 2 overdues');
1287 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1288 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1290 my $o = $overdues->reset->next;
1291 my $unblessed_overdue = $o->unblessed_all_relateds;
1292 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1293 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1294 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1295 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1298 $patron->checkouts->delete;
1302 subtest 'userid_is_valid' => sub {
1305 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1306 my $patron_category = $builder->build_object(
1308 class => 'Koha::Patron::Categories',
1309 value => { category_type => 'P', enrolmentfee => 0 }
1313 cardnumber => "123456789",
1314 firstname => "Tomasito",
1316 categorycode => $patron_category->categorycode,
1317 branchcode => $library->branchcode,
1320 my $expected_userid_patron_1 = 'tomasito.none';
1321 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1322 my $patron_1 = Koha::Patrons->find($borrowernumber);
1323 is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1324 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1326 $patron_1->userid( 'tomasito.non' );
1327 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1328 1, 'recently created userid -> unique (borrowernumber passed)' );
1330 $patron_1->userid( 'tomasitoxxx' );
1331 is( $patron_1->has_valid_userid,
1332 1, 'non-existent userid -> unique (borrowernumber passed)' );
1333 $patron_1->discard_changes; # We compare with the original userid later
1335 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1336 is( $patron_not_in_storage->has_valid_userid,
1337 0, 'userid exists for another patron, patron is not in storage yet' );
1339 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1340 is( $patron_not_in_storage->has_valid_userid,
1341 1, 'non-existent userid, patron is not in storage yet' );
1343 # Regression tests for BZ12226
1344 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1345 is( $db_patron->has_valid_userid,
1346 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1348 # Add a new borrower with the same userid but different cardnumber
1349 $data{cardnumber} = "987654321";
1350 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1351 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1352 $patron_2->userid($patron_1->userid);
1353 is( $patron_2->has_valid_userid,
1354 0, 'The userid is already in used, it cannot be used for another patron' );
1356 my $new_userid = 'a_user_id';
1357 $data{cardnumber} = "234567890";
1358 $data{userid} = 'a_user_id';
1359 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1360 my $patron_3 = Koha::Patrons->find($borrowernumber);
1361 is( $patron_3->userid, $new_userid,
1362 'Koha::Patron->store should insert the given userid' );
1370 subtest 'generate_userid' => sub {
1373 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1374 my $patron_category = $builder->build_object(
1376 class => 'Koha::Patron::Categories',
1377 value => { category_type => 'P', enrolmentfee => 0 }
1381 cardnumber => "123456789",
1382 firstname => "Tomasito",
1384 categorycode => $patron_category->categorycode,
1385 branchcode => $library->branchcode,
1388 my $expected_userid_patron_1 = 'tomasito.none';
1389 my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1390 $new_patron->generate_userid;
1391 my $userid = $new_patron->userid;
1392 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1393 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1394 my $patron_1 = Koha::Patrons->find($borrowernumber);
1395 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1397 $new_patron->generate_userid;
1398 $userid = $new_patron->userid;
1399 is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1400 $data{cardnumber} = '987654321';
1401 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1402 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1403 isnt( $patron_2->userid, 'tomasito',
1404 "Patron with duplicate userid has new userid generated" );
1405 is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1406 "Patron with duplicate userid has new userid generated (1 is appened" );
1408 $new_patron->generate_userid;
1409 $userid = $new_patron->userid;
1410 is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1412 $patron_1 = Koha::Patrons->find($borrowernumber);
1413 $patron_1->userid(undef);
1414 $patron_1->generate_userid;
1415 $userid = $patron_1->userid;
1416 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1423 subtest 'attributes' => sub {
1426 my $library1 = Koha::Library->new({
1427 branchcode => 'LIBPATRON',
1428 branchname => 'Library of testing patron',
1431 my $library2 = Koha::Library->new({
1432 branchcode => 'LIBATTR',
1433 branchname => 'Library for testing attribute',
1436 my $category = Koha::Patron::Category->new({
1437 categorycode => 'CAT1',
1438 description => 'Category 1',
1441 my $patron = Koha::Patron->new({
1442 firstname => 'Patron',
1443 surname => 'with attributes',
1444 branchcode => 'LIBPATRON',
1445 categorycode => 'CAT1',
1448 my $attribute_type1 = Koha::Patron::Attribute::Type->new({
1450 description => 'Code A desciption',
1453 my $attribute_type2 = Koha::Patron::Attribute::Type->new({
1455 description => 'Code A desciption',
1458 $attribute_type2->library_limits ( [ $library2->branchcode ] );
1460 Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type1->code, attribute => 'value 1' } )->store();
1461 Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type2->code, attribute => 'value 2' } )->store();
1463 is( $patron->attributes->count, 1, 'There should be one attribute');
1465 $attribute_type2->library_limits ( [ $library1->branchcode ] );
1467 is( $patron->attributes->count, 2, 'There should be 2 attributes');
1472 $nb_of_patrons = Koha::Patrons->search->count;
1473 $retrieved_patron_1->delete;
1474 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1476 subtest 'BorrowersLog tests' => sub {
1479 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1480 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1482 my $cardnumber = $patron->cardnumber;
1483 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1486 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1487 my $log_info = from_json( $logs[0]->info );
1488 is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1489 is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1490 is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1492 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1493 $patron->track_login();
1494 @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1495 is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1498 $schema->storage->txn_rollback;
1500 subtest 'Test Koha::Patrons::merge' => sub {
1503 my $schema = Koha::Database->new()->schema();
1505 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1507 $schema->storage->txn_begin;
1509 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1510 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1511 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1513 while (my ($r, $field) = each(%$resultsets)) {
1514 $builder->build({ source => $r, value => { $field => $keeper->id } });
1515 $builder->build({ source => $r, value => { $field => $loser_1 } });
1516 $builder->build({ source => $r, value => { $field => $loser_2 } });
1519 $schema->resultset($r)->search( { $field => $keeper->id } );
1520 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1523 $schema->resultset($r)->search( { $field => $loser_1 } );
1524 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1527 $schema->resultset($r)->search( { $field => $loser_2 } );
1528 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1531 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1533 while (my ($r, $field) = each(%$resultsets)) {
1535 $schema->resultset($r)->search( {$field => $keeper->id } );
1536 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1539 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1540 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1542 $schema->storage->txn_rollback;
1545 subtest '->store' => sub {
1547 my $schema = Koha::Database->new->schema;
1548 $schema->storage->txn_begin;
1550 my $print_error = $schema->storage->dbh->{PrintError};
1551 $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1553 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1554 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1557 { $patron_2->userid($patron_1->userid)->store; }
1558 'Koha::Exceptions::Object::DuplicateID',
1559 'Koha::Patron->store raises an exception on duplicate ID';
1562 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1563 my $password = 'password';
1564 $patron_1->set_password({ password => $password });
1565 like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1566 my $digest = $patron_1->password;
1567 $patron_1->surname('xxx')->store;
1568 is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1570 # Test uppercasesurnames
1571 t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 );
1572 my $surname = lc $patron_1->surname;
1573 $patron_1->surname($surname)->store;
1574 isnt( $patron_1->surname, $surname,
1575 'Surname converts to uppercase on store.');
1576 t::lib::Mocks::mock_preference( 'uppercasesurnames', 0 );
1577 $patron_1->surname($surname)->store;
1578 is( $patron_1->surname, $surname,
1579 'Surname remains unchanged on store.');
1581 $schema->storage->dbh->{PrintError} = $print_error;
1582 $schema->storage->txn_rollback;
1584 subtest 'skip updated_on for BorrowersLog' => sub {
1586 $schema->storage->txn_begin;
1587 t::lib::Mocks::mock_preference('BorrowersLog', 1);
1588 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1589 $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1590 my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1591 is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1592 $schema->storage->txn_rollback;
1596 subtest '->set_password' => sub {
1600 $schema->storage->txn_begin;
1602 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1604 # Disable logging password changes for this tests
1605 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1607 # Password-length tests
1608 t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1609 throws_ok { $patron->set_password({ password => 'ab' }); }
1610 'Koha::Exceptions::Password::TooShort',
1611 'minPasswordLength is undef, fall back to 3, fail test';
1613 'Password length (2) is shorter than required (3)',
1614 'Exception parameters passed correctly'
1617 t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1618 throws_ok { $patron->set_password({ password => 'ab' }); }
1619 'Koha::Exceptions::Password::TooShort',
1620 'minPasswordLength is 2, fall back to 3, fail test';
1622 t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1623 throws_ok { $patron->set_password({ password => 'abcb' }); }
1624 'Koha::Exceptions::Password::TooShort',
1625 'minPasswordLength is 5, fail test';
1627 # Trailing spaces tests
1628 throws_ok { $patron->set_password({ password => 'abcD12d ' }); }
1629 'Koha::Exceptions::Password::WhitespaceCharacters',
1630 'Password contains trailing spaces, exception is thrown';
1632 # Require strong password tests
1633 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1634 throws_ok { $patron->set_password({ password => 'abcd a' }); }
1635 'Koha::Exceptions::Password::TooWeak',
1636 'Password is too weak, exception is thrown';
1638 # Refresh patron from DB, just to make sure
1639 $patron->discard_changes;
1640 is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1642 $patron->set_password({ password => 'abcD12 34' });
1643 $patron->discard_changes;
1645 is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1647 lives_ok { $patron->set_password({ password => 'abcd a', skip_validation => 1 }) }
1648 'Password is weak, but skip_validation was passed, so no exception thrown';
1651 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1652 $patron->login_attempts(3)->store;
1653 my $old_digest = $patron->password;
1654 $patron->set_password({ password => 'abcd a' });
1655 $patron->discard_changes;
1657 isnt( $patron->password, $old_digest, 'Password has been updated' );
1658 ok( checkpw_hash('abcd a', $patron->password), 'Password hash is correct' );
1659 is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1661 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1662 is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1664 # Enable logging password changes
1665 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1666 $patron->set_password({ password => 'abcd b' });
1668 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1669 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1671 $schema->storage->txn_rollback;
1674 $schema->storage->txn_begin;
1675 subtest 'search_unsubscribed' => sub {
1678 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1679 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
1680 is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
1682 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1683 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1685 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
1686 Koha::Patron::Consents->delete; # for correct counts
1687 Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string })->store;
1688 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
1690 # Add another refusal but shift the period
1691 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
1692 Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string->subtract(days=>2) })->store;
1693 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
1695 # Try another (special) attempts setting
1696 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
1697 # Lockout is now disabled
1698 # Patron2 still matches: refused earlier, not locked
1699 is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
1702 subtest 'search_anonymize_candidates' => sub {
1704 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1705 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1706 $patron1->anonymized(0);
1707 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1708 $patron2->anonymized(0);
1709 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1711 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
1712 is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
1714 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
1715 my $cnt = Koha::Patrons->search_anonymize_candidates->count;
1716 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1717 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1718 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
1720 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
1721 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1722 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1723 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1724 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1725 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1726 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
1728 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
1729 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1730 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1731 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1732 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1733 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1734 is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
1736 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1737 $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1738 $patron1->login_attempts(0)->store;
1739 $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1740 $patron2->login_attempts(0)->store;
1741 $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
1742 $patron1->login_attempts(3)->store;
1743 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1744 $cnt+1, 'Locked flag' );
1747 subtest 'search_anonymized' => sub {
1749 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1751 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
1752 is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
1754 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
1755 $patron1->dateexpiry( dt_from_string );
1756 $patron1->anonymized(0)->store;
1757 my $cnt = Koha::Patrons->search_anonymized->count;
1758 $patron1->anonymized(1)->store;
1759 is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
1760 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1761 is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
1764 subtest 'lock' => sub {
1767 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1768 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1769 my $hold = $builder->build_object({
1770 class => 'Koha::Holds',
1771 value => { borrowernumber => $patron1->borrowernumber },
1774 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1775 my $expiry = dt_from_string->add(days => 1);
1776 $patron1->dateexpiry( $expiry );
1778 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1779 is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
1780 is( $patron1->holds->count, 1, 'No holds removed' );
1782 $patron1->lock({ expire => 1, remove => 1});
1783 isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
1784 is( $patron1->holds->count, 0, 'Holds removed' );
1786 # Disable lockout feature
1787 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1788 $patron1->login_attempts(0);
1789 $patron1->dateexpiry( $expiry );
1792 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1794 # Trivial wrapper test (Koha::Patrons->lock)
1795 $patron1->login_attempts(0)->store;
1796 Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
1797 $patron1->discard_changes; # refresh
1798 $patron2->discard_changes;
1799 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
1800 is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
1803 subtest 'anonymize' => sub {
1806 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1807 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1809 # First try patron with issues
1810 my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
1811 warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
1814 t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
1815 my $surname = $patron1->surname; # expect change, no clear
1816 my $branchcode = $patron1->branchcode; # expect skip
1817 $patron1->anonymize;
1818 is($patron1->anonymized, 1, 'Check flag' );
1820 is( $patron1->dateofbirth, undef, 'Birth date cleared' );
1821 is( $patron1->firstname, undef, 'First name cleared' );
1822 isnt( $patron1->surname, $surname, 'Surname changed' );
1823 ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
1824 is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
1825 is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
1827 # Test wrapper in Koha::Patrons
1828 $patron1->surname($surname)->store; # restore
1829 my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
1830 $patron1->discard_changes; # refresh
1831 isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
1832 $patron2->discard_changes; # refresh
1833 is( $patron2->firstname, undef, 'First name patron2 cleared' );
1835 $schema->storage->txn_rollback;