Bug 22741: Add a test
[koha.git] / t / db_dependent / Koha / Patrons.t
blob8f2c4069fc7a95fe3684259458d21ee767ba1c44
1 #!/usr/bin/perl
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>.
20 use Modern::Perl;
22 use Test::More tests => 40;
23 use Test::Warn;
24 use Test::Exception;
25 use Test::MockModule;
26 use Time::Fake;
27 use DateTime;
28 use JSON;
29 use Data::Dumper;
31 use C4::Circulation;
32 use C4::Biblio;
33 use C4::Auth qw(checkpw_hash);
35 use Koha::ActionLogs;
36 use Koha::Holds;
37 use Koha::Old::Holds;
38 use Koha::Patrons;
39 use Koha::Patron::Categories;
40 use Koha::Database;
41 use Koha::DateUtils;
42 use Koha::Virtualshelves;
44 use t::lib::TestBuilder;
45 use t::lib::Mocks;
47 my $schema = Koha::Database->new->schema;
48 $schema->storage->txn_begin;
50 my $builder = t::lib::TestBuilder->new;
51 my $library = $builder->build({source => 'Branch' });
52 my $category = $builder->build({source => 'Category' });
53 my $nb_of_patrons = Koha::Patrons->search->count;
54 my $new_patron_1 = Koha::Patron->new(
55 { cardnumber => 'test_cn_1',
56 branchcode => $library->{branchcode},
57 categorycode => $category->{categorycode},
58 surname => 'surname for patron1',
59 firstname => 'firstname for patron1',
60 userid => 'a_nonexistent_userid_1',
61 flags => 1, # Is superlibrarian
63 )->store;
64 my $new_patron_2 = Koha::Patron->new(
65 { cardnumber => 'test_cn_2',
66 branchcode => $library->{branchcode},
67 categorycode => $category->{categorycode},
68 surname => 'surname for patron2',
69 firstname => 'firstname for patron2',
70 userid => 'a_nonexistent_userid_2',
72 )->store;
74 t::lib::Mocks::mock_userenv({ patron => $new_patron_1 });
76 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
78 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
79 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
81 subtest 'library' => sub {
82 plan tests => 2;
83 is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
84 is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
87 subtest 'guarantees' => sub {
88 plan tests => 13;
89 my $guarantees = $new_patron_1->guarantees;
90 is( ref($guarantees), 'Koha::Patrons', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
91 is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee' );
92 my @guarantees = $new_patron_1->guarantees;
93 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantees should return an array in a list context' );
94 is( scalar(@guarantees), 0, 'new_patron_1 should have 0 guarantee' );
96 my $guarantee_1 = $builder->build({ source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber }});
97 my $guarantee_2 = $builder->build({ source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber }});
99 $guarantees = $new_patron_1->guarantees;
100 is( ref($guarantees), 'Koha::Patrons', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
101 is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
102 @guarantees = $new_patron_1->guarantees;
103 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantees should return an array in a list context' );
104 is( scalar(@guarantees), 2, 'new_patron_1 should have 2 guarantees' );
105 $_->delete for @guarantees;
107 #Test return order of guarantees BZ 18635
108 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
109 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
111 my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
113 my $order_guarantee1 = $builder->build_object( { class => 'Koha::Patrons' , value => {
114 surname => 'Zebra',
115 guarantorid => $guarantor->borrowernumber
117 })->borrowernumber;
119 my $order_guarantee2 = $builder->build_object( { class => 'Koha::Patrons' , value => {
120 surname => 'Yak',
121 guarantorid => $guarantor->borrowernumber
123 })->borrowernumber;
125 my $order_guarantee3 = $builder->build_object( { class => 'Koha::Patrons' , value => {
126 surname => 'Xerus',
127 firstname => 'Walrus',
128 guarantorid => $guarantor->borrowernumber
130 })->borrowernumber;
132 my $order_guarantee4 = $builder->build_object( { class => 'Koha::Patrons' , value => {
133 surname => 'Xerus',
134 firstname => 'Vulture',
135 guarantorid => $guarantor->borrowernumber
137 })->borrowernumber;
139 my $order_guarantee5 = $builder->build_object( { class => 'Koha::Patrons' , value => {
140 surname => 'Xerus',
141 firstname => 'Unicorn',
142 guarantorid => $guarantor->borrowernumber
144 })->borrowernumber;
146 $guarantees = $guarantor->guarantees();
148 is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
149 is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
150 is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
151 is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
152 is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
155 subtest 'category' => sub {
156 plan tests => 2;
157 my $patron_category = $new_patron_1->category;
158 is( ref( $patron_category), 'Koha::Patron::Category', );
159 is( $patron_category->categorycode, $category->{categorycode}, );
162 subtest 'siblings' => sub {
163 plan tests => 7;
164 my $siblings = $new_patron_1->siblings;
165 is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
166 my $guarantee_1 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
167 my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
168 $siblings = $retrieved_guarantee_1->siblings;
169 is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
170 my @siblings = $retrieved_guarantee_1->siblings;
171 is( ref( \@siblings ), 'ARRAY', 'Koha::Patron->siblings should return an array in a list context' );
172 is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' );
173 my $guarantee_2 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
174 my $guarantee_3 = $builder->build( { source => 'Borrower', value => { guarantorid => $new_patron_1->borrowernumber } } );
175 $siblings = $retrieved_guarantee_1->siblings;
176 is( $siblings->count, 2, 'guarantee_1 should have 2 siblings' );
177 is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
178 is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
179 $_->delete for $retrieved_guarantee_1->siblings;
180 $retrieved_guarantee_1->delete;
183 subtest 'has_overdues' => sub {
184 plan tests => 3;
186 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
187 my $item_1 = $builder->build(
188 { source => 'Item',
189 value => {
190 homebranch => $library->{branchcode},
191 holdingbranch => $library->{branchcode},
192 notforloan => 0,
193 itemlost => 0,
194 withdrawn => 0,
195 biblionumber => $biblioitem_1->{biblionumber}
199 my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
200 is( $retrieved_patron->has_overdues, 0, );
202 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
203 my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
204 is( $retrieved_patron->has_overdues, 0, );
205 $issue->delete();
206 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
207 $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
208 $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
209 is( $retrieved_patron->has_overdues, 1, );
210 $issue->delete();
213 subtest 'is_expired' => sub {
214 plan tests => 4;
215 my $patron = $builder->build({ source => 'Borrower' });
216 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
217 $patron->dateexpiry( undef )->store->discard_changes;
218 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
219 $patron->dateexpiry( dt_from_string )->store->discard_changes;
220 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
221 $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
222 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
223 $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
224 is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
226 $patron->delete;
229 subtest 'is_going_to_expire' => sub {
230 plan tests => 8;
231 my $patron = $builder->build({ source => 'Borrower' });
232 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
233 $patron->dateexpiry( undef )->store->discard_changes;
234 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
236 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
237 $patron->dateexpiry( dt_from_string )->store->discard_changes;
238 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
240 $patron->dateexpiry( dt_from_string )->store->discard_changes;
241 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
243 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
244 $patron->dateexpiry( dt_from_string->add( days => 11 ) )->store->discard_changes;
245 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');
247 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
248 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
249 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');
251 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
252 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
253 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 10 days ahead and pref is 10');
254 $patron->delete;
256 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
257 $patron->dateexpiry( dt_from_string->add( days => 20 ) )->store->discard_changes;
258 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');
260 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
261 $patron->dateexpiry( dt_from_string->add( days => 10 ) )->store->discard_changes;
262 is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
264 $patron->delete;
268 subtest 'renew_account' => sub {
269 plan tests => 48;
271 for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
272 my $dt = dt_from_string( $date, 'iso' );
273 Time::Fake->offset( $dt->epoch );
274 my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
275 my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
276 my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
277 my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
278 my $a_year_later_plus_a_month = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
279 my $patron_category = $builder->build(
280 { source => 'Category',
281 value => {
282 enrolmentperiod => 12,
283 enrolmentperioddate => undef,
287 my $patron = $builder->build(
288 { source => 'Borrower',
289 value => {
290 dateexpiry => $a_month_ago,
291 categorycode => $patron_category->{categorycode},
292 date_renewed => undef, # Force builder to not populate the column for new patron
296 my $patron_2 = $builder->build(
297 { source => 'Borrower',
298 value => {
299 dateexpiry => $a_month_ago,
300 categorycode => $patron_category->{categorycode},
304 my $patron_3 = $builder->build(
305 { source => 'Borrower',
306 value => {
307 dateexpiry => $a_month_later,
308 categorycode => $patron_category->{categorycode},
312 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
313 my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
314 my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
316 is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
318 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
319 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
320 my $expiry_date = $retrieved_patron->renew_account;
321 is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
322 my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
323 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" );
324 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
325 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
327 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
328 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
329 $expiry_date = $retrieved_patron->renew_account;
330 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
331 $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
332 is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
333 $retrieved_expiry_date = $retrieved_patron->dateexpiry;
334 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
335 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
336 is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
338 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
339 $expiry_date = $retrieved_patron_2->renew_account;
340 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
341 $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
342 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
344 $expiry_date = $retrieved_patron_3->renew_account;
345 is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
346 $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
347 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" );
349 $retrieved_patron->delete;
350 $retrieved_patron_2->delete;
351 $retrieved_patron_3->delete;
353 Time::Fake->reset;
356 subtest "move_to_deleted" => sub {
357 plan tests => 5;
358 my $originally_updated_on = '2016-01-01 12:12:12';
359 my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
360 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
361 is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
362 ; # FIXME This should be Koha::Deleted::Patron
363 my $deleted_patron = $schema->resultset('Deletedborrower')
364 ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
365 ->next;
366 ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
367 ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
368 isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
369 $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
370 is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
371 $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup
374 subtest "delete" => sub {
375 plan tests => 6;
376 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
377 my $patron = $builder->build( { source => 'Borrower' } );
378 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
379 my $hold = $builder->build(
380 { source => 'Reserve',
381 value => { borrowernumber => $patron->{borrowernumber} }
384 my $list = $builder->build(
385 { source => 'Virtualshelve',
386 value => { owner => $patron->{borrowernumber} }
390 my $deleted = $retrieved_patron->delete;
391 is( $deleted, 1, 'Koha::Patron->delete should return 1 if the patron has been correctly deleted' );
393 is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
395 is (Koha::Old::Holds->search( { reserve_id => $hold->{ reserve_id } } )->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| );
397 is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have cancelled patron's holds 2| );
399 is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
401 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
402 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
405 subtest 'Koha::Patrons->delete' => sub {
406 plan tests => 4;
408 my $mod_patron = Test::MockModule->new( 'Koha::Patron' );
409 my $moved_to_deleted = 0;
410 $mod_patron->mock( 'move_to_deleted', sub { $moved_to_deleted++; } );
412 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
413 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
414 my $id1 = $patron1->borrowernumber;
415 my $set = Koha::Patrons->search({ borrowernumber => { '>=' => $id1 }});
416 is( $set->count, 2, 'Two patrons found as expected' );
417 is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
418 is( $moved_to_deleted, 2, 'Patrons moved to deletedborrowers' );
420 # Add again, test if we can raise an exception
421 $mod_patron->mock( 'delete', sub { return -1; } );
422 $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
423 $id1 = $patron1->borrowernumber;
424 $set = Koha::Patrons->search({ borrowernumber => { '>=' => $id1 }});
425 throws_ok { $set->delete } 'Koha::Exceptions::Patron::FailedDelete',
426 'Exception raised for deleting patron';
429 subtest 'add_enrolment_fee_if_needed' => sub {
430 plan tests => 4;
432 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
433 foreach( keys %{$enrolmentfees} ) {
434 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
436 my $enrolmentfee_K = $enrolmentfees->{K};
437 my $enrolmentfee_J = $enrolmentfees->{J};
438 my $enrolmentfee_YA = $enrolmentfees->{YA};
440 my %borrower_data = (
441 firstname => 'my firstname',
442 surname => 'my surname',
443 categorycode => 'K',
444 branchcode => $library->{branchcode},
447 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
448 $borrower_data{borrowernumber} = $borrowernumber;
450 my $patron = Koha::Patrons->find( $borrowernumber );
451 my $total = $patron->account->balance;
452 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
454 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
455 $borrower_data{categorycode} = 'J';
456 $patron->set(\%borrower_data)->store;
457 $total = $patron->account->balance;
458 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
460 $borrower_data{categorycode} = 'K';
461 $patron->set(\%borrower_data)->store;
462 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
464 $borrower_data{categorycode} = 'J';
465 $patron->set(\%borrower_data)->store;
466 $total = $patron->account->balance;
467 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
469 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
470 $patron->categorycode('YA')->store;
471 $total = $patron->account->balance;
472 is( int($total),
473 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
474 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
477 $patron->delete;
480 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
481 plan tests => 17;
483 my $library = $builder->build( { source => 'Branch' } );
484 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
485 my $item_1 = $builder->build(
487 source => 'Item',
488 value => {
489 homebranch => $library->{branchcode},
490 holdingbranch => $library->{branchcode},
491 biblionumber => $biblionumber_1,
492 itemlost => 0,
493 withdrawn => 0,
497 my $item_2 = $builder->build(
499 source => 'Item',
500 value => {
501 homebranch => $library->{branchcode},
502 holdingbranch => $library->{branchcode},
503 biblionumber => $biblionumber_1,
504 itemlost => 0,
505 withdrawn => 0,
509 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
510 my $item_3 = $builder->build(
512 source => 'Item',
513 value => {
514 homebranch => $library->{branchcode},
515 holdingbranch => $library->{branchcode},
516 biblionumber => $biblionumber_2,
517 itemlost => 0,
518 withdrawn => 0,
522 my $patron = $builder->build(
524 source => 'Borrower',
525 value => { branchcode => $library->{branchcode} }
529 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
530 my $checkouts = $patron->checkouts;
531 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
532 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
533 my $pending_checkouts = $patron->pending_checkouts;
534 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
535 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
536 my $old_checkouts = $patron->old_checkouts;
537 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
538 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
540 # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
541 $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
543 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
545 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
546 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
547 AddIssue( $patron, $item_3->{barcode} );
549 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
550 $checkouts = $patron->checkouts;
551 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
552 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
553 $pending_checkouts = $patron->pending_checkouts;
554 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
555 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
557 my $first_checkout = $pending_checkouts->next;
558 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
560 my $overdues = $patron->get_overdues;
561 is( $overdues->count, 2, 'Patron should have 2 overdues');
562 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
563 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
564 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
567 C4::Circulation::AddReturn( $item_1->{barcode} );
568 C4::Circulation::AddReturn( $item_2->{barcode} );
569 $old_checkouts = $patron->old_checkouts;
570 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
571 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
573 # Clean stuffs
574 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
575 $patron->delete;
578 subtest 'get_routing_lists' => sub {
579 plan tests => 5;
581 my $biblio = Koha::Biblio->new()->store();
582 my $subscription = Koha::Subscription->new({
583 biblionumber => $biblio->biblionumber,
585 )->store;
587 my $patron = $builder->build( { source => 'Borrower' } );
588 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
590 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
592 my $routinglist_count = Koha::Subscription::Routinglists->count;
593 my $routinglist = Koha::Subscription::Routinglist->new({
594 borrowernumber => $patron->borrowernumber,
595 ranking => 5,
596 subscriptionid => $subscription->subscriptionid
597 })->store;
599 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
601 my $routinglists = $patron->get_routing_lists;
602 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
603 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
605 my $subscription2 = Koha::Subscription->new({
606 biblionumber => $biblio->biblionumber,
608 )->store;
609 my $routinglist2 = Koha::Subscription::Routinglist->new({
610 borrowernumber => $patron->borrowernumber,
611 ranking => 1,
612 subscriptionid => $subscription2->subscriptionid
613 })->store;
615 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
617 $patron->delete; # Clean up for later tests
621 subtest 'get_age' => sub {
622 plan tests => 7;
624 my $patron = $builder->build( { source => 'Borrower' } );
625 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
627 my $today = dt_from_string;
629 $patron->dateofbirth( undef );
630 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
631 $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1, end_of_month => 'limit' ) );
632 is( $patron->get_age, 12, 'Patron should be 12' );
633 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 1, end_of_month => 'limit' ) );
634 is( $patron->get_age, 17, 'Patron should be 17, happy birthday tomorrow!' );
635 $patron->dateofbirth( $today->clone->add( years => -18, months => 0, days => 0, end_of_month => 'limit' ) );
636 is( $patron->get_age, 18, 'Patron should be 18' );
637 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -31, end_of_month => 'limit' ) );
638 is( $patron->get_age, 19, 'Patron should be 19' );
639 $patron->dateofbirth( $today->clone->add( years => -18, months => -12, days => -30, end_of_month => 'limit' ) );
640 is( $patron->get_age, 19, 'Patron should be 19 again' );
641 $patron->dateofbirth( $today->clone->add( years => 0, months => -1, days => -1, end_of_month => 'limit' ) );
642 is( $patron->get_age, 0, 'Patron is a newborn child' );
644 $patron->delete;
647 subtest 'is_valid_age' => sub {
648 plan tests => 10;
650 my $today = dt_from_string;
652 my $category = $builder->build({
653 source => 'Category',
654 value => {
655 categorycode => 'AGE_5_10',
656 dateofbirthrequired => 5,
657 upperagelimit => 10
660 $category = Koha::Patron::Categories->find( $category->{categorycode} );
662 my $patron = $builder->build({
663 source => 'Borrower',
664 value => {
665 categorycode => 'AGE_5_10'
668 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
671 $patron->dateofbirth( undef );
672 is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
674 $patron->dateofbirth( $today->clone->add( years => -12, months => -6, days => -1 ) );
675 is( $patron->is_valid_age, 0, 'Patron is 12, so the age is above allowed range 5-10 years');
677 $patron->dateofbirth( $today->clone->add( years => -3, months => -6, days => -1 ) );
678 is( $patron->is_valid_age, 0, 'Patron is 3, so the age is below allowed range 5-10 years');
680 $patron->dateofbirth( $today->clone->add( years => -7, months => -6, days => -1 ) );
681 is( $patron->is_valid_age, 1, 'Patron is 7, so the age perfectly suits allowed range 5-10 years');
683 $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => 0 ) );
684 is( $patron->is_valid_age, 1, 'Patron celebrates the 5th birthday today, so the age is allowed for this category');
686 $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => 1 ) );
687 is( $patron->is_valid_age, 0, 'Patron will celebrate the 5th birthday tomorrow, so the age is NOT allowed for this category');
689 $patron->dateofbirth( $today->clone->add( years => -5, months => 0, days => -1 ) );
690 is( $patron->is_valid_age, 1, 'Patron celebrated the 5th birthday yesterday, so the age is allowed for this category');
692 $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => 0 ) );
693 is( $patron->is_valid_age, 0, 'Patron celebrate the 11th birthday today, so the age is NOT allowed for this category');
695 $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => 1 ) );
696 is( $patron->is_valid_age, 1, 'Patron will celebrate the 11th birthday tomorrow, so the age is allowed for this category');
698 $patron->dateofbirth( $today->clone->add( years => -11, months => 0, days => -1 ) );
699 is( $patron->is_valid_age, 0, 'Patron celebrated the 11th birthday yesterday, so the age is NOT allowed for this category');
701 $patron->delete;
702 $category->delete;
705 subtest 'account' => sub {
706 plan tests => 1;
708 my $patron = $builder->build({source => 'Borrower'});
710 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
711 my $account = $patron->account;
712 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
714 $patron->delete;
717 subtest 'search_upcoming_membership_expires' => sub {
718 plan tests => 9;
720 my $expiry_days = 15;
721 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
722 my $nb_of_days_before = 1;
723 my $nb_of_days_after = 2;
725 my $builder = t::lib::TestBuilder->new();
727 my $library = $builder->build({ source => 'Branch' });
729 # before we add borrowers to this branch, add the expires we have now
730 # note that this pertains to the current mocked setting of the pref
731 # for this reason we add the new branchcode to most of the tests
732 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
734 my $patron_1 = $builder->build({
735 source => 'Borrower',
736 value => {
737 branchcode => $library->{branchcode},
738 dateexpiry => dt_from_string->add( days => $expiry_days )
742 my $patron_2 = $builder->build({
743 source => 'Borrower',
744 value => {
745 branchcode => $library->{branchcode},
746 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
750 my $patron_3 = $builder->build({
751 source => 'Borrower',
752 value => {
753 branchcode => $library->{branchcode},
754 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
758 # Test without extra parameters
759 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
760 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
762 # Test with branch
763 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
764 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
765 my $expired = $upcoming_mem_expires->next;
766 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
767 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
768 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
770 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
771 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
772 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
774 # Test MembershipExpiryDaysNotice == undef
775 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
776 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
777 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
779 # Test the before parameter
780 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
781 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
782 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
783 # Test after parameter also
784 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
785 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
786 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
789 subtest 'holds and old_holds' => sub {
790 plan tests => 6;
792 my $library = $builder->build( { source => 'Branch' } );
793 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
794 my $item_1 = $builder->build(
796 source => 'Item',
797 value => {
798 homebranch => $library->{branchcode},
799 holdingbranch => $library->{branchcode},
800 biblionumber => $biblionumber_1
804 my $item_2 = $builder->build(
806 source => 'Item',
807 value => {
808 homebranch => $library->{branchcode},
809 holdingbranch => $library->{branchcode},
810 biblionumber => $biblionumber_1
814 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
815 my $item_3 = $builder->build(
817 source => 'Item',
818 value => {
819 homebranch => $library->{branchcode},
820 holdingbranch => $library->{branchcode},
821 biblionumber => $biblionumber_2
825 my $patron = $builder->build(
827 source => 'Borrower',
828 value => { branchcode => $library->{branchcode} }
832 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
833 my $holds = $patron->holds;
834 is( ref($holds), 'Koha::Holds',
835 'Koha::Patron->holds should return a Koha::Holds objects' );
836 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
838 C4::Reserves::AddReserve( $library->{branchcode},
839 $patron->borrowernumber, $biblionumber_1 );
840 # In the future
841 C4::Reserves::AddReserve( $library->{branchcode},
842 $patron->borrowernumber, $biblionumber_2, undef, undef, dt_from_string->add( days => 2 ) );
844 $holds = $patron->holds;
845 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
847 my $old_holds = $patron->old_holds;
848 is( ref($old_holds), 'Koha::Old::Holds',
849 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
850 is( $old_holds->count, 0, 'There should not be any old holds yet');
852 my $hold = $holds->next;
853 $hold->cancel;
855 $old_holds = $patron->old_holds;
856 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
858 $old_holds->delete;
859 $holds->delete;
860 $patron->delete;
863 subtest 'notice_email_address' => sub {
864 plan tests => 2;
866 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
868 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
869 is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
871 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
872 is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
874 $patron->delete;
877 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
878 plan tests => 4;
880 # TODO create a subroutine in t::lib::Mocks
881 my $branch = $builder->build({ source => 'Branch' });
882 my $userenv_patron = $builder->build_object({
883 class => 'Koha::Patrons',
884 value => { branchcode => $branch->{branchcode}, flags => 0 },
886 t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
888 my $anonymous = $builder->build( { source => 'Borrower', }, );
890 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
892 subtest 'patron privacy is 1 (default)' => sub {
893 plan tests => 9;
895 t::lib::Mocks::mock_preference('IndependentBranches', 0);
896 my $patron = $builder->build(
897 { source => 'Borrower',
898 value => { privacy => 1, }
901 my $item_1 = $builder->build(
902 { source => 'Item',
903 value => {
904 itemlost => 0,
905 withdrawn => 0,
909 my $issue_1 = $builder->build(
910 { source => 'Issue',
911 value => {
912 borrowernumber => $patron->{borrowernumber},
913 itemnumber => $item_1->{itemnumber},
917 my $item_2 = $builder->build(
918 { source => 'Item',
919 value => {
920 itemlost => 0,
921 withdrawn => 0,
925 my $issue_2 = $builder->build(
926 { source => 'Issue',
927 value => {
928 borrowernumber => $patron->{borrowernumber},
929 itemnumber => $item_2->{itemnumber},
934 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, dt_from_string('2010-10-10') );
935 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, dt_from_string('2011-11-11') );
936 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
938 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
939 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
941 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
942 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
944 $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
945 is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
947 my $dbh = C4::Context->dbh;
948 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
949 $sth->execute($item_1->{itemnumber});
950 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
951 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
952 $sth->execute($item_2->{itemnumber});
953 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
954 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
956 $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
957 $sth->execute($item_2->{itemnumber});
958 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
959 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
961 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
962 $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
963 $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
964 $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
965 $sth->execute($item_1->{itemnumber});
966 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
967 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
968 $sth->execute($item_2->{itemnumber});
969 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
970 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
972 Koha::Patrons->find( $patron->{borrowernumber})->delete;
975 subtest 'patron privacy is 0 (forever)' => sub {
976 plan tests => 2;
978 t::lib::Mocks::mock_preference('IndependentBranches', 0);
979 my $patron = $builder->build(
980 { source => 'Borrower',
981 value => { privacy => 0, }
984 my $item = $builder->build(
985 { source => 'Item',
986 value => {
987 itemlost => 0,
988 withdrawn => 0,
992 my $issue = $builder->build(
993 { source => 'Issue',
994 value => {
995 borrowernumber => $patron->{borrowernumber},
996 itemnumber => $item->{itemnumber},
1001 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1002 is( $returned, 1, 'The item should have been returned' );
1004 my $dbh = C4::Context->dbh;
1005 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1006 SELECT borrowernumber FROM old_issues where itemnumber = ?
1007 |, undef, $item->{itemnumber});
1008 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1009 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1012 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1014 subtest 'AnonymousPatron is not defined' => sub {
1015 plan tests => 3;
1017 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1018 my $patron = $builder->build(
1019 { source => 'Borrower',
1020 value => { privacy => 1, }
1023 my $item = $builder->build(
1024 { source => 'Item',
1025 value => {
1026 itemlost => 0,
1027 withdrawn => 0,
1031 my $issue = $builder->build(
1032 { source => 'Issue',
1033 value => {
1034 borrowernumber => $patron->{borrowernumber},
1035 itemnumber => $item->{itemnumber},
1040 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1041 is( $returned, 1, 'The item should have been returned' );
1042 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
1043 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1045 my $dbh = C4::Context->dbh;
1046 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1047 SELECT borrowernumber FROM old_issues where itemnumber = ?
1048 |, undef, $item->{itemnumber});
1049 is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
1050 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1053 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1054 plan tests => 1;
1055 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1056 my $patron = $builder->build(
1057 { source => 'Borrower',
1058 value => { privacy => 1 } # Another branchcode than the logged in librarian
1061 my $item = $builder->build(
1062 { source => 'Item',
1063 value => {
1064 itemlost => 0,
1065 withdrawn => 0,
1069 my $issue = $builder->build(
1070 { source => 'Issue',
1071 value => {
1072 borrowernumber => $patron->{borrowernumber},
1073 itemnumber => $item->{itemnumber},
1078 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1079 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1080 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1083 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1084 $userenv_patron->delete;
1086 # Reset IndependentBranches for further tests
1087 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1090 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1091 plan tests => 3;
1093 # group1
1094 # + library_11
1095 # + library_12
1096 # group2
1097 # + library21
1098 $nb_of_patrons = Koha::Patrons->search->count;
1099 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1100 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1101 my $library_11 = $builder->build( { source => 'Branch' } );
1102 my $library_12 = $builder->build( { source => 'Branch' } );
1103 my $library_21 = $builder->build( { source => 'Branch' } );
1104 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1105 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1106 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1107 Koha::Library::Group->new(
1108 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1109 Koha::Library::Group->new(
1110 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1111 Koha::Library::Group->new(
1112 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1114 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1115 # 2 patrons from library_11 (group1)
1116 # patron_11_1 see patron's infos from outside its group
1117 # Setting flags => undef to not be considered as superlibrarian
1118 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1119 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1120 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1121 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1122 # patron_11_2 can only see patron's info from its group
1123 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1124 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1125 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1126 # 1 patron from library_12 (group1)
1127 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1128 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1129 # 1 patron from library_21 (group2) can only see patron's info from its group
1130 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1131 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1132 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1134 # Pfiou, we can start now!
1135 subtest 'libraries_where_can_see_patrons' => sub {
1136 plan tests => 3;
1138 my @branchcodes;
1140 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1141 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1142 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1144 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1145 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1146 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| );
1148 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1149 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1150 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| );
1152 subtest 'can_see_patron_infos' => sub {
1153 plan tests => 6;
1155 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1156 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1157 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1158 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1160 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1161 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1162 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1163 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1165 subtest 'search_limited' => sub {
1166 plan tests => 6;
1168 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1169 my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1170 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1171 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1173 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1174 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1175 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' );
1177 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1178 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1179 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1181 $patron_11_1->delete;
1182 $patron_11_2->delete;
1183 $patron_12->delete;
1184 $patron_21->delete;
1187 subtest 'account_locked' => sub {
1188 plan tests => 13;
1189 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1190 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1191 for my $value ( undef, '', 0 ) {
1192 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1193 $patron->login_attempts(0)->store;
1194 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1195 $patron->login_attempts(1)->store;
1196 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1197 $patron->login_attempts(-1)->store;
1198 is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1201 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1202 $patron->login_attempts(2)->store;
1203 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1204 $patron->login_attempts(3)->store;
1205 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1206 $patron->login_attempts(4)->store;
1207 is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1208 $patron->login_attempts(-1)->store;
1209 is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1211 $patron->delete;
1214 subtest 'is_child | is_adult' => sub {
1215 plan tests => 8;
1216 my $category = $builder->build_object(
1218 class => 'Koha::Patron::Categories',
1219 value => { category_type => 'A' }
1222 my $patron_adult = $builder->build_object(
1224 class => 'Koha::Patrons',
1225 value => { categorycode => $category->categorycode }
1228 $category = $builder->build_object(
1230 class => 'Koha::Patron::Categories',
1231 value => { category_type => 'I' }
1234 my $patron_adult_i = $builder->build_object(
1236 class => 'Koha::Patrons',
1237 value => { categorycode => $category->categorycode }
1240 $category = $builder->build_object(
1242 class => 'Koha::Patron::Categories',
1243 value => { category_type => 'C' }
1246 my $patron_child = $builder->build_object(
1248 class => 'Koha::Patrons',
1249 value => { categorycode => $category->categorycode }
1252 $category = $builder->build_object(
1254 class => 'Koha::Patron::Categories',
1255 value => { category_type => 'O' }
1258 my $patron_other = $builder->build_object(
1260 class => 'Koha::Patrons',
1261 value => { categorycode => $category->categorycode }
1264 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1265 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1266 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1267 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1269 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1270 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1271 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1272 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1274 # Clean up
1275 $patron_adult->delete;
1276 $patron_adult_i->delete;
1277 $patron_child->delete;
1278 $patron_other->delete;
1281 subtest 'get_overdues' => sub {
1282 plan tests => 7;
1284 my $library = $builder->build( { source => 'Branch' } );
1285 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1286 my $item_1 = $builder->build(
1288 source => 'Item',
1289 value => {
1290 homebranch => $library->{branchcode},
1291 holdingbranch => $library->{branchcode},
1292 biblionumber => $biblionumber_1
1296 my $item_2 = $builder->build(
1298 source => 'Item',
1299 value => {
1300 homebranch => $library->{branchcode},
1301 holdingbranch => $library->{branchcode},
1302 biblionumber => $biblionumber_1
1306 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1307 my $item_3 = $builder->build(
1309 source => 'Item',
1310 value => {
1311 homebranch => $library->{branchcode},
1312 holdingbranch => $library->{branchcode},
1313 biblionumber => $biblionumber_2
1317 my $patron = $builder->build(
1319 source => 'Borrower',
1320 value => { branchcode => $library->{branchcode} }
1324 t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1326 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1327 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1328 AddIssue( $patron, $item_3->{barcode} );
1330 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1331 my $overdues = $patron->get_overdues;
1332 is( $overdues->count, 2, 'Patron should have 2 overdues');
1333 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1334 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1336 my $o = $overdues->reset->next;
1337 my $unblessed_overdue = $o->unblessed_all_relateds;
1338 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1339 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1340 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1341 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1343 # Clean stuffs
1344 $patron->checkouts->delete;
1345 $patron->delete;
1348 subtest 'userid_is_valid' => sub {
1349 plan tests => 9;
1351 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1352 my $patron_category = $builder->build_object(
1354 class => 'Koha::Patron::Categories',
1355 value => { category_type => 'P', enrolmentfee => 0 }
1358 my %data = (
1359 cardnumber => "123456789",
1360 firstname => "Tomasito",
1361 surname => "None",
1362 categorycode => $patron_category->categorycode,
1363 branchcode => $library->branchcode,
1366 my $expected_userid_patron_1 = 'tomasito.none';
1367 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1368 my $patron_1 = Koha::Patrons->find($borrowernumber);
1369 is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1370 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1372 $patron_1->userid( 'tomasito.non' );
1373 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1374 1, 'recently created userid -> unique (borrowernumber passed)' );
1376 $patron_1->userid( 'tomasitoxxx' );
1377 is( $patron_1->has_valid_userid,
1378 1, 'non-existent userid -> unique (borrowernumber passed)' );
1379 $patron_1->discard_changes; # We compare with the original userid later
1381 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1382 is( $patron_not_in_storage->has_valid_userid,
1383 0, 'userid exists for another patron, patron is not in storage yet' );
1385 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1386 is( $patron_not_in_storage->has_valid_userid,
1387 1, 'non-existent userid, patron is not in storage yet' );
1389 # Regression tests for BZ12226
1390 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1391 is( $db_patron->has_valid_userid,
1392 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1394 # Add a new borrower with the same userid but different cardnumber
1395 $data{cardnumber} = "987654321";
1396 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1397 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1398 $patron_2->userid($patron_1->userid);
1399 is( $patron_2->has_valid_userid,
1400 0, 'The userid is already in used, it cannot be used for another patron' );
1402 my $new_userid = 'a_user_id';
1403 $data{cardnumber} = "234567890";
1404 $data{userid} = 'a_user_id';
1405 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1406 my $patron_3 = Koha::Patrons->find($borrowernumber);
1407 is( $patron_3->userid, $new_userid,
1408 'Koha::Patron->store should insert the given userid' );
1410 # Cleanup
1411 $patron_1->delete;
1412 $patron_2->delete;
1413 $patron_3->delete;
1416 subtest 'generate_userid' => sub {
1417 plan tests => 7;
1419 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1420 my $patron_category = $builder->build_object(
1422 class => 'Koha::Patron::Categories',
1423 value => { category_type => 'P', enrolmentfee => 0 }
1426 my %data = (
1427 cardnumber => "123456789",
1428 firstname => "Tomasito",
1429 surname => "None",
1430 categorycode => $patron_category->categorycode,
1431 branchcode => $library->branchcode,
1434 my $expected_userid_patron_1 = 'tomasito.none';
1435 my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1436 $new_patron->generate_userid;
1437 my $userid = $new_patron->userid;
1438 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1439 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1440 my $patron_1 = Koha::Patrons->find($borrowernumber);
1441 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1443 $new_patron->generate_userid;
1444 $userid = $new_patron->userid;
1445 is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1446 $data{cardnumber} = '987654321';
1447 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1448 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1449 isnt( $patron_2->userid, 'tomasito',
1450 "Patron with duplicate userid has new userid generated" );
1451 is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1452 "Patron with duplicate userid has new userid generated (1 is appened" );
1454 $new_patron->generate_userid;
1455 $userid = $new_patron->userid;
1456 is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1458 $patron_1 = Koha::Patrons->find($borrowernumber);
1459 $patron_1->userid(undef);
1460 $patron_1->generate_userid;
1461 $userid = $patron_1->userid;
1462 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1464 # Cleanup
1465 $patron_1->delete;
1466 $patron_2->delete;
1469 subtest 'attributes' => sub {
1470 plan tests => 2;
1472 my $library1 = Koha::Library->new({
1473 branchcode => 'LIBPATRON',
1474 branchname => 'Library of testing patron',
1475 })->store;
1477 my $library2 = Koha::Library->new({
1478 branchcode => 'LIBATTR',
1479 branchname => 'Library for testing attribute',
1480 })->store;
1482 my $category = Koha::Patron::Category->new({
1483 categorycode => 'CAT1',
1484 description => 'Category 1',
1485 })->store;
1487 my $patron = Koha::Patron->new({
1488 firstname => 'Patron',
1489 surname => 'with attributes',
1490 branchcode => 'LIBPATRON',
1491 categorycode => 'CAT1',
1492 })->store;
1494 my $attribute_type1 = Koha::Patron::Attribute::Type->new({
1495 code => 'CODE_A',
1496 description => 'Code A desciption',
1497 })->store;
1499 my $attribute_type2 = Koha::Patron::Attribute::Type->new({
1500 code => 'CODE_B',
1501 description => 'Code A desciption',
1502 })->store;
1504 $attribute_type2->library_limits ( [ $library2->branchcode ] );
1506 Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type1->code, attribute => 'value 1' } )->store();
1507 Koha::Patron::Attribute->new({ borrowernumber => $patron->borrowernumber, code => $attribute_type2->code, attribute => 'value 2' } )->store();
1509 is( $patron->attributes->count, 1, 'There should be one attribute');
1511 $attribute_type2->library_limits ( [ $library1->branchcode ] );
1513 is( $patron->attributes->count, 2, 'There should be 2 attributes');
1515 $patron->delete;
1518 $nb_of_patrons = Koha::Patrons->search->count;
1519 $retrieved_patron_1->delete;
1520 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1522 subtest 'BorrowersLog tests' => sub {
1523 plan tests => 4;
1525 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1526 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1528 my $cardnumber = $patron->cardnumber;
1529 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1530 $patron->store;
1532 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1533 my $log_info = from_json( $logs[0]->info );
1534 is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1535 is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1536 is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1538 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1539 $patron->track_login();
1540 @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1541 is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1544 $schema->storage->txn_rollback;
1546 subtest 'Test Koha::Patrons::merge' => sub {
1547 plan tests => 110;
1549 my $schema = Koha::Database->new()->schema();
1551 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1553 $schema->storage->txn_begin;
1555 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1556 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1557 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1559 while (my ($r, $field) = each(%$resultsets)) {
1560 $builder->build({ source => $r, value => { $field => $keeper->id } });
1561 $builder->build({ source => $r, value => { $field => $loser_1 } });
1562 $builder->build({ source => $r, value => { $field => $loser_2 } });
1564 my $keeper_rs =
1565 $schema->resultset($r)->search( { $field => $keeper->id } );
1566 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1568 my $loser_1_rs =
1569 $schema->resultset($r)->search( { $field => $loser_1 } );
1570 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1572 my $loser_2_rs =
1573 $schema->resultset($r)->search( { $field => $loser_2 } );
1574 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1577 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1579 while (my ($r, $field) = each(%$resultsets)) {
1580 my $keeper_rs =
1581 $schema->resultset($r)->search( {$field => $keeper->id } );
1582 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1585 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1586 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1588 $schema->storage->txn_rollback;
1591 subtest '->store' => sub {
1592 plan tests => 6;
1593 my $schema = Koha::Database->new->schema;
1594 $schema->storage->txn_begin;
1596 my $print_error = $schema->storage->dbh->{PrintError};
1597 $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1599 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1600 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1602 throws_ok
1603 { $patron_2->userid($patron_1->userid)->store; }
1604 'Koha::Exceptions::Object::DuplicateID',
1605 'Koha::Patron->store raises an exception on duplicate ID';
1607 # Test password
1608 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1609 my $password = 'password';
1610 $patron_1->set_password({ password => $password });
1611 like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1612 my $digest = $patron_1->password;
1613 $patron_1->surname('xxx')->store;
1614 is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1616 # Test uppercasesurname
1617 t::lib::Mocks::mock_preference( 'uppercasesurname', 1 );
1618 my $surname = lc $patron_1->surname;
1619 $patron_1->surname($surname)->store;
1620 isnt( $patron_1->surname, $surname,
1621 'Surname converts to uppercase on store.');
1622 t::lib::Mocks::mock_preference( 'uppercasesurname', 0 );
1623 $patron_1->surname($surname)->store;
1624 is( $patron_1->surname, $surname,
1625 'Surname remains unchanged on store.');
1627 $schema->storage->dbh->{PrintError} = $print_error;
1628 $schema->storage->txn_rollback;
1630 subtest 'skip updated_on for BorrowersLog' => sub {
1631 plan tests => 1;
1632 $schema->storage->txn_begin;
1633 t::lib::Mocks::mock_preference('BorrowersLog', 1);
1634 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1635 $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1636 my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1637 is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1638 $schema->storage->txn_rollback;
1642 subtest '->set_password' => sub {
1644 plan tests => 14;
1646 $schema->storage->txn_begin;
1648 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1650 # Disable logging password changes for this tests
1651 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1653 # Password-length tests
1654 t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1655 throws_ok { $patron->set_password({ password => 'ab' }); }
1656 'Koha::Exceptions::Password::TooShort',
1657 'minPasswordLength is undef, fall back to 3, fail test';
1658 is( "$@",
1659 'Password length (2) is shorter than required (3)',
1660 'Exception parameters passed correctly'
1663 t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1664 throws_ok { $patron->set_password({ password => 'ab' }); }
1665 'Koha::Exceptions::Password::TooShort',
1666 'minPasswordLength is 2, fall back to 3, fail test';
1668 t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1669 throws_ok { $patron->set_password({ password => 'abcb' }); }
1670 'Koha::Exceptions::Password::TooShort',
1671 'minPasswordLength is 5, fail test';
1673 # Trailing spaces tests
1674 throws_ok { $patron->set_password({ password => 'abcD12d ' }); }
1675 'Koha::Exceptions::Password::WhitespaceCharacters',
1676 'Password contains trailing spaces, exception is thrown';
1678 # Require strong password tests
1679 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1680 throws_ok { $patron->set_password({ password => 'abcd a' }); }
1681 'Koha::Exceptions::Password::TooWeak',
1682 'Password is too weak, exception is thrown';
1684 # Refresh patron from DB, just to make sure
1685 $patron->discard_changes;
1686 is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1688 $patron->set_password({ password => 'abcD12 34' });
1689 $patron->discard_changes;
1691 is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1693 lives_ok { $patron->set_password({ password => 'abcd a', skip_validation => 1 }) }
1694 'Password is weak, but skip_validation was passed, so no exception thrown';
1696 # Completeness
1697 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1698 $patron->login_attempts(3)->store;
1699 my $old_digest = $patron->password;
1700 $patron->set_password({ password => 'abcd a' });
1701 $patron->discard_changes;
1703 isnt( $patron->password, $old_digest, 'Password has been updated' );
1704 ok( checkpw_hash('abcd a', $patron->password), 'Password hash is correct' );
1705 is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1707 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1708 is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1710 # Enable logging password changes
1711 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1712 $patron->set_password({ password => 'abcd b' });
1714 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1715 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1717 $schema->storage->txn_rollback;
1720 $schema->storage->txn_begin;
1721 subtest 'search_unsubscribed' => sub {
1722 plan tests => 4;
1724 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1725 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
1726 is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
1728 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1729 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1731 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
1732 Koha::Patron::Consents->delete; # for correct counts
1733 Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string })->store;
1734 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
1736 # Add another refusal but shift the period
1737 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
1738 Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string->subtract(days=>2) })->store;
1739 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
1741 # Try another (special) attempts setting
1742 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
1743 # Lockout is now disabled
1744 # Patron2 still matches: refused earlier, not locked
1745 is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
1748 subtest 'search_anonymize_candidates' => sub {
1749 plan tests => 5;
1750 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1751 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1752 $patron1->anonymized(0);
1753 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1754 $patron2->anonymized(0);
1755 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1757 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
1758 is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
1760 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
1761 my $cnt = Koha::Patrons->search_anonymize_candidates->count;
1762 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1763 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1764 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
1766 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
1767 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1768 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1769 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1770 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1771 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1772 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
1774 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
1775 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1776 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1777 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1778 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1779 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1780 is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
1782 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1783 $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1784 $patron1->login_attempts(0)->store;
1785 $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1786 $patron2->login_attempts(0)->store;
1787 $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
1788 $patron1->login_attempts(3)->store;
1789 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1790 $cnt+1, 'Locked flag' );
1793 subtest 'search_anonymized' => sub {
1794 plan tests => 3;
1795 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1797 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
1798 is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
1800 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
1801 $patron1->dateexpiry( dt_from_string );
1802 $patron1->anonymized(0)->store;
1803 my $cnt = Koha::Patrons->search_anonymized->count;
1804 $patron1->anonymized(1)->store;
1805 is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
1806 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1807 is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
1810 subtest 'lock' => sub {
1811 plan tests => 8;
1813 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1814 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1815 my $hold = $builder->build_object({
1816 class => 'Koha::Holds',
1817 value => { borrowernumber => $patron1->borrowernumber },
1820 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1821 my $expiry = dt_from_string->add(days => 1);
1822 $patron1->dateexpiry( $expiry );
1823 $patron1->lock;
1824 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1825 is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
1826 is( $patron1->holds->count, 1, 'No holds removed' );
1828 $patron1->lock({ expire => 1, remove => 1});
1829 isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
1830 is( $patron1->holds->count, 0, 'Holds removed' );
1832 # Disable lockout feature
1833 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1834 $patron1->login_attempts(0);
1835 $patron1->dateexpiry( $expiry );
1836 $patron1->store;
1837 $patron1->lock;
1838 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1840 # Trivial wrapper test (Koha::Patrons->lock)
1841 $patron1->login_attempts(0)->store;
1842 Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
1843 $patron1->discard_changes; # refresh
1844 $patron2->discard_changes;
1845 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
1846 is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
1849 subtest 'anonymize' => sub {
1850 plan tests => 10;
1852 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1853 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1855 # First try patron with issues
1856 my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
1857 warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
1858 $issue->delete;
1860 t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
1861 my $surname = $patron1->surname; # expect change, no clear
1862 my $branchcode = $patron1->branchcode; # expect skip
1863 $patron1->anonymize;
1864 is($patron1->anonymized, 1, 'Check flag' );
1866 is( $patron1->dateofbirth, undef, 'Birth date cleared' );
1867 is( $patron1->firstname, undef, 'First name cleared' );
1868 isnt( $patron1->surname, $surname, 'Surname changed' );
1869 ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
1870 is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
1871 is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
1873 # Test wrapper in Koha::Patrons
1874 $patron1->surname($surname)->store; # restore
1875 my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
1876 $patron1->discard_changes; # refresh
1877 isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
1878 $patron2->discard_changes; # refresh
1879 is( $patron2->firstname, undef, 'First name patron2 cleared' );
1881 $schema->storage->txn_rollback;