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 => 32;
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;
106 subtest 'category' => sub {
108 my $patron_category = $new_patron_1->category;
109 is( ref( $patron_category), 'Koha::Patron::Category', );
110 is( $patron_category->categorycode, $category->{categorycode}, );
113 subtest 'siblings' => sub {
115 my $siblings = $new_patron_1->siblings;
116 is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
117 my $guarantee_1 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
118 my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
119 $siblings = $retrieved_guarantee_1->siblings;
120 is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
121 my @siblings = $retrieved_guarantee_1->siblings;
122 is( ref( \@siblings ), 'ARRAY', 'Koha::Patron->siblings should return an array in a list context' );
123 is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' );
124 my $guarantee_2 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
125 my $guarantee_3 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
126 $siblings = $retrieved_guarantee_1->siblings;
127 is( $siblings->count, 2, 'guarantee_1 should have 2 siblings' );
128 is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
129 is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
130 $_->delete for $retrieved_guarantee_1->siblings;
131 $retrieved_guarantee_1->delete;
134 subtest 'has_overdues' => sub {
137 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
138 my $item_1 = $builder->build(
141 homebranch => $library->{branchcode},
142 holdingbranch => $library->{branchcode},
146 biblionumber => $biblioitem_1->{biblionumber}
150 my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
151 is( $retrieved_patron->has_overdues, 0, );
153 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
154 my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
155 is( $retrieved_patron->has_overdues, 0, );
157 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
158 $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
159 $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
160 is( $retrieved_patron->has_overdues, 1, );
164 subtest 'update_password' => sub {
167 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
168 my $original_userid = $new_patron_1->userid;
169 my $original_password = $new_patron_1->password;
170 warning_like { $retrieved_patron_1->update_password( $new_patron_2->userid, 'another_password' ) }
172 'Koha::Patron->update_password should warn if the userid is already used by another patron';
173 is( Koha::Patrons->find( $new_patron_1->borrowernumber )->userid, $original_userid, 'Koha::Patron->update_password should not have updated the userid' );
174 is( Koha::Patrons->find( $new_patron_1->borrowernumber )->password, $original_password, 'Koha::Patron->update_password should not have updated the userid' );
176 $retrieved_patron_1->update_password( 'another_nonexistent_userid_1', 'another_password' );
177 is( Koha::Patrons->find( $new_patron_1->borrowernumber )->userid, 'another_nonexistent_userid_1', 'Koha::Patron->update_password should have updated the userid' );
178 is( Koha::Patrons->find( $new_patron_1->borrowernumber )->password, 'another_password', 'Koha::Patron->update_password should have updated the password' );
180 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $new_patron_1->borrowernumber } )->count;
181 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->update_password should have logged' );
183 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
184 $retrieved_patron_1->update_password( 'yet_another_nonexistent_userid_1', 'another_password' );
185 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $new_patron_1->borrowernumber } )->count;
186 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->update_password should not have logged' );
189 subtest 'is_expired' => sub {
191 my $patron = $builder->build({ source => 'Borrower' });
192 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
193 $patron->dateexpiry( undef )->store->discard_changes;
194 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
195 $patron->dateexpiry( dt_from_string )->store->discard_changes;
196 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
197 $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
198 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
199 $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
200 is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
205 subtest 'is_going_to_expire' => sub {
207 my $patron = $builder->build({ source => 'Borrower' });
208 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
209 $patron->dateexpiry( undef )->store->discard_changes;
210 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
212 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
213 $patron->dateexpiry( dt_from_string )->store->discard_changes;
214 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
216 $patron->dateexpiry( dt_from_string )->store->discard_changes;
217 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
219 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
220 $patron->dateexpiry( dt_from_string->add( days => 11 ) )->store->discard_changes;
221 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');
223 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
224 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
225 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');
227 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
228 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
229 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');
232 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
233 $patron->dateexpiry( dt_from_string->add( days => 20 ) )->store->discard_changes;
234 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');
236 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
237 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
238 is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
244 subtest 'renew_account' => sub {
247 for my $date ( '2016-03-31', '2016-11-30', dt_from_string() ) {
248 my $dt = dt_from_string( $date, 'iso' );
249 Time::Fake->offset( $dt->epoch );
250 my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
251 my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
252 my $a_year_later_minus_a_month = $dt->clone->add( months => 11, end_of_month => 'limit' )->truncate( to => 'day' );
253 my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
254 my $a_year_later_plus_a_month = $dt->clone->add( months => 13, end_of_month => 'limit' )->truncate( to => 'day' );
255 my $patron_category = $builder->build(
256 { source => 'Category',
258 enrolmentperiod => 12,
259 enrolmentperioddate => undef,
263 my $patron = $builder->build(
264 { source => 'Borrower',
266 dateexpiry => $a_month_ago,
267 categorycode => $patron_category->{categorycode},
268 date_renewed => undef, # Force builder to not populate the column for new patron
272 my $patron_2 = $builder->build(
273 { source => 'Borrower',
275 dateexpiry => $a_month_ago,
276 categorycode => $patron_category->{categorycode},
280 my $patron_3 = $builder->build(
281 { source => 'Borrower',
283 dateexpiry => $a_month_later,
284 categorycode => $patron_category->{categorycode},
288 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
289 my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
290 my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
292 is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
294 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
295 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
296 my $expiry_date = $retrieved_patron->renew_account;
297 is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
298 my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
299 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" );
300 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
301 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
303 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
304 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
305 $expiry_date = $retrieved_patron->renew_account;
306 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
307 $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
308 is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
309 $retrieved_expiry_date = $retrieved_patron->dateexpiry;
310 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
311 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
312 is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
314 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
315 $expiry_date = $retrieved_patron_2->renew_account;
316 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
317 $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
318 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
320 $expiry_date = $retrieved_patron_3->renew_account;
321 is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
322 $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
323 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" );
325 $retrieved_patron->delete;
326 $retrieved_patron_2->delete;
327 $retrieved_patron_3->delete;
332 subtest "move_to_deleted" => sub {
334 my $originally_updated_on = '2016-01-01 12:12:12';
335 my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
336 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
337 is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
338 ; # FIXME This should be Koha::Deleted::Patron
339 my $deleted_patron = $schema->resultset('Deletedborrower')
340 ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
342 ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
343 ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
344 isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
345 $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
346 is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
347 $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup
350 subtest "delete" => sub {
352 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
353 my $patron = $builder->build( { source => 'Borrower' } );
354 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
355 my $hold = $builder->build(
356 { source => 'Reserve',
357 value => { borrowernumber => $patron->{borrowernumber} }
360 my $list = $builder->build(
361 { source => 'Virtualshelve',
362 value => { owner => $patron->{borrowernumber} }
366 my $deleted = $retrieved_patron->delete;
367 is( $deleted, 1, 'Koha::Patron->delete should return 1 if the patron has been correctly deleted' );
369 is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
371 is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's holds| );
373 is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
375 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
376 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
379 subtest 'add_enrolment_fee_if_needed' => sub {
382 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
383 foreach( keys %{$enrolmentfees} ) {
384 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
386 my $enrolmentfee_K = $enrolmentfees->{K};
387 my $enrolmentfee_J = $enrolmentfees->{J};
388 my $enrolmentfee_YA = $enrolmentfees->{YA};
390 my %borrower_data = (
391 firstname => 'my firstname',
392 surname => 'my surname',
394 branchcode => $library->{branchcode},
397 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
398 $borrower_data{borrowernumber} = $borrowernumber;
400 my $patron = Koha::Patrons->find( $borrowernumber );
401 my $total = $patron->account->balance;
402 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
404 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
405 $borrower_data{categorycode} = 'J';
406 $patron->set(\%borrower_data)->store;
407 $total = $patron->account->balance;
408 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
410 $borrower_data{categorycode} = 'K';
411 $patron->set(\%borrower_data)->store;
412 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
414 $borrower_data{categorycode} = 'J';
415 $patron->set(\%borrower_data)->store;
416 $total = $patron->account->balance;
417 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
419 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
420 $patron->categorycode('YA')->store;
421 $total = $patron->account->balance;
423 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
424 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
430 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
433 my $library = $builder->build( { source => 'Branch' } );
434 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
435 my $item_1 = $builder->build(
439 homebranch => $library->{branchcode},
440 holdingbranch => $library->{branchcode},
441 biblionumber => $biblionumber_1,
447 my $item_2 = $builder->build(
451 homebranch => $library->{branchcode},
452 holdingbranch => $library->{branchcode},
453 biblionumber => $biblionumber_1,
459 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
460 my $item_3 = $builder->build(
464 homebranch => $library->{branchcode},
465 holdingbranch => $library->{branchcode},
466 biblionumber => $biblionumber_2,
472 my $patron = $builder->build(
474 source => 'Borrower',
475 value => { branchcode => $library->{branchcode} }
479 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
480 my $checkouts = $patron->checkouts;
481 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
482 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
483 my $pending_checkouts = $patron->pending_checkouts;
484 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
485 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
486 my $old_checkouts = $patron->old_checkouts;
487 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
488 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
490 # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
491 $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
493 my $module = new Test::MockModule('C4::Context');
494 $module->mock( 'userenv', sub { { branch => $library->{branchcode} } } );
496 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
497 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
498 AddIssue( $patron, $item_3->{barcode} );
500 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
501 $checkouts = $patron->checkouts;
502 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
503 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
504 $pending_checkouts = $patron->pending_checkouts;
505 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
506 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
508 my $first_checkout = $pending_checkouts->next;
509 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
511 my $overdues = $patron->get_overdues;
512 is( $overdues->count, 2, 'Patron should have 2 overdues');
513 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
514 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
515 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
518 C4::Circulation::AddReturn( $item_1->{barcode} );
519 C4::Circulation::AddReturn( $item_2->{barcode} );
520 $old_checkouts = $patron->old_checkouts;
521 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
522 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
525 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
527 $module->unmock('userenv');
530 subtest 'get_routing_lists' => sub {
533 my $biblio = Koha::Biblio->new()->store();
534 my $subscription = Koha::Subscription->new({
535 biblionumber => $biblio->biblionumber,
539 my $patron = $builder->build( { source => 'Borrower' } );
540 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
542 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
544 my $routinglist_count = Koha::Subscription::Routinglists->count;
545 my $routinglist = Koha::Subscription::Routinglist->new({
546 borrowernumber => $patron->borrowernumber,
548 subscriptionid => $subscription->subscriptionid
551 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
553 my $routinglists = $patron->get_routing_lists;
554 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
555 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
557 my $subscription2 = Koha::Subscription->new({
558 biblionumber => $biblio->biblionumber,
561 my $routinglist2 = Koha::Subscription::Routinglist->new({
562 borrowernumber => $patron->borrowernumber,
564 subscriptionid => $subscription2->subscriptionid
567 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
569 $patron->delete; # Clean up for later tests
573 subtest 'get_age' => sub {
576 my $patron = $builder->build( { source => 'Borrower' } );
577 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
579 my $today = dt_from_string;
581 $patron->dateofbirth( undef );
582 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
583 $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1, end_of_month => 'limit' ) );
584 is( $patron->get_age, 12, 'Patron should be 12' );
585 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 1, end_of_month => 'limit' ) );
586 is( $patron->get_age, 17, 'Patron should be 17, happy birthday tomorrow!' );
587 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 0, end_of_month => 'limit' ) );
588 is( $patron->get_age, 18, 'Patron should be 18' );
589 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -31, end_of_month => 'limit' ) );
590 is( $patron->get_age, 19, 'Patron should be 19' );
591 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -30, end_of_month => 'limit' ) );
592 is( $patron->get_age, 19, 'Patron should be 19 again' );
593 $patron->dateofbirth( $today->clone->add( years => 0, months => -1, days => -1, end_of_month => 'limit' ) );
594 is( $patron->get_age, 0, 'Patron is a newborn child' );
599 subtest 'account' => sub {
602 my $patron = $builder->build({source => 'Borrower'});
604 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
605 my $account = $patron->account;
606 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
611 subtest 'search_upcoming_membership_expires' => sub {
614 my $expiry_days = 15;
615 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
616 my $nb_of_days_before = 1;
617 my $nb_of_days_after = 2;
619 my $builder = t::lib::TestBuilder->new();
621 my $library = $builder->build({ source => 'Branch' });
623 # before we add borrowers to this branch, add the expires we have now
624 # note that this pertains to the current mocked setting of the pref
625 # for this reason we add the new branchcode to most of the tests
626 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
628 my $patron_1 = $builder->build({
629 source => 'Borrower',
631 branchcode => $library->{branchcode},
632 dateexpiry => dt_from_string->add( days => $expiry_days )
636 my $patron_2 = $builder->build({
637 source => 'Borrower',
639 branchcode => $library->{branchcode},
640 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
644 my $patron_3 = $builder->build({
645 source => 'Borrower',
647 branchcode => $library->{branchcode},
648 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
652 # Test without extra parameters
653 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
654 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
657 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
658 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
659 my $expired = $upcoming_mem_expires->next;
660 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
661 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
662 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
664 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
665 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
666 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
668 # Test MembershipExpiryDaysNotice == undef
669 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
670 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
671 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
673 # Test the before parameter
674 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
675 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
676 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
677 # Test after parameter also
678 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
679 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
680 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
683 subtest 'holds and old_holds' => sub {
686 my $library = $builder->build( { source => 'Branch' } );
687 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
688 my $item_1 = $builder->build(
692 homebranch => $library->{branchcode},
693 holdingbranch => $library->{branchcode},
694 biblionumber => $biblionumber_1
698 my $item_2 = $builder->build(
702 homebranch => $library->{branchcode},
703 holdingbranch => $library->{branchcode},
704 biblionumber => $biblionumber_1
708 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
709 my $item_3 = $builder->build(
713 homebranch => $library->{branchcode},
714 holdingbranch => $library->{branchcode},
715 biblionumber => $biblionumber_2
719 my $patron = $builder->build(
721 source => 'Borrower',
722 value => { branchcode => $library->{branchcode} }
726 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
727 my $holds = $patron->holds;
728 is( ref($holds), 'Koha::Holds',
729 'Koha::Patron->holds should return a Koha::Holds objects' );
730 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
732 C4::Reserves::AddReserve( $library->{branchcode},
733 $patron->borrowernumber, $biblionumber_1 );
735 C4::Reserves::AddReserve( $library->{branchcode},
736 $patron->borrowernumber, $biblionumber_2, undef, undef, dt_from_string->add( days => 2 ) );
738 $holds = $patron->holds;
739 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
741 my $old_holds = $patron->old_holds;
742 is( ref($old_holds), 'Koha::Old::Holds',
743 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
744 is( $old_holds->count, 0, 'There should not be any old holds yet');
746 my $hold = $holds->next;
749 $old_holds = $patron->old_holds;
750 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
757 subtest 'notice_email_address' => sub {
760 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
762 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
763 is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
765 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
766 is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
771 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
774 # TODO create a subroutine in t::lib::Mocks
775 my $branch = $builder->build({ source => 'Branch' });
776 my $userenv_patron = $builder->build({
777 source => 'Borrower',
778 value => { branchcode => $branch->{branchcode} },
780 C4::Context->_new_userenv('DUMMY SESSION');
781 C4::Context->set_userenv(
782 $userenv_patron->{borrowernumber},
783 $userenv_patron->{userid},
784 'usercnum', 'First name', 'Surname',
785 $branch->{branchcode},
786 $branch->{branchname},
789 my $anonymous = $builder->build( { source => 'Borrower', }, );
791 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
793 subtest 'patron privacy is 1 (default)' => sub {
796 t::lib::Mocks::mock_preference('IndependentBranches', 0);
797 my $patron = $builder->build(
798 { source => 'Borrower',
799 value => { privacy => 1, }
802 my $item_1 = $builder->build(
810 my $issue_1 = $builder->build(
813 borrowernumber => $patron->{borrowernumber},
814 itemnumber => $item_1->{itemnumber},
818 my $item_2 = $builder->build(
826 my $issue_2 = $builder->build(
829 borrowernumber => $patron->{borrowernumber},
830 itemnumber => $item_2->{itemnumber},
835 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, undef, '2010-10-10' );
836 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, undef, '2011-11-11' );
837 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
839 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
840 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
842 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
843 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
845 my $dbh = C4::Context->dbh;
846 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
847 $sth->execute($item_1->{itemnumber});
848 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
849 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
850 $sth->execute($item_2->{itemnumber});
851 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
852 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
854 $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
855 $sth->execute($item_2->{itemnumber});
856 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
857 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
859 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
860 $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
861 $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
862 $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
863 $sth->execute($item_1->{itemnumber});
864 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
865 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
866 $sth->execute($item_2->{itemnumber});
867 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
868 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
870 Koha::Patrons->find( $patron->{borrowernumber})->delete;
873 subtest 'patron privacy is 0 (forever)' => sub {
876 t::lib::Mocks::mock_preference('IndependentBranches', 0);
877 my $patron = $builder->build(
878 { source => 'Borrower',
879 value => { privacy => 0, }
882 my $item = $builder->build(
890 my $issue = $builder->build(
893 borrowernumber => $patron->{borrowernumber},
894 itemnumber => $item->{itemnumber},
899 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
900 is( $returned, 1, 'The item should have been returned' );
901 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
902 ok( $rows_affected > 0, 'AnonymiseIssueHistory should not return any error if success' );
904 my $dbh = C4::Context->dbh;
905 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
906 SELECT borrowernumber FROM old_issues where itemnumber = ?
907 |, undef, $item->{itemnumber});
908 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
909 Koha::Patrons->find( $patron->{borrowernumber})->delete;
912 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
914 subtest 'AnonymousPatron is not defined' => sub {
917 t::lib::Mocks::mock_preference('IndependentBranches', 0);
918 my $patron = $builder->build(
919 { source => 'Borrower',
920 value => { privacy => 1, }
923 my $item = $builder->build(
931 my $issue = $builder->build(
934 borrowernumber => $patron->{borrowernumber},
935 itemnumber => $item->{itemnumber},
940 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
941 is( $returned, 1, 'The item should have been returned' );
942 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
943 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
945 my $dbh = C4::Context->dbh;
946 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
947 SELECT borrowernumber FROM old_issues where itemnumber = ?
948 |, undef, $item->{itemnumber});
949 is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
950 Koha::Patrons->find( $patron->{borrowernumber})->delete;
953 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
955 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
956 my $patron = $builder->build(
957 { source => 'Borrower',
958 value => { privacy => 1 } # Another branchcode than the logged in librarian
961 my $item = $builder->build(
969 my $issue = $builder->build(
972 borrowernumber => $patron->{borrowernumber},
973 itemnumber => $item->{itemnumber},
978 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, undef, '2010-10-10' );
979 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
980 Koha::Patrons->find( $patron->{borrowernumber})->delete;
983 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
984 Koha::Patrons->find( $userenv_patron->{borrowernumber})->delete;
986 # Reset IndependentBranches for further tests
987 t::lib::Mocks::mock_preference('IndependentBranches', 0);
990 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
998 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
999 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1000 my $library_11 = $builder->build( { source => 'Branch' } );
1001 my $library_12 = $builder->build( { source => 'Branch' } );
1002 my $library_21 = $builder->build( { source => 'Branch' } );
1003 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1004 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1005 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1006 Koha::Library::Group->new(
1007 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1008 Koha::Library::Group->new(
1009 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1010 Koha::Library::Group->new(
1011 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1013 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1014 # 2 patrons from library_11 (group1)
1015 # patron_11_1 see patron's infos from outside its group
1016 # Setting flags => undef to not be considered as superlibrarian
1017 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1018 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1019 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1020 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1021 # patron_11_2 can only see patron's info from its group
1022 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1023 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1024 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1025 # 1 patron from library_12 (group1)
1026 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1027 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1028 # 1 patron from library_21 (group2) can only see patron's info from its group
1029 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1030 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1031 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1033 # Pfiou, we can start now!
1034 subtest 'libraries_where_can_see_patrons' => sub {
1039 set_logged_in_user( $patron_11_1 );
1040 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1041 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1043 set_logged_in_user( $patron_11_2 );
1044 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1045 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| );
1047 set_logged_in_user( $patron_21 );
1048 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1049 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| );
1051 subtest 'can_see_patron_infos' => sub {
1054 set_logged_in_user( $patron_11_1 );
1055 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1056 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1057 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1059 set_logged_in_user( $patron_11_2 );
1060 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1061 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1062 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1064 subtest 'search_limited' => sub {
1067 set_logged_in_user( $patron_11_1 );
1068 my $total_number_of_patrons = $nb_of_patrons + 6; # 2 created before + 4 for these subtests
1069 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1070 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1072 set_logged_in_user( $patron_11_2 );
1073 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1074 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' );
1076 set_logged_in_user( $patron_21 );
1077 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1078 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1080 $patron_11_1->delete;
1081 $patron_11_2->delete;
1086 subtest 'account_locked' => sub {
1088 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1089 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1090 for my $value ( undef, '', 0 ) {
1091 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1092 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1093 $patron->login_attempts(1)->store;
1094 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1097 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1098 $patron->login_attempts(2)->store;
1099 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1100 $patron->login_attempts(3)->store;
1101 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1106 subtest 'is_child | is_adult' => sub {
1108 my $category = $builder->build_object(
1110 class => 'Koha::Patron::Categories',
1111 value => { category_type => 'A' }
1114 my $patron_adult = $builder->build_object(
1116 class => 'Koha::Patrons',
1117 value => { categorycode => $category->categorycode }
1120 $category = $builder->build_object(
1122 class => 'Koha::Patron::Categories',
1123 value => { category_type => 'I' }
1126 my $patron_adult_i = $builder->build_object(
1128 class => 'Koha::Patrons',
1129 value => { categorycode => $category->categorycode }
1132 $category = $builder->build_object(
1134 class => 'Koha::Patron::Categories',
1135 value => { category_type => 'C' }
1138 my $patron_child = $builder->build_object(
1140 class => 'Koha::Patrons',
1141 value => { categorycode => $category->categorycode }
1144 $category = $builder->build_object(
1146 class => 'Koha::Patron::Categories',
1147 value => { category_type => 'O' }
1150 my $patron_other = $builder->build_object(
1152 class => 'Koha::Patrons',
1153 value => { categorycode => $category->categorycode }
1156 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1157 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1158 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1159 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1161 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1162 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1163 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1164 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1167 $patron_adult->delete;
1168 $patron_adult_i->delete;
1169 $patron_child->delete;
1170 $patron_other->delete;
1173 subtest 'get_overdues' => sub {
1176 my $library = $builder->build( { source => 'Branch' } );
1177 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1178 my $item_1 = $builder->build(
1182 homebranch => $library->{branchcode},
1183 holdingbranch => $library->{branchcode},
1184 biblionumber => $biblionumber_1
1188 my $item_2 = $builder->build(
1192 homebranch => $library->{branchcode},
1193 holdingbranch => $library->{branchcode},
1194 biblionumber => $biblionumber_1
1198 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1199 my $item_3 = $builder->build(
1203 homebranch => $library->{branchcode},
1204 holdingbranch => $library->{branchcode},
1205 biblionumber => $biblionumber_2
1209 my $patron = $builder->build(
1211 source => 'Borrower',
1212 value => { branchcode => $library->{branchcode} }
1216 my $module = new Test::MockModule('C4::Context');
1217 $module->mock( 'userenv', sub { { branch => $library->{branchcode} } } );
1219 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1220 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1221 AddIssue( $patron, $item_3->{barcode} );
1223 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1224 my $overdues = $patron->get_overdues;
1225 is( $overdues->count, 2, 'Patron should have 2 overdues');
1226 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1227 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1229 my $o = $overdues->reset->next;
1230 my $unblessed_overdue = $o->unblessed_all_relateds;
1231 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1232 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1233 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1234 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1237 $patron->checkouts->delete;
1241 subtest 'userid_is_valid' => sub {
1244 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1245 my $patron_category = $builder->build_object(
1247 class => 'Koha::Patron::Categories',
1248 value => { category_type => 'P', enrolmentfee => 0 }
1252 cardnumber => "123456789",
1253 firstname => "Tomasito",
1255 categorycode => $patron_category->categorycode,
1256 branchcode => $library->branchcode,
1259 my $expected_userid_patron_1 = 'tomasito.none';
1260 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1261 my $patron_1 = Koha::Patrons->find($borrowernumber);
1262 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1264 $patron_1->userid( 'tomasito.non' );
1265 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1266 1, 'recently created userid -> unique (borrowernumber passed)' );
1268 $patron_1->userid( 'tomasitoxxx' );
1269 is( $patron_1->has_valid_userid,
1270 1, 'non-existent userid -> unique (borrowernumber passed)' );
1271 $patron_1->discard_changes; # We compare with the original userid later
1273 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1274 is( $patron_not_in_storage->has_valid_userid,
1275 0, 'userid exists for another patron, patron is not in storage yet' );
1277 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1278 is( $patron_not_in_storage->has_valid_userid,
1279 1, 'non-existent userid, patron is not in storage yet' );
1281 # Regression tests for BZ12226
1282 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1283 is( $db_patron->has_valid_userid,
1284 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1286 # Add a new borrower with the same userid but different cardnumber
1287 $data{cardnumber} = "987654321";
1288 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1289 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1290 $patron_2->userid($patron_1->userid);
1291 is( $patron_2->has_valid_userid,
1292 0, 'The userid is already in used, it cannot be used for another patron' );
1294 my $new_userid = 'a_user_id';
1295 $data{cardnumber} = "234567890";
1296 $data{userid} = 'a_user_id';
1297 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1298 my $patron_3 = Koha::Patrons->find($borrowernumber);
1299 is( $patron_3->userid, $new_userid,
1300 'Koha::Patron->store should insert the given userid' );
1308 subtest 'generate_userid' => sub {
1311 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1312 my $patron_category = $builder->build_object(
1314 class => 'Koha::Patron::Categories',
1315 value => { category_type => 'P', enrolmentfee => 0 }
1319 cardnumber => "123456789",
1320 firstname => "Tomasito",
1322 categorycode => $patron_category->categorycode,
1323 branchcode => $library->branchcode,
1326 my $expected_userid_patron_1 = 'tomasito.none';
1327 my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1328 $new_patron->generate_userid;
1329 my $userid = $new_patron->userid;
1330 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1331 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1332 my $patron_1 = Koha::Patrons->find($borrowernumber);
1333 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1335 $new_patron->generate_userid;
1336 $userid = $new_patron->userid;
1337 is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1338 $data{cardnumber} = '987654321';
1339 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1340 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1341 isnt( $patron_2->userid, 'tomasito',
1342 "Patron with duplicate userid has new userid generated" );
1343 is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1344 "Patron with duplicate userid has new userid generated (1 is appened" );
1346 $new_patron->generate_userid;
1347 $userid = $new_patron->userid;
1348 is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1350 $patron_1 = Koha::Patrons->find($borrowernumber);
1351 $patron_1->userid(undef);
1352 $patron_1->generate_userid;
1353 $userid = $patron_1->userid;
1354 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1362 $retrieved_patron_1->delete;
1363 is( Koha::Patrons->search->count, $nb_of_patrons + 1, 'Delete should have deleted the patron' );
1365 subtest 'Log cardnumber change' => sub {
1368 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1369 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1371 my $cardnumber = $patron->cardnumber;
1372 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1375 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1376 my $log_info = from_json( $logs[0]->info );
1377 is( $log_info->{cardnumber_replaced}->{new_cardnumber}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1378 is( $log_info->{cardnumber_replaced}->{previous_cardnumber}, $cardnumber, 'Got correct old cardnumber' );
1379 is( scalar @logs, 2, 'With BorrowerLogs, Change in cardnumber should be logged, as well as general alert of patron mod.' );
1382 $schema->storage->txn_rollback;
1384 subtest 'Test Koha::Patrons::merge' => sub {
1387 my $schema = Koha::Database->new()->schema();
1389 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1391 $schema->storage->txn_begin;
1393 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1394 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1395 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1397 while (my ($r, $field) = each(%$resultsets)) {
1398 $builder->build({ source => $r, value => { $field => $keeper->id } });
1399 $builder->build({ source => $r, value => { $field => $loser_1 } });
1400 $builder->build({ source => $r, value => { $field => $loser_2 } });
1403 $schema->resultset($r)->search( { $field => $keeper->id } );
1404 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1407 $schema->resultset($r)->search( { $field => $loser_1 } );
1408 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1411 $schema->resultset($r)->search( { $field => $loser_2 } );
1412 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1415 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1417 while (my ($r, $field) = each(%$resultsets)) {
1419 $schema->resultset($r)->search( {$field => $keeper->id } );
1420 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1423 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1424 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1426 $schema->storage->txn_rollback;
1429 subtest '->store' => sub {
1431 my $schema = Koha::Database->new->schema;
1432 $schema->storage->txn_begin;
1434 my $print_error = $schema->storage->dbh->{PrintError};
1435 $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1437 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1438 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1441 { $patron_2->userid($patron_1->userid)->store; }
1442 'Koha::Exceptions::Object::DuplicateID',
1443 'AddMember raises an exception on invalid categorycode';
1445 $schema->storage->dbh->{PrintError} = $print_error;
1446 $schema->storage->txn_rollback;
1450 # TODO Move to t::lib::Mocks and reuse it!
1451 sub set_logged_in_user {
1453 C4::Context->set_userenv(
1454 $patron->borrowernumber, $patron->userid,
1455 $patron->cardnumber, 'firstname',
1456 'surname', $patron->library->branchcode,
1457 'Midway Public Library', $patron->flags,