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 => 34;
32 use C4::Auth qw(checkpw_hash);
36 use Koha::Patron::Categories;
39 use Koha::Virtualshelves;
41 use t::lib::TestBuilder;
44 my $schema = Koha::Database->new->schema;
45 $schema->storage->txn_begin;
47 my $builder = t::lib::TestBuilder->new;
48 my $library = $builder->build({source => 'Branch' });
49 my $category = $builder->build({source => 'Category' });
50 my $nb_of_patrons = Koha::Patrons->search->count;
51 my $new_patron_1 = Koha::Patron->new(
52 { cardnumber => 'test_cn_1',
53 branchcode => $library->{branchcode},
54 categorycode => $category->{categorycode},
55 surname => 'surname for patron1',
56 firstname => 'firstname for patron1',
57 userid => 'a_nonexistent_userid_1',
58 flags => 1, # Is superlibrarian
61 my $new_patron_2 = Koha::Patron->new(
62 { cardnumber => 'test_cn_2',
63 branchcode => $library->{branchcode},
64 categorycode => $category->{categorycode},
65 surname => 'surname for patron2',
66 firstname => 'firstname for patron2',
67 userid => 'a_nonexistent_userid_2',
71 C4::Context->_new_userenv('xxx');
72 set_logged_in_user( $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 'update_password' => sub {
214 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
215 my $original_userid = $new_patron_1->userid;
216 my $original_password = $new_patron_1->password;
217 warning_like { $retrieved_patron_1->update_password( $new_patron_2->userid, 'another_password' ) }
219 'Koha::Patron->update_password should warn if the userid is already used by another patron';
220 is( Koha::Patrons->find( $new_patron_1->borrowernumber )->userid, $original_userid, 'Koha::Patron->update_password should not have updated the userid' );
221 is( Koha::Patrons->find( $new_patron_1->borrowernumber )->password, $original_password, 'Koha::Patron->update_password should not have updated the userid' );
223 my $digest = $retrieved_patron_1->update_password( 'another_nonexistent_userid_1', 'another_password' );
224 is( Koha::Patrons->find( $new_patron_1->borrowernumber )->userid, 'another_nonexistent_userid_1', 'Koha::Patron->update_password should have updated the userid' );
225 is( Koha::Patrons->find( $new_patron_1->borrowernumber )->password, $digest, 'Koha::Patron->update_password should have updated the password' );
227 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $new_patron_1->borrowernumber } )->count;
228 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->update_password should have logged' );
230 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
231 $retrieved_patron_1->update_password( 'yet_another_nonexistent_userid_1', 'another_password' );
232 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $new_patron_1->borrowernumber } )->count;
233 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->update_password should not have logged' );
236 subtest 'is_expired' => sub {
238 my $patron = $builder->build({ source => 'Borrower' });
239 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
240 $patron->dateexpiry( undef )->store->discard_changes;
241 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
242 $patron->dateexpiry( dt_from_string )->store->discard_changes;
243 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
244 $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
245 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
246 $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
247 is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
252 subtest 'is_going_to_expire' => sub {
254 my $patron = $builder->build({ source => 'Borrower' });
255 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
256 $patron->dateexpiry( undef )->store->discard_changes;
257 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
259 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
260 $patron->dateexpiry( dt_from_string )->store->discard_changes;
261 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
263 $patron->dateexpiry( dt_from_string )->store->discard_changes;
264 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
266 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
267 $patron->dateexpiry( dt_from_string->add( days => 11 ) )->store->discard_changes;
268 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');
270 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
271 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
272 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');
274 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
275 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
276 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');
279 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
280 $patron->dateexpiry( dt_from_string->add( days => 20 ) )->store->discard_changes;
281 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');
283 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
284 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
285 is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
291 subtest 'renew_account' => sub {
294 for my $date ( '2016-03-31', '2016-11-30', dt_from_string() ) {
295 my $dt = dt_from_string( $date, 'iso' );
296 Time::Fake->offset( $dt->epoch );
297 my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
298 my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
299 my $a_year_later_minus_a_month = $dt->clone->add( months => 11, end_of_month => 'limit' )->truncate( to => 'day' );
300 my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
301 my $a_year_later_plus_a_month = $dt->clone->add( months => 13, end_of_month => 'limit' )->truncate( to => 'day' );
302 my $patron_category = $builder->build(
303 { source => 'Category',
305 enrolmentperiod => 12,
306 enrolmentperioddate => undef,
310 my $patron = $builder->build(
311 { source => 'Borrower',
313 dateexpiry => $a_month_ago,
314 categorycode => $patron_category->{categorycode},
315 date_renewed => undef, # Force builder to not populate the column for new patron
319 my $patron_2 = $builder->build(
320 { source => 'Borrower',
322 dateexpiry => $a_month_ago,
323 categorycode => $patron_category->{categorycode},
327 my $patron_3 = $builder->build(
328 { source => 'Borrower',
330 dateexpiry => $a_month_later,
331 categorycode => $patron_category->{categorycode},
335 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
336 my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
337 my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
339 is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
341 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
342 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
343 my $expiry_date = $retrieved_patron->renew_account;
344 is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
345 my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
346 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" );
347 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
348 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
350 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
351 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
352 $expiry_date = $retrieved_patron->renew_account;
353 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
354 $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
355 is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
356 $retrieved_expiry_date = $retrieved_patron->dateexpiry;
357 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
358 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
359 is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
361 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
362 $expiry_date = $retrieved_patron_2->renew_account;
363 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
364 $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
365 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
367 $expiry_date = $retrieved_patron_3->renew_account;
368 is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
369 $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
370 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" );
372 $retrieved_patron->delete;
373 $retrieved_patron_2->delete;
374 $retrieved_patron_3->delete;
379 subtest "move_to_deleted" => sub {
381 my $originally_updated_on = '2016-01-01 12:12:12';
382 my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
383 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
384 is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
385 ; # FIXME This should be Koha::Deleted::Patron
386 my $deleted_patron = $schema->resultset('Deletedborrower')
387 ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
389 ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
390 ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
391 isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
392 $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
393 is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
394 $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup
397 subtest "delete" => sub {
399 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
400 my $patron = $builder->build( { source => 'Borrower' } );
401 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
402 my $hold = $builder->build(
403 { source => 'Reserve',
404 value => { borrowernumber => $patron->{borrowernumber} }
407 my $list = $builder->build(
408 { source => 'Virtualshelve',
409 value => { owner => $patron->{borrowernumber} }
413 my $deleted = $retrieved_patron->delete;
414 is( $deleted, 1, 'Koha::Patron->delete should return 1 if the patron has been correctly deleted' );
416 is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
418 is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's holds| );
420 is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
422 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
423 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
426 subtest 'Koha::Patrons->delete' => sub {
429 my $mod_patron = Test::MockModule->new( 'Koha::Patron' );
430 my $moved_to_deleted = 0;
431 $mod_patron->mock( 'move_to_deleted', sub { $moved_to_deleted++; } );
433 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
434 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
435 my $id1 = $patron1->borrowernumber;
436 my $set = Koha::Patrons->search({ borrowernumber => { '>=' => $id1 }});
437 is( $set->count, 2, 'Two patrons found as expected' );
438 is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
439 is( $moved_to_deleted, 2, 'Patrons moved to deletedborrowers' );
441 # Add again, test if we can raise an exception
442 $mod_patron->mock( 'delete', sub { return -1; } );
443 $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
444 $id1 = $patron1->borrowernumber;
445 $set = Koha::Patrons->search({ borrowernumber => { '>=' => $id1 }});
446 throws_ok { $set->delete } 'Koha::Exceptions::Patron::Delete',
447 'Exception raised for deleting patron';
450 subtest 'add_enrolment_fee_if_needed' => sub {
453 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
454 foreach( keys %{$enrolmentfees} ) {
455 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
457 my $enrolmentfee_K = $enrolmentfees->{K};
458 my $enrolmentfee_J = $enrolmentfees->{J};
459 my $enrolmentfee_YA = $enrolmentfees->{YA};
461 my %borrower_data = (
462 firstname => 'my firstname',
463 surname => 'my surname',
465 branchcode => $library->{branchcode},
468 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
469 $borrower_data{borrowernumber} = $borrowernumber;
471 my $patron = Koha::Patrons->find( $borrowernumber );
472 my $total = $patron->account->balance;
473 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
475 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
476 $borrower_data{categorycode} = 'J';
477 $patron->set(\%borrower_data)->store;
478 $total = $patron->account->balance;
479 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
481 $borrower_data{categorycode} = 'K';
482 $patron->set(\%borrower_data)->store;
483 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
485 $borrower_data{categorycode} = 'J';
486 $patron->set(\%borrower_data)->store;
487 $total = $patron->account->balance;
488 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
490 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
491 $patron->categorycode('YA')->store;
492 $total = $patron->account->balance;
494 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
495 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
501 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
504 my $library = $builder->build( { source => 'Branch' } );
505 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
506 my $item_1 = $builder->build(
510 homebranch => $library->{branchcode},
511 holdingbranch => $library->{branchcode},
512 biblionumber => $biblionumber_1,
518 my $item_2 = $builder->build(
522 homebranch => $library->{branchcode},
523 holdingbranch => $library->{branchcode},
524 biblionumber => $biblionumber_1,
530 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
531 my $item_3 = $builder->build(
535 homebranch => $library->{branchcode},
536 holdingbranch => $library->{branchcode},
537 biblionumber => $biblionumber_2,
543 my $patron = $builder->build(
545 source => 'Borrower',
546 value => { branchcode => $library->{branchcode} }
550 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
551 my $checkouts = $patron->checkouts;
552 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
553 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
554 my $pending_checkouts = $patron->pending_checkouts;
555 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
556 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
557 my $old_checkouts = $patron->old_checkouts;
558 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
559 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
561 # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
562 $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
564 my $module = new Test::MockModule('C4::Context');
565 $module->mock( 'userenv', sub { { branch => $library->{branchcode} } } );
567 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
568 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
569 AddIssue( $patron, $item_3->{barcode} );
571 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
572 $checkouts = $patron->checkouts;
573 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
574 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
575 $pending_checkouts = $patron->pending_checkouts;
576 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
577 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
579 my $first_checkout = $pending_checkouts->next;
580 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
582 my $overdues = $patron->get_overdues;
583 is( $overdues->count, 2, 'Patron should have 2 overdues');
584 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
585 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
586 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
589 C4::Circulation::AddReturn( $item_1->{barcode} );
590 C4::Circulation::AddReturn( $item_2->{barcode} );
591 $old_checkouts = $patron->old_checkouts;
592 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
593 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
596 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
598 $module->unmock('userenv');
601 subtest 'get_routing_lists' => sub {
604 my $biblio = Koha::Biblio->new()->store();
605 my $subscription = Koha::Subscription->new({
606 biblionumber => $biblio->biblionumber,
610 my $patron = $builder->build( { source => 'Borrower' } );
611 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
613 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
615 my $routinglist_count = Koha::Subscription::Routinglists->count;
616 my $routinglist = Koha::Subscription::Routinglist->new({
617 borrowernumber => $patron->borrowernumber,
619 subscriptionid => $subscription->subscriptionid
622 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
624 my $routinglists = $patron->get_routing_lists;
625 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
626 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
628 my $subscription2 = Koha::Subscription->new({
629 biblionumber => $biblio->biblionumber,
632 my $routinglist2 = Koha::Subscription::Routinglist->new({
633 borrowernumber => $patron->borrowernumber,
635 subscriptionid => $subscription2->subscriptionid
638 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
640 $patron->delete; # Clean up for later tests
644 subtest 'get_age' => sub {
647 my $patron = $builder->build( { source => 'Borrower' } );
648 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
650 my $today = dt_from_string;
652 $patron->dateofbirth( undef );
653 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
654 $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1, end_of_month => 'limit' ) );
655 is( $patron->get_age, 12, 'Patron should be 12' );
656 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 1, end_of_month => 'limit' ) );
657 is( $patron->get_age, 17, 'Patron should be 17, happy birthday tomorrow!' );
658 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 0, end_of_month => 'limit' ) );
659 is( $patron->get_age, 18, 'Patron should be 18' );
660 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -31, end_of_month => 'limit' ) );
661 is( $patron->get_age, 19, 'Patron should be 19' );
662 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -30, end_of_month => 'limit' ) );
663 is( $patron->get_age, 19, 'Patron should be 19 again' );
664 $patron->dateofbirth( $today->clone->add( years => 0, months => -1, days => -1, end_of_month => 'limit' ) );
665 is( $patron->get_age, 0, 'Patron is a newborn child' );
670 subtest 'account' => sub {
673 my $patron = $builder->build({source => 'Borrower'});
675 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
676 my $account = $patron->account;
677 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
682 subtest 'search_upcoming_membership_expires' => sub {
685 my $expiry_days = 15;
686 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
687 my $nb_of_days_before = 1;
688 my $nb_of_days_after = 2;
690 my $builder = t::lib::TestBuilder->new();
692 my $library = $builder->build({ source => 'Branch' });
694 # before we add borrowers to this branch, add the expires we have now
695 # note that this pertains to the current mocked setting of the pref
696 # for this reason we add the new branchcode to most of the tests
697 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
699 my $patron_1 = $builder->build({
700 source => 'Borrower',
702 branchcode => $library->{branchcode},
703 dateexpiry => dt_from_string->add( days => $expiry_days )
707 my $patron_2 = $builder->build({
708 source => 'Borrower',
710 branchcode => $library->{branchcode},
711 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
715 my $patron_3 = $builder->build({
716 source => 'Borrower',
718 branchcode => $library->{branchcode},
719 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
723 # Test without extra parameters
724 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
725 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
728 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
729 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
730 my $expired = $upcoming_mem_expires->next;
731 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
732 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
733 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
735 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
736 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
737 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
739 # Test MembershipExpiryDaysNotice == undef
740 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
741 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
742 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
744 # Test the before parameter
745 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
746 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
747 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
748 # Test after parameter also
749 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
750 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
751 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
754 subtest 'holds and old_holds' => sub {
757 my $library = $builder->build( { source => 'Branch' } );
758 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
759 my $item_1 = $builder->build(
763 homebranch => $library->{branchcode},
764 holdingbranch => $library->{branchcode},
765 biblionumber => $biblionumber_1
769 my $item_2 = $builder->build(
773 homebranch => $library->{branchcode},
774 holdingbranch => $library->{branchcode},
775 biblionumber => $biblionumber_1
779 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
780 my $item_3 = $builder->build(
784 homebranch => $library->{branchcode},
785 holdingbranch => $library->{branchcode},
786 biblionumber => $biblionumber_2
790 my $patron = $builder->build(
792 source => 'Borrower',
793 value => { branchcode => $library->{branchcode} }
797 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
798 my $holds = $patron->holds;
799 is( ref($holds), 'Koha::Holds',
800 'Koha::Patron->holds should return a Koha::Holds objects' );
801 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
803 C4::Reserves::AddReserve( $library->{branchcode},
804 $patron->borrowernumber, $biblionumber_1 );
806 C4::Reserves::AddReserve( $library->{branchcode},
807 $patron->borrowernumber, $biblionumber_2, undef, undef, dt_from_string->add( days => 2 ) );
809 $holds = $patron->holds;
810 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
812 my $old_holds = $patron->old_holds;
813 is( ref($old_holds), 'Koha::Old::Holds',
814 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
815 is( $old_holds->count, 0, 'There should not be any old holds yet');
817 my $hold = $holds->next;
820 $old_holds = $patron->old_holds;
821 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
828 subtest 'notice_email_address' => sub {
831 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
833 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
834 is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
836 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
837 is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
842 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
845 # TODO create a subroutine in t::lib::Mocks
846 my $branch = $builder->build({ source => 'Branch' });
847 my $userenv_patron = $builder->build({
848 source => 'Borrower',
849 value => { branchcode => $branch->{branchcode} },
851 C4::Context->_new_userenv('DUMMY SESSION');
852 C4::Context->set_userenv(
853 $userenv_patron->{borrowernumber},
854 $userenv_patron->{userid},
855 'usercnum', 'First name', 'Surname',
856 $branch->{branchcode},
857 $branch->{branchname},
860 my $anonymous = $builder->build( { source => 'Borrower', }, );
862 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
864 subtest 'patron privacy is 1 (default)' => sub {
867 t::lib::Mocks::mock_preference('IndependentBranches', 0);
868 my $patron = $builder->build(
869 { source => 'Borrower',
870 value => { privacy => 1, }
873 my $item_1 = $builder->build(
881 my $issue_1 = $builder->build(
884 borrowernumber => $patron->{borrowernumber},
885 itemnumber => $item_1->{itemnumber},
889 my $item_2 = $builder->build(
897 my $issue_2 = $builder->build(
900 borrowernumber => $patron->{borrowernumber},
901 itemnumber => $item_2->{itemnumber},
906 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, undef, '2010-10-10' );
907 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, undef, '2011-11-11' );
908 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
910 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
911 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
913 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
914 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
916 my $dbh = C4::Context->dbh;
917 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
918 $sth->execute($item_1->{itemnumber});
919 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
920 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
921 $sth->execute($item_2->{itemnumber});
922 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
923 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
925 $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
926 $sth->execute($item_2->{itemnumber});
927 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
928 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
930 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
931 $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
932 $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
933 $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
934 $sth->execute($item_1->{itemnumber});
935 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
936 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
937 $sth->execute($item_2->{itemnumber});
938 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
939 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
941 Koha::Patrons->find( $patron->{borrowernumber})->delete;
944 subtest 'patron privacy is 0 (forever)' => sub {
947 t::lib::Mocks::mock_preference('IndependentBranches', 0);
948 my $patron = $builder->build(
949 { source => 'Borrower',
950 value => { privacy => 0, }
953 my $item = $builder->build(
961 my $issue = $builder->build(
964 borrowernumber => $patron->{borrowernumber},
965 itemnumber => $item->{itemnumber},
970 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
971 is( $returned, 1, 'The item should have been returned' );
972 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
973 ok( $rows_affected > 0, 'AnonymiseIssueHistory should not return any error if success' );
975 my $dbh = C4::Context->dbh;
976 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
977 SELECT borrowernumber FROM old_issues where itemnumber = ?
978 |, undef, $item->{itemnumber});
979 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
980 Koha::Patrons->find( $patron->{borrowernumber})->delete;
983 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
985 subtest 'AnonymousPatron is not defined' => sub {
988 t::lib::Mocks::mock_preference('IndependentBranches', 0);
989 my $patron = $builder->build(
990 { source => 'Borrower',
991 value => { privacy => 1, }
994 my $item = $builder->build(
1002 my $issue = $builder->build(
1003 { source => 'Issue',
1005 borrowernumber => $patron->{borrowernumber},
1006 itemnumber => $item->{itemnumber},
1011 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
1012 is( $returned, 1, 'The item should have been returned' );
1013 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
1014 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1016 my $dbh = C4::Context->dbh;
1017 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1018 SELECT borrowernumber FROM old_issues where itemnumber = ?
1019 |, undef, $item->{itemnumber});
1020 is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
1021 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1024 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1026 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1027 my $patron = $builder->build(
1028 { source => 'Borrower',
1029 value => { privacy => 1 } # Another branchcode than the logged in librarian
1032 my $item = $builder->build(
1040 my $issue = $builder->build(
1041 { source => 'Issue',
1043 borrowernumber => $patron->{borrowernumber},
1044 itemnumber => $item->{itemnumber},
1049 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
1050 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1051 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1054 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1055 Koha::Patrons->find( $userenv_patron->{borrowernumber})->delete;
1057 # Reset IndependentBranches for further tests
1058 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1061 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1069 $nb_of_patrons = Koha::Patrons->search->count;
1070 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1071 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1072 my $library_11 = $builder->build( { source => 'Branch' } );
1073 my $library_12 = $builder->build( { source => 'Branch' } );
1074 my $library_21 = $builder->build( { source => 'Branch' } );
1075 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1076 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1077 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1078 Koha::Library::Group->new(
1079 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1080 Koha::Library::Group->new(
1081 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1082 Koha::Library::Group->new(
1083 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1085 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1086 # 2 patrons from library_11 (group1)
1087 # patron_11_1 see patron's infos from outside its group
1088 # Setting flags => undef to not be considered as superlibrarian
1089 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1090 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1091 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1092 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1093 # patron_11_2 can only see patron's info from its group
1094 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1095 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1096 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1097 # 1 patron from library_12 (group1)
1098 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1099 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1100 # 1 patron from library_21 (group2) can only see patron's info from its group
1101 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1102 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1103 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1105 # Pfiou, we can start now!
1106 subtest 'libraries_where_can_see_patrons' => sub {
1111 set_logged_in_user( $patron_11_1 );
1112 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1113 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1115 set_logged_in_user( $patron_11_2 );
1116 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1117 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| );
1119 set_logged_in_user( $patron_21 );
1120 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1121 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| );
1123 subtest 'can_see_patron_infos' => sub {
1126 set_logged_in_user( $patron_11_1 );
1127 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1128 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1129 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1131 set_logged_in_user( $patron_11_2 );
1132 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1133 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1134 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1136 subtest 'search_limited' => sub {
1139 set_logged_in_user( $patron_11_1 );
1140 my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1141 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1142 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1144 set_logged_in_user( $patron_11_2 );
1145 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1146 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' );
1148 set_logged_in_user( $patron_21 );
1149 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1150 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1152 $patron_11_1->delete;
1153 $patron_11_2->delete;
1158 subtest 'account_locked' => sub {
1160 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1161 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1162 for my $value ( undef, '', 0 ) {
1163 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1164 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1165 $patron->login_attempts(1)->store;
1166 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1169 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1170 $patron->login_attempts(2)->store;
1171 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1172 $patron->login_attempts(3)->store;
1173 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1178 subtest 'is_child | is_adult' => sub {
1180 my $category = $builder->build_object(
1182 class => 'Koha::Patron::Categories',
1183 value => { category_type => 'A' }
1186 my $patron_adult = $builder->build_object(
1188 class => 'Koha::Patrons',
1189 value => { categorycode => $category->categorycode }
1192 $category = $builder->build_object(
1194 class => 'Koha::Patron::Categories',
1195 value => { category_type => 'I' }
1198 my $patron_adult_i = $builder->build_object(
1200 class => 'Koha::Patrons',
1201 value => { categorycode => $category->categorycode }
1204 $category = $builder->build_object(
1206 class => 'Koha::Patron::Categories',
1207 value => { category_type => 'C' }
1210 my $patron_child = $builder->build_object(
1212 class => 'Koha::Patrons',
1213 value => { categorycode => $category->categorycode }
1216 $category = $builder->build_object(
1218 class => 'Koha::Patron::Categories',
1219 value => { category_type => 'O' }
1222 my $patron_other = $builder->build_object(
1224 class => 'Koha::Patrons',
1225 value => { categorycode => $category->categorycode }
1228 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1229 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1230 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1231 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1233 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1234 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1235 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1236 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1239 $patron_adult->delete;
1240 $patron_adult_i->delete;
1241 $patron_child->delete;
1242 $patron_other->delete;
1245 subtest 'get_overdues' => sub {
1248 my $library = $builder->build( { source => 'Branch' } );
1249 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1250 my $item_1 = $builder->build(
1254 homebranch => $library->{branchcode},
1255 holdingbranch => $library->{branchcode},
1256 biblionumber => $biblionumber_1
1260 my $item_2 = $builder->build(
1264 homebranch => $library->{branchcode},
1265 holdingbranch => $library->{branchcode},
1266 biblionumber => $biblionumber_1
1270 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1271 my $item_3 = $builder->build(
1275 homebranch => $library->{branchcode},
1276 holdingbranch => $library->{branchcode},
1277 biblionumber => $biblionumber_2
1281 my $patron = $builder->build(
1283 source => 'Borrower',
1284 value => { branchcode => $library->{branchcode} }
1288 my $module = new Test::MockModule('C4::Context');
1289 $module->mock( 'userenv', sub { { branch => $library->{branchcode} } } );
1291 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1292 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1293 AddIssue( $patron, $item_3->{barcode} );
1295 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1296 my $overdues = $patron->get_overdues;
1297 is( $overdues->count, 2, 'Patron should have 2 overdues');
1298 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1299 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1301 my $o = $overdues->reset->next;
1302 my $unblessed_overdue = $o->unblessed_all_relateds;
1303 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1304 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1305 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1306 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1309 $patron->checkouts->delete;
1313 subtest 'userid_is_valid' => sub {
1316 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1317 my $patron_category = $builder->build_object(
1319 class => 'Koha::Patron::Categories',
1320 value => { category_type => 'P', enrolmentfee => 0 }
1324 cardnumber => "123456789",
1325 firstname => "Tomasito",
1327 categorycode => $patron_category->categorycode,
1328 branchcode => $library->branchcode,
1331 my $expected_userid_patron_1 = 'tomasito.none';
1332 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1333 my $patron_1 = Koha::Patrons->find($borrowernumber);
1334 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1336 $patron_1->userid( 'tomasito.non' );
1337 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1338 1, 'recently created userid -> unique (borrowernumber passed)' );
1340 $patron_1->userid( 'tomasitoxxx' );
1341 is( $patron_1->has_valid_userid,
1342 1, 'non-existent userid -> unique (borrowernumber passed)' );
1343 $patron_1->discard_changes; # We compare with the original userid later
1345 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1346 is( $patron_not_in_storage->has_valid_userid,
1347 0, 'userid exists for another patron, patron is not in storage yet' );
1349 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1350 is( $patron_not_in_storage->has_valid_userid,
1351 1, 'non-existent userid, patron is not in storage yet' );
1353 # Regression tests for BZ12226
1354 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1355 is( $db_patron->has_valid_userid,
1356 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1358 # Add a new borrower with the same userid but different cardnumber
1359 $data{cardnumber} = "987654321";
1360 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1361 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1362 $patron_2->userid($patron_1->userid);
1363 is( $patron_2->has_valid_userid,
1364 0, 'The userid is already in used, it cannot be used for another patron' );
1366 my $new_userid = 'a_user_id';
1367 $data{cardnumber} = "234567890";
1368 $data{userid} = 'a_user_id';
1369 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1370 my $patron_3 = Koha::Patrons->find($borrowernumber);
1371 is( $patron_3->userid, $new_userid,
1372 'Koha::Patron->store should insert the given userid' );
1380 subtest 'generate_userid' => sub {
1383 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1384 my $patron_category = $builder->build_object(
1386 class => 'Koha::Patron::Categories',
1387 value => { category_type => 'P', enrolmentfee => 0 }
1391 cardnumber => "123456789",
1392 firstname => "Tomasito",
1394 categorycode => $patron_category->categorycode,
1395 branchcode => $library->branchcode,
1398 my $expected_userid_patron_1 = 'tomasito.none';
1399 my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1400 $new_patron->generate_userid;
1401 my $userid = $new_patron->userid;
1402 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1403 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1404 my $patron_1 = Koha::Patrons->find($borrowernumber);
1405 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1407 $new_patron->generate_userid;
1408 $userid = $new_patron->userid;
1409 is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1410 $data{cardnumber} = '987654321';
1411 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1412 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1413 isnt( $patron_2->userid, 'tomasito',
1414 "Patron with duplicate userid has new userid generated" );
1415 is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1416 "Patron with duplicate userid has new userid generated (1 is appened" );
1418 $new_patron->generate_userid;
1419 $userid = $new_patron->userid;
1420 is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1422 $patron_1 = Koha::Patrons->find($borrowernumber);
1423 $patron_1->userid(undef);
1424 $patron_1->generate_userid;
1425 $userid = $patron_1->userid;
1426 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1433 $nb_of_patrons = Koha::Patrons->search->count;
1434 $retrieved_patron_1->delete;
1435 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1437 subtest 'Log cardnumber change' => sub {
1440 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1441 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1443 my $cardnumber = $patron->cardnumber;
1444 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1447 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1448 my $log_info = from_json( $logs[0]->info );
1449 is( $log_info->{cardnumber_replaced}->{new_cardnumber}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1450 is( $log_info->{cardnumber_replaced}->{previous_cardnumber}, $cardnumber, 'Got correct old cardnumber' );
1451 is( scalar @logs, 2, 'With BorrowerLogs, Change in cardnumber should be logged, as well as general alert of patron mod.' );
1454 $schema->storage->txn_rollback;
1456 subtest 'Test Koha::Patrons::merge' => sub {
1459 my $schema = Koha::Database->new()->schema();
1461 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1463 $schema->storage->txn_begin;
1465 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1466 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1467 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1469 while (my ($r, $field) = each(%$resultsets)) {
1470 $builder->build({ source => $r, value => { $field => $keeper->id } });
1471 $builder->build({ source => $r, value => { $field => $loser_1 } });
1472 $builder->build({ source => $r, value => { $field => $loser_2 } });
1475 $schema->resultset($r)->search( { $field => $keeper->id } );
1476 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1479 $schema->resultset($r)->search( { $field => $loser_1 } );
1480 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1483 $schema->resultset($r)->search( { $field => $loser_2 } );
1484 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1487 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1489 while (my ($r, $field) = each(%$resultsets)) {
1491 $schema->resultset($r)->search( {$field => $keeper->id } );
1492 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1495 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1496 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1498 $schema->storage->txn_rollback;
1501 subtest '->store' => sub {
1503 my $schema = Koha::Database->new->schema;
1504 $schema->storage->txn_begin;
1506 my $print_error = $schema->storage->dbh->{PrintError};
1507 $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1509 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1510 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1513 { $patron_2->userid($patron_1->userid)->store; }
1514 'Koha::Exceptions::Object::DuplicateID',
1515 'Koha::Patron->store raises an exception on duplicate ID';
1518 my $password = 'password';
1519 $patron_1->update_password($patron_1->userid, $password);
1520 like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1521 my $digest = $patron_1->password;
1522 $patron_1->surname('xxx')->store;
1523 is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1525 $schema->storage->dbh->{PrintError} = $print_error;
1526 $schema->storage->txn_rollback;
1529 subtest '->set_password' => sub {
1533 $schema->storage->txn_begin;
1535 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1537 # Disable logging password changes for this tests
1538 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1540 # Password-length tests
1541 t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1542 throws_ok { $patron->set_password('ab'); }
1543 'Koha::Exceptions::Password::TooShort',
1544 'minPasswordLength is undef, fall back to 3, fail test';
1546 t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1547 throws_ok { $patron->set_password('ab'); }
1548 'Koha::Exceptions::Password::TooShort',
1549 'minPasswordLength is 2, fall back to 3, fail test';
1551 t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1552 throws_ok { $patron->set_password('abcb'); }
1553 'Koha::Exceptions::Password::TooShort',
1554 'minPasswordLength is 5, fail test';
1556 # Trailing spaces tests
1557 throws_ok { $patron->set_password('abcD12d '); }
1558 'Koha::Exceptions::Password::WhitespaceCharacters',
1559 'Password contains trailing spaces, exception is thrown';
1561 # Require strong password tests
1562 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1563 throws_ok { $patron->set_password('abcd a'); }
1564 'Koha::Exceptions::Password::TooWeak',
1565 'Password is too weak, exception is thrown';
1567 # Refresh patron from DB, just to make sure
1568 $patron->discard_changes;
1569 is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1571 $patron->set_password('abcD12 34');
1572 $patron->discard_changes;
1574 is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1577 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1578 $patron->login_attempts(3)->store;
1579 my $old_digest = $patron->password;
1580 $patron->set_password('abcd a');
1581 $patron->discard_changes;
1583 isnt( $patron->password, $old_digest, 'Password has been updated' );
1584 ok( checkpw_hash('abcd a', $patron->password), 'Password hash is correct' );
1585 is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1587 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1588 is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1590 # Enable logging password changes
1591 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1592 $patron->set_password('abcd b');
1594 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1595 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1597 $schema->storage->txn_rollback;
1602 # TODO Move to t::lib::Mocks and reuse it!
1603 sub set_logged_in_user {
1605 C4::Context->set_userenv(
1606 $patron->borrowernumber, $patron->userid,
1607 $patron->cardnumber, 'firstname',
1608 'surname', $patron->library->branchcode,
1609 'Midway Public Library', $patron->flags,