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 => 33;
34 use Koha::Patron::Categories;
37 use Koha::Virtualshelves;
39 use t::lib::TestBuilder;
42 my $schema = Koha::Database->new->schema;
43 $schema->storage->txn_begin;
45 my $builder = t::lib::TestBuilder->new;
46 my $library = $builder->build({source => 'Branch' });
47 my $category = $builder->build({source => 'Category' });
48 my $nb_of_patrons = Koha::Patrons->search->count;
49 my $new_patron_1 = Koha::Patron->new(
50 { cardnumber => 'test_cn_1',
51 branchcode => $library->{branchcode},
52 categorycode => $category->{categorycode},
53 surname => 'surname for patron1',
54 firstname => 'firstname for patron1',
55 userid => 'a_nonexistent_userid_1',
56 flags => 1, # Is superlibrarian
59 my $new_patron_2 = Koha::Patron->new(
60 { cardnumber => 'test_cn_2',
61 branchcode => $library->{branchcode},
62 categorycode => $category->{categorycode},
63 surname => 'surname for patron2',
64 firstname => 'firstname for patron2',
65 userid => 'a_nonexistent_userid_2',
69 C4::Context->_new_userenv('xxx');
70 set_logged_in_user( $new_patron_1 );
72 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
74 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
75 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
77 subtest 'library' => sub {
79 is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
80 is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
83 subtest 'guarantees' => sub {
85 my $guarantees = $new_patron_1->guarantees;
86 is( ref($guarantees), 'Koha::Patrons', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
87 is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee' );
88 my @guarantees = $new_patron_1->guarantees;
89 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantees should return an array in a list context' );
90 is( scalar(@guarantees), 0, 'new_patron_1 should have 0 guarantee' );
92 my $guarantee_1 = $builder->build({ source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber }});
93 my $guarantee_2 = $builder->build({ source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber }});
95 $guarantees = $new_patron_1->guarantees;
96 is( ref($guarantees), 'Koha::Patrons', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
97 is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
98 @guarantees = $new_patron_1->guarantees;
99 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantees should return an array in a list context' );
100 is( scalar(@guarantees), 2, 'new_patron_1 should have 2 guarantees' );
101 $_->delete for @guarantees;
103 #Test return order of guarantees BZ 18635
104 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
105 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
107 my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
109 my $order_guarantee1 = $builder->build_object( { class => 'Koha::Patrons' , value => {
111 guarantorid => $guarantor->borrowernumber
115 my $order_guarantee2 = $builder->build_object( { class => 'Koha::Patrons' , value => {
117 guarantorid => $guarantor->borrowernumber
121 my $order_guarantee3 = $builder->build_object( { class => 'Koha::Patrons' , value => {
123 firstname => 'Walrus',
124 guarantorid => $guarantor->borrowernumber
128 my $order_guarantee4 = $builder->build_object( { class => 'Koha::Patrons' , value => {
130 firstname => 'Vulture',
131 guarantorid => $guarantor->borrowernumber
135 my $order_guarantee5 = $builder->build_object( { class => 'Koha::Patrons' , value => {
137 firstname => 'Unicorn',
138 guarantorid => $guarantor->borrowernumber
142 $guarantees = $guarantor->guarantees();
144 is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
145 is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
146 is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
147 is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
148 is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
151 subtest 'category' => sub {
153 my $patron_category = $new_patron_1->category;
154 is( ref( $patron_category), 'Koha::Patron::Category', );
155 is( $patron_category->categorycode, $category->{categorycode}, );
158 subtest 'siblings' => sub {
160 my $siblings = $new_patron_1->siblings;
161 is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
162 my $guarantee_1 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
163 my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
164 $siblings = $retrieved_guarantee_1->siblings;
165 is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
166 my @siblings = $retrieved_guarantee_1->siblings;
167 is( ref( \@siblings ), 'ARRAY', 'Koha::Patron->siblings should return an array in a list context' );
168 is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' );
169 my $guarantee_2 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
170 my $guarantee_3 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
171 $siblings = $retrieved_guarantee_1->siblings;
172 is( $siblings->count, 2, 'guarantee_1 should have 2 siblings' );
173 is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
174 is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
175 $_->delete for $retrieved_guarantee_1->siblings;
176 $retrieved_guarantee_1->delete;
179 subtest 'has_overdues' => sub {
182 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
183 my $item_1 = $builder->build(
186 homebranch => $library->{branchcode},
187 holdingbranch => $library->{branchcode},
191 biblionumber => $biblioitem_1->{biblionumber}
195 my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
196 is( $retrieved_patron->has_overdues, 0, );
198 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
199 my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
200 is( $retrieved_patron->has_overdues, 0, );
202 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
203 $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
204 $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
205 is( $retrieved_patron->has_overdues, 1, );
209 subtest 'update_password' => sub {
212 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
213 my $original_userid = $new_patron_1->userid;
214 my $original_password = $new_patron_1->password;
215 warning_like { $retrieved_patron_1->update_password( $new_patron_2->userid, 'another_password' ) }
217 'Koha::Patron->update_password should warn if the userid is already used by another patron';
218 is( Koha::Patrons->find( $new_patron_1->borrowernumber )->userid, $original_userid, 'Koha::Patron->update_password should not have updated the userid' );
219 is( Koha::Patrons->find( $new_patron_1->borrowernumber )->password, $original_password, 'Koha::Patron->update_password should not have updated the userid' );
221 my $digest = $retrieved_patron_1->update_password( 'another_nonexistent_userid_1', 'another_password' );
222 is( Koha::Patrons->find( $new_patron_1->borrowernumber )->userid, 'another_nonexistent_userid_1', 'Koha::Patron->update_password should have updated the userid' );
223 is( Koha::Patrons->find( $new_patron_1->borrowernumber )->password, $digest, 'Koha::Patron->update_password should have updated the password' );
225 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $new_patron_1->borrowernumber } )->count;
226 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->update_password should have logged' );
228 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
229 $retrieved_patron_1->update_password( 'yet_another_nonexistent_userid_1', 'another_password' );
230 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $new_patron_1->borrowernumber } )->count;
231 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->update_password should not have logged' );
234 subtest 'is_expired' => sub {
236 my $patron = $builder->build({ source => 'Borrower' });
237 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
238 $patron->dateexpiry( undef )->store->discard_changes;
239 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
240 $patron->dateexpiry( dt_from_string )->store->discard_changes;
241 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
242 $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
243 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
244 $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
245 is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
250 subtest 'is_going_to_expire' => sub {
252 my $patron = $builder->build({ source => 'Borrower' });
253 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
254 $patron->dateexpiry( undef )->store->discard_changes;
255 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
257 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
258 $patron->dateexpiry( dt_from_string )->store->discard_changes;
259 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
261 $patron->dateexpiry( dt_from_string )->store->discard_changes;
262 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
264 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
265 $patron->dateexpiry( dt_from_string->add( days => 11 ) )->store->discard_changes;
266 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');
268 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
269 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
270 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');
272 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
273 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
274 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');
277 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
278 $patron->dateexpiry( dt_from_string->add( days => 20 ) )->store->discard_changes;
279 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');
281 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
282 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
283 is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
289 subtest 'renew_account' => sub {
292 for my $date ( '2016-03-31', '2016-11-30', dt_from_string() ) {
293 my $dt = dt_from_string( $date, 'iso' );
294 Time::Fake->offset( $dt->epoch );
295 my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
296 my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
297 my $a_year_later_minus_a_month = $dt->clone->add( months => 11, end_of_month => 'limit' )->truncate( to => 'day' );
298 my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
299 my $a_year_later_plus_a_month = $dt->clone->add( months => 13, end_of_month => 'limit' )->truncate( to => 'day' );
300 my $patron_category = $builder->build(
301 { source => 'Category',
303 enrolmentperiod => 12,
304 enrolmentperioddate => undef,
308 my $patron = $builder->build(
309 { source => 'Borrower',
311 dateexpiry => $a_month_ago,
312 categorycode => $patron_category->{categorycode},
313 date_renewed => undef, # Force builder to not populate the column for new patron
317 my $patron_2 = $builder->build(
318 { source => 'Borrower',
320 dateexpiry => $a_month_ago,
321 categorycode => $patron_category->{categorycode},
325 my $patron_3 = $builder->build(
326 { source => 'Borrower',
328 dateexpiry => $a_month_later,
329 categorycode => $patron_category->{categorycode},
333 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
334 my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
335 my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
337 is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
339 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
340 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
341 my $expiry_date = $retrieved_patron->renew_account;
342 is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
343 my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
344 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" );
345 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
346 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
348 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
349 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
350 $expiry_date = $retrieved_patron->renew_account;
351 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
352 $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
353 is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
354 $retrieved_expiry_date = $retrieved_patron->dateexpiry;
355 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
356 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
357 is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
359 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
360 $expiry_date = $retrieved_patron_2->renew_account;
361 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
362 $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
363 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
365 $expiry_date = $retrieved_patron_3->renew_account;
366 is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
367 $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
368 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" );
370 $retrieved_patron->delete;
371 $retrieved_patron_2->delete;
372 $retrieved_patron_3->delete;
377 subtest "move_to_deleted" => sub {
379 my $originally_updated_on = '2016-01-01 12:12:12';
380 my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
381 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
382 is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
383 ; # FIXME This should be Koha::Deleted::Patron
384 my $deleted_patron = $schema->resultset('Deletedborrower')
385 ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
387 ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
388 ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
389 isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
390 $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
391 is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
392 $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup
395 subtest "delete" => sub {
397 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
398 my $patron = $builder->build( { source => 'Borrower' } );
399 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
400 my $hold = $builder->build(
401 { source => 'Reserve',
402 value => { borrowernumber => $patron->{borrowernumber} }
405 my $list = $builder->build(
406 { source => 'Virtualshelve',
407 value => { owner => $patron->{borrowernumber} }
411 my $deleted = $retrieved_patron->delete;
412 is( $deleted, 1, 'Koha::Patron->delete should return 1 if the patron has been correctly deleted' );
414 is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
416 is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's holds| );
418 is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
420 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
421 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
424 subtest 'add_enrolment_fee_if_needed' => sub {
427 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
428 foreach( keys %{$enrolmentfees} ) {
429 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
431 my $enrolmentfee_K = $enrolmentfees->{K};
432 my $enrolmentfee_J = $enrolmentfees->{J};
433 my $enrolmentfee_YA = $enrolmentfees->{YA};
435 my %borrower_data = (
436 firstname => 'my firstname',
437 surname => 'my surname',
439 branchcode => $library->{branchcode},
442 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
443 $borrower_data{borrowernumber} = $borrowernumber;
445 my $patron = Koha::Patrons->find( $borrowernumber );
446 my $total = $patron->account->balance;
447 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
449 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
450 $borrower_data{categorycode} = 'J';
451 $patron->set(\%borrower_data)->store;
452 $total = $patron->account->balance;
453 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
455 $borrower_data{categorycode} = 'K';
456 $patron->set(\%borrower_data)->store;
457 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
459 $borrower_data{categorycode} = 'J';
460 $patron->set(\%borrower_data)->store;
461 $total = $patron->account->balance;
462 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
464 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
465 $patron->categorycode('YA')->store;
466 $total = $patron->account->balance;
468 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
469 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
475 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
478 my $library = $builder->build( { source => 'Branch' } );
479 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
480 my $item_1 = $builder->build(
484 homebranch => $library->{branchcode},
485 holdingbranch => $library->{branchcode},
486 biblionumber => $biblionumber_1,
492 my $item_2 = $builder->build(
496 homebranch => $library->{branchcode},
497 holdingbranch => $library->{branchcode},
498 biblionumber => $biblionumber_1,
504 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
505 my $item_3 = $builder->build(
509 homebranch => $library->{branchcode},
510 holdingbranch => $library->{branchcode},
511 biblionumber => $biblionumber_2,
517 my $patron = $builder->build(
519 source => 'Borrower',
520 value => { branchcode => $library->{branchcode} }
524 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
525 my $checkouts = $patron->checkouts;
526 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
527 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
528 my $pending_checkouts = $patron->pending_checkouts;
529 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
530 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
531 my $old_checkouts = $patron->old_checkouts;
532 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
533 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
535 # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
536 $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
538 my $module = new Test::MockModule('C4::Context');
539 $module->mock( 'userenv', sub { { branch => $library->{branchcode} } } );
541 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
542 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
543 AddIssue( $patron, $item_3->{barcode} );
545 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
546 $checkouts = $patron->checkouts;
547 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
548 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
549 $pending_checkouts = $patron->pending_checkouts;
550 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
551 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
553 my $first_checkout = $pending_checkouts->next;
554 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
556 my $overdues = $patron->get_overdues;
557 is( $overdues->count, 2, 'Patron should have 2 overdues');
558 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
559 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
560 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
563 C4::Circulation::AddReturn( $item_1->{barcode} );
564 C4::Circulation::AddReturn( $item_2->{barcode} );
565 $old_checkouts = $patron->old_checkouts;
566 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
567 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
570 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
572 $module->unmock('userenv');
575 subtest 'get_routing_lists' => sub {
578 my $biblio = Koha::Biblio->new()->store();
579 my $subscription = Koha::Subscription->new({
580 biblionumber => $biblio->biblionumber,
584 my $patron = $builder->build( { source => 'Borrower' } );
585 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
587 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
589 my $routinglist_count = Koha::Subscription::Routinglists->count;
590 my $routinglist = Koha::Subscription::Routinglist->new({
591 borrowernumber => $patron->borrowernumber,
593 subscriptionid => $subscription->subscriptionid
596 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
598 my $routinglists = $patron->get_routing_lists;
599 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
600 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
602 my $subscription2 = Koha::Subscription->new({
603 biblionumber => $biblio->biblionumber,
606 my $routinglist2 = Koha::Subscription::Routinglist->new({
607 borrowernumber => $patron->borrowernumber,
609 subscriptionid => $subscription2->subscriptionid
612 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
614 $patron->delete; # Clean up for later tests
618 subtest 'get_age' => sub {
621 my $patron = $builder->build( { source => 'Borrower' } );
622 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
624 my $today = dt_from_string;
626 $patron->dateofbirth( undef );
627 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
628 $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1, end_of_month => 'limit' ) );
629 is( $patron->get_age, 12, 'Patron should be 12' );
630 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 1, end_of_month => 'limit' ) );
631 is( $patron->get_age, 17, 'Patron should be 17, happy birthday tomorrow!' );
632 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 0, end_of_month => 'limit' ) );
633 is( $patron->get_age, 18, 'Patron should be 18' );
634 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -31, end_of_month => 'limit' ) );
635 is( $patron->get_age, 19, 'Patron should be 19' );
636 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -30, end_of_month => 'limit' ) );
637 is( $patron->get_age, 19, 'Patron should be 19 again' );
638 $patron->dateofbirth( $today->clone->add( years => 0, months => -1, days => -1, end_of_month => 'limit' ) );
639 is( $patron->get_age, 0, 'Patron is a newborn child' );
644 subtest 'account' => sub {
647 my $patron = $builder->build({source => 'Borrower'});
649 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
650 my $account = $patron->account;
651 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
656 subtest 'search_upcoming_membership_expires' => sub {
659 my $expiry_days = 15;
660 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
661 my $nb_of_days_before = 1;
662 my $nb_of_days_after = 2;
664 my $builder = t::lib::TestBuilder->new();
666 my $library = $builder->build({ source => 'Branch' });
668 # before we add borrowers to this branch, add the expires we have now
669 # note that this pertains to the current mocked setting of the pref
670 # for this reason we add the new branchcode to most of the tests
671 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
673 my $patron_1 = $builder->build({
674 source => 'Borrower',
676 branchcode => $library->{branchcode},
677 dateexpiry => dt_from_string->add( days => $expiry_days )
681 my $patron_2 = $builder->build({
682 source => 'Borrower',
684 branchcode => $library->{branchcode},
685 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
689 my $patron_3 = $builder->build({
690 source => 'Borrower',
692 branchcode => $library->{branchcode},
693 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
697 # Test without extra parameters
698 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
699 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
702 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
703 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
704 my $expired = $upcoming_mem_expires->next;
705 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
706 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
707 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
709 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
710 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
711 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
713 # Test MembershipExpiryDaysNotice == undef
714 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
715 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
716 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
718 # Test the before parameter
719 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
720 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
721 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
722 # Test after parameter also
723 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
724 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
725 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
728 subtest 'holds and old_holds' => sub {
731 my $library = $builder->build( { source => 'Branch' } );
732 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
733 my $item_1 = $builder->build(
737 homebranch => $library->{branchcode},
738 holdingbranch => $library->{branchcode},
739 biblionumber => $biblionumber_1
743 my $item_2 = $builder->build(
747 homebranch => $library->{branchcode},
748 holdingbranch => $library->{branchcode},
749 biblionumber => $biblionumber_1
753 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
754 my $item_3 = $builder->build(
758 homebranch => $library->{branchcode},
759 holdingbranch => $library->{branchcode},
760 biblionumber => $biblionumber_2
764 my $patron = $builder->build(
766 source => 'Borrower',
767 value => { branchcode => $library->{branchcode} }
771 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
772 my $holds = $patron->holds;
773 is( ref($holds), 'Koha::Holds',
774 'Koha::Patron->holds should return a Koha::Holds objects' );
775 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
777 C4::Reserves::AddReserve( $library->{branchcode},
778 $patron->borrowernumber, $biblionumber_1 );
780 C4::Reserves::AddReserve( $library->{branchcode},
781 $patron->borrowernumber, $biblionumber_2, undef, undef, dt_from_string->add( days => 2 ) );
783 $holds = $patron->holds;
784 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
786 my $old_holds = $patron->old_holds;
787 is( ref($old_holds), 'Koha::Old::Holds',
788 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
789 is( $old_holds->count, 0, 'There should not be any old holds yet');
791 my $hold = $holds->next;
794 $old_holds = $patron->old_holds;
795 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
802 subtest 'notice_email_address' => sub {
805 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
807 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
808 is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
810 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
811 is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
816 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
819 # TODO create a subroutine in t::lib::Mocks
820 my $branch = $builder->build({ source => 'Branch' });
821 my $userenv_patron = $builder->build({
822 source => 'Borrower',
823 value => { branchcode => $branch->{branchcode} },
825 C4::Context->_new_userenv('DUMMY SESSION');
826 C4::Context->set_userenv(
827 $userenv_patron->{borrowernumber},
828 $userenv_patron->{userid},
829 'usercnum', 'First name', 'Surname',
830 $branch->{branchcode},
831 $branch->{branchname},
834 my $anonymous = $builder->build( { source => 'Borrower', }, );
836 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
838 subtest 'patron privacy is 1 (default)' => sub {
841 t::lib::Mocks::mock_preference('IndependentBranches', 0);
842 my $patron = $builder->build(
843 { source => 'Borrower',
844 value => { privacy => 1, }
847 my $item_1 = $builder->build(
855 my $issue_1 = $builder->build(
858 borrowernumber => $patron->{borrowernumber},
859 itemnumber => $item_1->{itemnumber},
863 my $item_2 = $builder->build(
871 my $issue_2 = $builder->build(
874 borrowernumber => $patron->{borrowernumber},
875 itemnumber => $item_2->{itemnumber},
880 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, undef, '2010-10-10' );
881 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, undef, '2011-11-11' );
882 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
884 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
885 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
887 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
888 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
890 my $dbh = C4::Context->dbh;
891 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
892 $sth->execute($item_1->{itemnumber});
893 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
894 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
895 $sth->execute($item_2->{itemnumber});
896 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
897 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
899 $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
900 $sth->execute($item_2->{itemnumber});
901 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
902 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
904 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
905 $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
906 $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
907 $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
908 $sth->execute($item_1->{itemnumber});
909 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
910 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
911 $sth->execute($item_2->{itemnumber});
912 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
913 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
915 Koha::Patrons->find( $patron->{borrowernumber})->delete;
918 subtest 'patron privacy is 0 (forever)' => sub {
921 t::lib::Mocks::mock_preference('IndependentBranches', 0);
922 my $patron = $builder->build(
923 { source => 'Borrower',
924 value => { privacy => 0, }
927 my $item = $builder->build(
935 my $issue = $builder->build(
938 borrowernumber => $patron->{borrowernumber},
939 itemnumber => $item->{itemnumber},
944 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
945 is( $returned, 1, 'The item should have been returned' );
946 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
947 ok( $rows_affected > 0, 'AnonymiseIssueHistory should not return any error if success' );
949 my $dbh = C4::Context->dbh;
950 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
951 SELECT borrowernumber FROM old_issues where itemnumber = ?
952 |, undef, $item->{itemnumber});
953 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
954 Koha::Patrons->find( $patron->{borrowernumber})->delete;
957 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
959 subtest 'AnonymousPatron is not defined' => sub {
962 t::lib::Mocks::mock_preference('IndependentBranches', 0);
963 my $patron = $builder->build(
964 { source => 'Borrower',
965 value => { privacy => 1, }
968 my $item = $builder->build(
976 my $issue = $builder->build(
979 borrowernumber => $patron->{borrowernumber},
980 itemnumber => $item->{itemnumber},
985 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
986 is( $returned, 1, 'The item should have been returned' );
987 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
988 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
990 my $dbh = C4::Context->dbh;
991 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
992 SELECT borrowernumber FROM old_issues where itemnumber = ?
993 |, undef, $item->{itemnumber});
994 is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
995 Koha::Patrons->find( $patron->{borrowernumber})->delete;
998 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1000 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1001 my $patron = $builder->build(
1002 { source => 'Borrower',
1003 value => { privacy => 1 } # Another branchcode than the logged in librarian
1006 my $item = $builder->build(
1014 my $issue = $builder->build(
1015 { source => 'Issue',
1017 borrowernumber => $patron->{borrowernumber},
1018 itemnumber => $item->{itemnumber},
1023 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
1024 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1025 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1028 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1029 Koha::Patrons->find( $userenv_patron->{borrowernumber})->delete;
1031 # Reset IndependentBranches for further tests
1032 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1035 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1043 $nb_of_patrons = Koha::Patrons->search->count;
1044 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1045 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1046 my $library_11 = $builder->build( { source => 'Branch' } );
1047 my $library_12 = $builder->build( { source => 'Branch' } );
1048 my $library_21 = $builder->build( { source => 'Branch' } );
1049 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1050 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1051 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1052 Koha::Library::Group->new(
1053 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1054 Koha::Library::Group->new(
1055 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1056 Koha::Library::Group->new(
1057 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1059 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1060 # 2 patrons from library_11 (group1)
1061 # patron_11_1 see patron's infos from outside its group
1062 # Setting flags => undef to not be considered as superlibrarian
1063 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1064 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1065 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1066 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1067 # patron_11_2 can only see patron's info from its group
1068 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1069 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1070 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1071 # 1 patron from library_12 (group1)
1072 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1073 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1074 # 1 patron from library_21 (group2) can only see patron's info from its group
1075 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1076 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1077 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1079 # Pfiou, we can start now!
1080 subtest 'libraries_where_can_see_patrons' => sub {
1085 set_logged_in_user( $patron_11_1 );
1086 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1087 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1089 set_logged_in_user( $patron_11_2 );
1090 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1091 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| );
1093 set_logged_in_user( $patron_21 );
1094 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1095 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| );
1097 subtest 'can_see_patron_infos' => sub {
1100 set_logged_in_user( $patron_11_1 );
1101 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1102 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1103 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1105 set_logged_in_user( $patron_11_2 );
1106 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1107 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1108 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1110 subtest 'search_limited' => sub {
1113 set_logged_in_user( $patron_11_1 );
1114 my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1115 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1116 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1118 set_logged_in_user( $patron_11_2 );
1119 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1120 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' );
1122 set_logged_in_user( $patron_21 );
1123 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1124 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1126 $patron_11_1->delete;
1127 $patron_11_2->delete;
1132 subtest 'account_locked' => sub {
1134 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1135 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1136 for my $value ( undef, '', 0 ) {
1137 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1138 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1139 $patron->login_attempts(1)->store;
1140 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1143 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1144 $patron->login_attempts(2)->store;
1145 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1146 $patron->login_attempts(3)->store;
1147 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1152 subtest 'is_child | is_adult' => sub {
1154 my $category = $builder->build_object(
1156 class => 'Koha::Patron::Categories',
1157 value => { category_type => 'A' }
1160 my $patron_adult = $builder->build_object(
1162 class => 'Koha::Patrons',
1163 value => { categorycode => $category->categorycode }
1166 $category = $builder->build_object(
1168 class => 'Koha::Patron::Categories',
1169 value => { category_type => 'I' }
1172 my $patron_adult_i = $builder->build_object(
1174 class => 'Koha::Patrons',
1175 value => { categorycode => $category->categorycode }
1178 $category = $builder->build_object(
1180 class => 'Koha::Patron::Categories',
1181 value => { category_type => 'C' }
1184 my $patron_child = $builder->build_object(
1186 class => 'Koha::Patrons',
1187 value => { categorycode => $category->categorycode }
1190 $category = $builder->build_object(
1192 class => 'Koha::Patron::Categories',
1193 value => { category_type => 'O' }
1196 my $patron_other = $builder->build_object(
1198 class => 'Koha::Patrons',
1199 value => { categorycode => $category->categorycode }
1202 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1203 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1204 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1205 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1207 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1208 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1209 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1210 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1213 $patron_adult->delete;
1214 $patron_adult_i->delete;
1215 $patron_child->delete;
1216 $patron_other->delete;
1219 subtest 'get_overdues' => sub {
1222 my $library = $builder->build( { source => 'Branch' } );
1223 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1224 my $item_1 = $builder->build(
1228 homebranch => $library->{branchcode},
1229 holdingbranch => $library->{branchcode},
1230 biblionumber => $biblionumber_1
1234 my $item_2 = $builder->build(
1238 homebranch => $library->{branchcode},
1239 holdingbranch => $library->{branchcode},
1240 biblionumber => $biblionumber_1
1244 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1245 my $item_3 = $builder->build(
1249 homebranch => $library->{branchcode},
1250 holdingbranch => $library->{branchcode},
1251 biblionumber => $biblionumber_2
1255 my $patron = $builder->build(
1257 source => 'Borrower',
1258 value => { branchcode => $library->{branchcode} }
1262 my $module = new Test::MockModule('C4::Context');
1263 $module->mock( 'userenv', sub { { branch => $library->{branchcode} } } );
1265 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1266 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1267 AddIssue( $patron, $item_3->{barcode} );
1269 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1270 my $overdues = $patron->get_overdues;
1271 is( $overdues->count, 2, 'Patron should have 2 overdues');
1272 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1273 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1275 my $o = $overdues->reset->next;
1276 my $unblessed_overdue = $o->unblessed_all_relateds;
1277 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1278 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1279 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1280 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1283 $patron->checkouts->delete;
1287 subtest 'userid_is_valid' => sub {
1290 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1291 my $patron_category = $builder->build_object(
1293 class => 'Koha::Patron::Categories',
1294 value => { category_type => 'P', enrolmentfee => 0 }
1298 cardnumber => "123456789",
1299 firstname => "Tomasito",
1301 categorycode => $patron_category->categorycode,
1302 branchcode => $library->branchcode,
1305 my $expected_userid_patron_1 = 'tomasito.none';
1306 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1307 my $patron_1 = Koha::Patrons->find($borrowernumber);
1308 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1310 $patron_1->userid( 'tomasito.non' );
1311 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1312 1, 'recently created userid -> unique (borrowernumber passed)' );
1314 $patron_1->userid( 'tomasitoxxx' );
1315 is( $patron_1->has_valid_userid,
1316 1, 'non-existent userid -> unique (borrowernumber passed)' );
1317 $patron_1->discard_changes; # We compare with the original userid later
1319 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1320 is( $patron_not_in_storage->has_valid_userid,
1321 0, 'userid exists for another patron, patron is not in storage yet' );
1323 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1324 is( $patron_not_in_storage->has_valid_userid,
1325 1, 'non-existent userid, patron is not in storage yet' );
1327 # Regression tests for BZ12226
1328 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1329 is( $db_patron->has_valid_userid,
1330 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1332 # Add a new borrower with the same userid but different cardnumber
1333 $data{cardnumber} = "987654321";
1334 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1335 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1336 $patron_2->userid($patron_1->userid);
1337 is( $patron_2->has_valid_userid,
1338 0, 'The userid is already in used, it cannot be used for another patron' );
1340 my $new_userid = 'a_user_id';
1341 $data{cardnumber} = "234567890";
1342 $data{userid} = 'a_user_id';
1343 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1344 my $patron_3 = Koha::Patrons->find($borrowernumber);
1345 is( $patron_3->userid, $new_userid,
1346 'Koha::Patron->store should insert the given userid' );
1354 subtest 'generate_userid' => sub {
1357 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1358 my $patron_category = $builder->build_object(
1360 class => 'Koha::Patron::Categories',
1361 value => { category_type => 'P', enrolmentfee => 0 }
1365 cardnumber => "123456789",
1366 firstname => "Tomasito",
1368 categorycode => $patron_category->categorycode,
1369 branchcode => $library->branchcode,
1372 my $expected_userid_patron_1 = 'tomasito.none';
1373 my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1374 $new_patron->generate_userid;
1375 my $userid = $new_patron->userid;
1376 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1377 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1378 my $patron_1 = Koha::Patrons->find($borrowernumber);
1379 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1381 $new_patron->generate_userid;
1382 $userid = $new_patron->userid;
1383 is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1384 $data{cardnumber} = '987654321';
1385 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1386 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1387 isnt( $patron_2->userid, 'tomasito',
1388 "Patron with duplicate userid has new userid generated" );
1389 is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1390 "Patron with duplicate userid has new userid generated (1 is appened" );
1392 $new_patron->generate_userid;
1393 $userid = $new_patron->userid;
1394 is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1396 $patron_1 = Koha::Patrons->find($borrowernumber);
1397 $patron_1->userid(undef);
1398 $patron_1->generate_userid;
1399 $userid = $patron_1->userid;
1400 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1407 $nb_of_patrons = Koha::Patrons->search->count;
1408 $retrieved_patron_1->delete;
1409 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1411 subtest 'Log cardnumber change' => sub {
1414 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1415 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1417 my $cardnumber = $patron->cardnumber;
1418 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1421 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1422 my $log_info = from_json( $logs[0]->info );
1423 is( $log_info->{cardnumber_replaced}->{new_cardnumber}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1424 is( $log_info->{cardnumber_replaced}->{previous_cardnumber}, $cardnumber, 'Got correct old cardnumber' );
1425 is( scalar @logs, 2, 'With BorrowerLogs, Change in cardnumber should be logged, as well as general alert of patron mod.' );
1428 $schema->storage->txn_rollback;
1430 subtest 'Test Koha::Patrons::merge' => sub {
1433 my $schema = Koha::Database->new()->schema();
1435 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1437 $schema->storage->txn_begin;
1439 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1440 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1441 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1443 while (my ($r, $field) = each(%$resultsets)) {
1444 $builder->build({ source => $r, value => { $field => $keeper->id } });
1445 $builder->build({ source => $r, value => { $field => $loser_1 } });
1446 $builder->build({ source => $r, value => { $field => $loser_2 } });
1449 $schema->resultset($r)->search( { $field => $keeper->id } );
1450 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1453 $schema->resultset($r)->search( { $field => $loser_1 } );
1454 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1457 $schema->resultset($r)->search( { $field => $loser_2 } );
1458 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1461 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1463 while (my ($r, $field) = each(%$resultsets)) {
1465 $schema->resultset($r)->search( {$field => $keeper->id } );
1466 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1469 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1470 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1472 $schema->storage->txn_rollback;
1475 subtest '->store' => sub {
1477 my $schema = Koha::Database->new->schema;
1478 $schema->storage->txn_begin;
1480 my $print_error = $schema->storage->dbh->{PrintError};
1481 $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1483 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1484 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1487 { $patron_2->userid($patron_1->userid)->store; }
1488 'Koha::Exceptions::Object::DuplicateID',
1489 'Koha::Patron->store raises an exception on duplicate ID';
1492 my $password = 'password';
1493 $patron_1->update_password($patron_1->userid, $password);
1494 like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1495 my $digest = $patron_1->password;
1496 $patron_1->surname('xxx')->store;
1497 is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1499 $schema->storage->dbh->{PrintError} = $print_error;
1500 $schema->storage->txn_rollback;
1503 subtest '->set_password' => sub {
1507 $schema->storage->txn_begin;
1509 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1511 # Disable logging password changes for this tests
1512 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1514 # Password-length tests
1515 t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1516 throws_ok { $patron->set_password('ab'); }
1517 'Koha::Exceptions::Password::TooShort',
1518 'minPasswordLength is undef, fall back to 3, fail test';
1520 t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1521 throws_ok { $patron->set_password('ab'); }
1522 'Koha::Exceptions::Password::TooShort',
1523 'minPasswordLength is 2, fall back to 3, fail test';
1525 t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1526 throws_ok { $patron->set_password('abcb'); }
1527 'Koha::Exceptions::Password::TooShort',
1528 'minPasswordLength is 5, fail test';
1530 # Trailing spaces tests
1531 throws_ok { $patron->set_password('abcD12d '); }
1532 'Koha::Exceptions::Password::WhitespaceCharacters',
1533 'Password contains trailing spaces, exception is thrown';
1535 # Require strong password tests
1536 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1537 throws_ok { $patron->set_password('abcd a'); }
1538 'Koha::Exceptions::Password::TooWeak',
1539 'Password is too weak, exception is thrown';
1541 # Refresh patron from DB, just to make sure
1542 $patron->discard_changes;
1543 is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1545 $patron->set_password('abcD12 34');
1546 $patron->discard_changes;
1548 is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1551 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1552 $patron->login_attempts(3)->store;
1553 my $old_digest = $patron->password;
1554 $patron->set_password('abcd a');
1555 $patron->discard_changes;
1557 isnt( $patron->password, $old_digest, 'Password has been updated' );
1558 is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1560 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1561 is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1563 # Enable logging password changes
1564 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1565 $patron->set_password('abcd b');
1567 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1568 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1570 $schema->storage->txn_rollback;
1575 # TODO Move to t::lib::Mocks and reuse it!
1576 sub set_logged_in_user {
1578 C4::Context->set_userenv(
1579 $patron->borrowernumber, $patron->userid,
1580 $patron->cardnumber, 'firstname',
1581 'surname', $patron->library->branchcode,
1582 'Midway Public Library', $patron->flags,