Bug 20443: Fix merge_with behavior
[koha.git] / t / db_dependent / Koha / Patrons.t
blob0c5bb31246a9acec82942e691e7143dd5d5f68ab
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;
30 use utf8;
32 use C4::Circulation;
33 use C4::Biblio;
34 use C4::Auth qw(checkpw_hash);
36 use Koha::ActionLogs;
37 use Koha::Holds;
38 use Koha::Old::Holds;
39 use Koha::Patrons;
40 use Koha::Old::Patrons;
41 use Koha::Patron::Attribute::Types;
42 use Koha::Patron::Categories;
43 use Koha::Patron::Relationship;
44 use Koha::Database;
45 use Koha::DateUtils;
46 use Koha::Virtualshelves;
48 use t::lib::TestBuilder;
49 use t::lib::Mocks;
51 my $schema = Koha::Database->new->schema;
52 $schema->storage->txn_begin;
54 my $builder = t::lib::TestBuilder->new;
55 my $library = $builder->build({source => 'Branch' });
56 my $category = $builder->build({source => 'Category' });
57 my $nb_of_patrons = Koha::Patrons->search->count;
58 my $new_patron_1 = Koha::Patron->new(
59 { cardnumber => 'test_cn_1',
60 branchcode => $library->{branchcode},
61 categorycode => $category->{categorycode},
62 surname => 'surname for patron1',
63 firstname => 'firstname for patron1',
64 userid => 'a_nonexistent_userid_1',
65 flags => 1, # Is superlibrarian
67 )->store;
68 my $new_patron_2 = Koha::Patron->new(
69 { cardnumber => 'test_cn_2',
70 branchcode => $library->{branchcode},
71 categorycode => $category->{categorycode},
72 surname => 'surname for patron2',
73 firstname => 'firstname for patron2',
74 userid => 'a_nonexistent_userid_2',
76 )->store;
78 t::lib::Mocks::mock_userenv({ patron => $new_patron_1 });
80 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
82 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
83 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
85 subtest 'library' => sub {
86 plan tests => 2;
87 is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
88 is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
91 subtest 'guarantees' => sub {
92 plan tests => 13;
94 t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test|test2' );
96 my $guarantees = $new_patron_1->guarantee_relationships;
97 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
98 is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee relationships' );
99 my @guarantees = $new_patron_1->guarantee_relationships;
100 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantee_relationships should return an array in a list context' );
101 is( scalar(@guarantees), 0, 'new_patron_1 should have 0 guarantee' );
103 my $guarantee_1 = $builder->build({ source => 'Borrower' });
104 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
105 my $guarantee_2 = $builder->build({ source => 'Borrower' });
106 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
108 $guarantees = $new_patron_1->guarantee_relationships;
109 is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantee_relationships should return a Koha::Patrons result set in a scalar context' );
110 is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
111 @guarantees = $new_patron_1->guarantee_relationships;
112 is( ref(\@guarantees), 'ARRAY', 'Koha::Patron->guarantee_relationships should return an array in a list context' );
113 is( scalar(@guarantees), 2, 'new_patron_1 should have 2 guarantees' );
114 $_->delete for @guarantees;
116 #Test return order of guarantees BZ 18635
117 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
118 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
120 my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
122 my $order_guarantee1 = $builder->build_object(
124 class => 'Koha::Patrons',
125 value => {
126 surname => 'Zebra',
129 )->borrowernumber;
130 $builder->build_object(
132 class => 'Koha::Patron::Relationships',
133 value => {
134 guarantor_id => $guarantor->id,
135 guarantee_id => $order_guarantee1,
136 relationship => 'test',
141 my $order_guarantee2 = $builder->build_object(
143 class => 'Koha::Patrons',
144 value => {
145 surname => 'Yak',
148 )->borrowernumber;
149 $builder->build_object(
151 class => 'Koha::Patron::Relationships',
152 value => {
153 guarantor_id => $guarantor->id,
154 guarantee_id => $order_guarantee2,
155 relationship => 'test',
160 my $order_guarantee3 = $builder->build_object(
162 class => 'Koha::Patrons',
163 value => {
164 surname => 'Xerus',
165 firstname => 'Walrus',
168 )->borrowernumber;
169 $builder->build_object(
171 class => 'Koha::Patron::Relationships',
172 value => {
173 guarantor_id => $guarantor->id,
174 guarantee_id => $order_guarantee3,
175 relationship => 'test',
180 my $order_guarantee4 = $builder->build_object(
182 class => 'Koha::Patrons',
183 value => {
184 surname => 'Xerus',
185 firstname => 'Vulture',
186 guarantorid => $guarantor->borrowernumber
189 )->borrowernumber;
190 $builder->build_object(
192 class => 'Koha::Patron::Relationships',
193 value => {
194 guarantor_id => $guarantor->id,
195 guarantee_id => $order_guarantee4,
196 relationship => 'test',
201 my $order_guarantee5 = $builder->build_object(
203 class => 'Koha::Patrons',
204 value => {
205 surname => 'Xerus',
206 firstname => 'Unicorn',
207 guarantorid => $guarantor->borrowernumber
210 )->borrowernumber;
211 my $r = $builder->build_object(
213 class => 'Koha::Patron::Relationships',
214 value => {
215 guarantor_id => $guarantor->id,
216 guarantee_id => $order_guarantee5,
217 relationship => 'test',
222 $guarantees = $guarantor->guarantee_relationships->guarantees;
224 is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
225 is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
226 is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
227 is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
228 is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
231 subtest 'category' => sub {
232 plan tests => 2;
233 my $patron_category = $new_patron_1->category;
234 is( ref( $patron_category), 'Koha::Patron::Category', );
235 is( $patron_category->categorycode, $category->{categorycode}, );
238 subtest 'siblings' => sub {
239 plan tests => 7;
240 my $siblings = $new_patron_1->siblings;
241 is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
242 my $guarantee_1 = $builder->build( { source => 'Borrower' } );
243 my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
244 my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
245 $siblings = $retrieved_guarantee_1->siblings;
246 is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
247 my @siblings = $retrieved_guarantee_1->siblings;
248 is( ref( \@siblings ), 'ARRAY', 'Koha::Patron->siblings should return an array in a list context' );
249 is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' );
250 my $guarantee_2 = $builder->build( { source => 'Borrower' } );
251 my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
252 my $guarantee_3 = $builder->build( { source => 'Borrower' } );
253 my $relationship_3 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_3->{borrowernumber}, relationship => 'test' } )->store();
254 $siblings = $retrieved_guarantee_1->siblings;
255 is( $siblings->count, 2, 'guarantee_1 should have 2 siblings' );
256 is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
257 is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
258 $_->delete for $retrieved_guarantee_1->siblings;
259 $retrieved_guarantee_1->delete;
262 subtest 'has_overdues' => sub {
263 plan tests => 3;
265 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
266 my $item_1 = $builder->build(
267 { source => 'Item',
268 value => {
269 homebranch => $library->{branchcode},
270 holdingbranch => $library->{branchcode},
271 notforloan => 0,
272 itemlost => 0,
273 withdrawn => 0,
274 biblionumber => $biblioitem_1->{biblionumber}
278 my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
279 is( $retrieved_patron->has_overdues, 0, );
281 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
282 my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
283 is( $retrieved_patron->has_overdues, 0, );
284 $issue->delete();
285 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
286 $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->{itemnumber}, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
287 $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
288 is( $retrieved_patron->has_overdues, 1, );
289 $issue->delete();
292 subtest 'is_expired' => sub {
293 plan tests => 4;
294 my $patron = $builder->build({ source => 'Borrower' });
295 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
296 $patron->dateexpiry( undef )->store->discard_changes;
297 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
298 $patron->dateexpiry( dt_from_string )->store->discard_changes;
299 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
300 $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
301 is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
302 $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
303 is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
305 $patron->delete;
308 subtest 'is_going_to_expire' => sub {
309 plan tests => 9;
311 my $today = dt_from_string(undef, undef, 'floating');
312 my $patron = $builder->build({ source => 'Borrower' });
313 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
314 $patron->dateexpiry( undef )->store->discard_changes;
315 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
317 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
318 $patron->dateexpiry( $today )->store->discard_changes;
319 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
321 $patron->dateexpiry( $today )->store->discard_changes;
322 is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
324 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
325 $patron->dateexpiry( $today->clone->add( days => 11 ) )->store->discard_changes;
326 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');
328 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
329 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
330 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');
332 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
333 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
334 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');
335 $patron->delete;
337 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
338 $patron->dateexpiry( $today->clone->add( days => 20 ) )->store->discard_changes;
339 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');
341 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
342 $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
343 is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
345 { # Testing invalid is going to expiry date
346 t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 30);
347 # mock_config does not work here, because of tz vs timezone subroutines
348 my $context = new Test::MockModule('C4::Context');
349 $context->mock( 'tz', sub {
350 'America/Sao_Paulo';
352 $patron->dateexpiry(DateTime->new( year => 2019, month => 12, day => 3 ))->store;
353 eval { $patron->is_going_to_expire };
354 is( $@, '', 'On invalid "is going to expire" date, the method should not crash with "Invalid local time for date in time zone"');
355 $context->unmock('tz');
358 $patron->delete;
362 subtest 'renew_account' => sub {
363 plan tests => 48;
365 for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
366 my $dt = dt_from_string( $date, 'iso' );
367 Time::Fake->offset( $dt->epoch );
368 my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
369 my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
370 my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
371 my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
372 my $a_year_later_plus_a_month = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
373 my $patron_category = $builder->build(
374 { source => 'Category',
375 value => {
376 enrolmentperiod => 12,
377 enrolmentperioddate => undef,
381 my $patron = $builder->build(
382 { source => 'Borrower',
383 value => {
384 dateexpiry => $a_month_ago,
385 categorycode => $patron_category->{categorycode},
386 date_renewed => undef, # Force builder to not populate the column for new patron
390 my $patron_2 = $builder->build(
391 { source => 'Borrower',
392 value => {
393 dateexpiry => $a_month_ago,
394 categorycode => $patron_category->{categorycode},
398 my $patron_3 = $builder->build(
399 { source => 'Borrower',
400 value => {
401 dateexpiry => $a_month_later,
402 categorycode => $patron_category->{categorycode},
406 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
407 my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
408 my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
410 is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
412 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
413 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
414 my $expiry_date = $retrieved_patron->renew_account;
415 is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
416 my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
417 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" );
418 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
419 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
421 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
422 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
423 $expiry_date = $retrieved_patron->renew_account;
424 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
425 $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
426 is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
427 $retrieved_expiry_date = $retrieved_patron->dateexpiry;
428 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
429 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
430 is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
432 t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
433 $expiry_date = $retrieved_patron_2->renew_account;
434 is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
435 $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
436 is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
438 $expiry_date = $retrieved_patron_3->renew_account;
439 is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
440 $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
441 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" );
443 $retrieved_patron->delete;
444 $retrieved_patron_2->delete;
445 $retrieved_patron_3->delete;
447 Time::Fake->reset;
450 subtest "move_to_deleted" => sub {
451 plan tests => 5;
452 my $originally_updated_on = '2016-01-01 12:12:12';
453 my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
454 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
455 is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
456 ; # FIXME This should be Koha::Deleted::Patron
457 my $deleted_patron = $schema->resultset('Deletedborrower')
458 ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
459 ->next;
460 ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
461 ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
462 isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
463 $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
464 is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
465 $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup
468 subtest "delete" => sub {
469 plan tests => 6;
470 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
471 my $patron = $builder->build( { source => 'Borrower' } );
472 my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
473 my $hold = $builder->build(
474 { source => 'Reserve',
475 value => { borrowernumber => $patron->{borrowernumber} }
478 my $list = $builder->build(
479 { source => 'Virtualshelve',
480 value => { owner => $patron->{borrowernumber} }
484 my $deleted = $retrieved_patron->delete;
485 is( ref($deleted), 'Koha::Patron', 'Koha::Patron->delete should return the deleted patron object if the patron has been correctly deleted' );
487 is( Koha::Patrons->find( $patron->{borrowernumber} ), undef, 'Koha::Patron->delete should have deleted the patron' );
489 is (Koha::Old::Holds->search( { reserve_id => $hold->{ reserve_id } } )->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| );
491 is( Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have cancelled patron's holds 2| );
493 is( Koha::Virtualshelves->search( { owner => $patron->{borrowernumber} } )->count, 0, q|Koha::Patron->delete should have deleted patron's lists| );
495 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $retrieved_patron->borrowernumber } )->count;
496 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
499 subtest 'Koha::Patrons->delete' => sub {
500 plan tests => 3;
502 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
503 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
504 my $id1 = $patron1->borrowernumber;
505 my $set = Koha::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
506 is( $set->count, 2, 'Two patrons found as expected' );
507 is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
508 my $deleted_patrons = Koha::Old::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
509 is( $deleted_patrons->count, 2, 'Patrons moved to deletedborrowers' );
511 # See other tests in t/db_dependent/Koha/Objects.t
514 subtest 'add_enrolment_fee_if_needed' => sub {
515 plan tests => 4;
517 my $enrolmentfees = { K => 5, J => 10, YA => 20 };
518 foreach( keys %{$enrolmentfees} ) {
519 ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
521 my $enrolmentfee_K = $enrolmentfees->{K};
522 my $enrolmentfee_J = $enrolmentfees->{J};
523 my $enrolmentfee_YA = $enrolmentfees->{YA};
525 my %borrower_data = (
526 firstname => 'my firstname',
527 surname => 'my surname',
528 categorycode => 'K',
529 branchcode => $library->{branchcode},
532 my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
533 $borrower_data{borrowernumber} = $borrowernumber;
535 my $patron = Koha::Patrons->find( $borrowernumber );
536 my $total = $patron->account->balance;
537 is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
539 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
540 $borrower_data{categorycode} = 'J';
541 $patron->set(\%borrower_data)->store;
542 $total = $patron->account->balance;
543 is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
545 $borrower_data{categorycode} = 'K';
546 $patron->set(\%borrower_data)->store;
547 t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
549 $borrower_data{categorycode} = 'J';
550 $patron->set(\%borrower_data)->store;
551 $total = $patron->account->balance;
552 is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
554 # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
555 $patron->categorycode('YA')->store;
556 $total = $patron->account->balance;
557 is( int($total),
558 int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
559 "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
562 $patron->delete;
565 subtest 'checkouts + pending_checkouts + get_overdues + old_checkouts' => sub {
566 plan tests => 17;
568 my $library = $builder->build( { source => 'Branch' } );
569 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
570 my $item_1 = $builder->build(
572 source => 'Item',
573 value => {
574 homebranch => $library->{branchcode},
575 holdingbranch => $library->{branchcode},
576 biblionumber => $biblionumber_1,
577 itemlost => 0,
578 withdrawn => 0,
582 my $item_2 = $builder->build(
584 source => 'Item',
585 value => {
586 homebranch => $library->{branchcode},
587 holdingbranch => $library->{branchcode},
588 biblionumber => $biblionumber_1,
589 itemlost => 0,
590 withdrawn => 0,
594 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
595 my $item_3 = $builder->build(
597 source => 'Item',
598 value => {
599 homebranch => $library->{branchcode},
600 holdingbranch => $library->{branchcode},
601 biblionumber => $biblionumber_2,
602 itemlost => 0,
603 withdrawn => 0,
607 my $patron = $builder->build(
609 source => 'Borrower',
610 value => { branchcode => $library->{branchcode} }
614 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
615 my $checkouts = $patron->checkouts;
616 is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
617 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
618 my $pending_checkouts = $patron->pending_checkouts;
619 is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
620 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
621 my $old_checkouts = $patron->old_checkouts;
622 is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
623 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
625 # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
626 $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
628 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
630 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
631 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
632 AddIssue( $patron, $item_3->{barcode} );
634 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
635 $checkouts = $patron->checkouts;
636 is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
637 is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
638 $pending_checkouts = $patron->pending_checkouts;
639 is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
640 is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
642 my $first_checkout = $pending_checkouts->next;
643 is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->{biblionumber}, 'pending_checkouts should prefetch values from other tables (here biblio)' );
645 my $overdues = $patron->get_overdues;
646 is( $overdues->count, 2, 'Patron should have 2 overdues');
647 is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->get_overdues should return Koha::Checkouts' );
648 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
649 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
652 C4::Circulation::AddReturn( $item_1->{barcode} );
653 C4::Circulation::AddReturn( $item_2->{barcode} );
654 $old_checkouts = $patron->old_checkouts;
655 is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
656 is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
658 # Clean stuffs
659 Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
660 $patron->delete;
663 subtest 'get_routing_lists' => sub {
664 plan tests => 5;
666 my $biblio = Koha::Biblio->new()->store();
667 my $subscription = Koha::Subscription->new({
668 biblionumber => $biblio->biblionumber,
670 )->store;
672 my $patron = $builder->build( { source => 'Borrower' } );
673 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
675 is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
677 my $routinglist_count = Koha::Subscription::Routinglists->count;
678 my $routinglist = Koha::Subscription::Routinglist->new({
679 borrowernumber => $patron->borrowernumber,
680 ranking => 5,
681 subscriptionid => $subscription->subscriptionid
682 })->store;
684 is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
686 my $routinglists = $patron->get_routing_lists;
687 is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
688 is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
690 my $subscription2 = Koha::Subscription->new({
691 biblionumber => $biblio->biblionumber,
693 )->store;
694 my $routinglist2 = Koha::Subscription::Routinglist->new({
695 borrowernumber => $patron->borrowernumber,
696 ranking => 1,
697 subscriptionid => $subscription2->subscriptionid
698 })->store;
700 is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
702 $patron->delete; # Clean up for later tests
706 subtest 'get_age' => sub {
707 plan tests => 31;
709 my $patron = $builder->build( { source => 'Borrower' } );
710 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
712 my @dates = (
714 today => '2020-02-28',
715 has_12 => { date => '2007-08-27', expected_age => 12 },
716 almost_18 => { date => '2002-03-01', expected_age => 17 },
717 has_18_today => { date => '2002-02-28', expected_age => 18 },
718 had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
719 almost_16 => { date => '2004-02-29', expected_age => 15 },
720 has_16_today => { date => '2004-02-28', expected_age => 16 },
721 had_16_yesterday => { date => '2004-02-27', expected_age => 16 },
722 new_born => { date => '2020-01-27', expected_age => 0 },
725 today => '2020-02-29',
726 has_12 => { date => '2007-08-27', expected_age => 12 },
727 almost_18 => { date => '2002-03-01', expected_age => 17 },
728 has_18_today => { date => '2002-02-28', expected_age => 18 },
729 had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
730 almost_16 => { date => '2004-03-01', expected_age => 15 },
731 has_16_today => { date => '2004-02-29', expected_age => 16 },
732 had_16_yesterday => { date => '2004-02-28', expected_age => 16 },
733 new_born => { date => '2020-01-27', expected_age => 0 },
736 today => '2020-03-01',
737 has_12 => { date => '2007-08-27', expected_age => 12 },
738 almost_18 => { date => '2002-03-02', expected_age => 17 },
739 has_18_today => { date => '2002-03-01', expected_age => 18 },
740 had_18_yesterday => { date => '2002-02-28', expected_age => 18 },
741 almost_16 => { date => '2004-03-02', expected_age => 15 },
742 has_16_today => { date => '2004-03-01', expected_age => 16 },
743 had_16_yesterday => { date => '2004-02-29', expected_age => 16 },
746 today => '2019-01-31',
747 has_12 => { date => '2006-08-27', expected_age => 12 },
748 almost_18 => { date => '2001-02-01', expected_age => 17 },
749 has_18_today => { date => '2001-01-31', expected_age => 18 },
750 had_18_yesterday => { date => '2001-01-30', expected_age => 18 },
751 almost_16 => { date => '2003-02-01', expected_age => 15 },
752 has_16_today => { date => '2003-01-31', expected_age => 16 },
753 had_16_yesterday => { date => '2003-01-30', expected_age => 16 },
757 $patron->dateofbirth( undef );
758 is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
760 for my $date ( @dates ) {
762 my $dt = dt_from_string($date->{today});
764 Time::Fake->offset( $dt->epoch );
766 for my $k ( keys %$date ) {
767 next if $k eq 'today';
769 my $dob = $date->{$k};
770 $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
772 $patron->get_age,
773 $dob->{expected_age},
774 sprintf(
775 "Today=%s, dob=%s, should be %d",
776 $date->{today}, $dob->{date}, $dob->{expected_age}
781 Time::Fake->reset;
785 $patron->delete;
788 subtest 'is_valid_age' => sub {
789 plan tests => 10;
791 my $dt = dt_from_string('2020-02-28');
793 Time::Fake->offset( $dt->epoch );
795 my $category = $builder->build({
796 source => 'Category',
797 value => {
798 categorycode => 'AGE_5_10',
799 dateofbirthrequired => 5,
800 upperagelimit => 10
803 $category = Koha::Patron::Categories->find( $category->{categorycode} );
805 my $patron = $builder->build({
806 source => 'Borrower',
807 value => {
808 categorycode => 'AGE_5_10'
811 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
814 $patron->dateofbirth( undef );
815 is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
817 my @dates = (
819 today => '2020-02-28',
820 add_m12_m6_m1 =>
821 { date => '2007-08-27', expected_age => 12, valid => 0 },
822 add_m3_m6_m1 =>
823 { date => '2016-08-27', expected_age => 3, valid => 0 },
824 add_m7_m6_m1 =>
825 { date => '2015-02-28', expected_age => 7, valid => 1 },
826 add_m5_0_0 =>
827 { date => '2015-02-28', expected_age => 5, valid => 1 },
828 add_m5_0_p1 =>
829 { date => '2015-03-01', expected_age => 5, valid => 0 },
830 add_m5_0_m1 =>
831 { date => '2015-02-27', expected_age => 5, valid => 1 },
832 add_m11_0_0 =>
833 { date => '2009-02-28', expected_age => 11, valid => 0 },
834 add_m11_0_p1 =>
835 { date => '2009-03-01', expected_age => 11, valid => 1 },
836 add_m11_0_m1 =>
837 { date => '2009-02-27', expected_age => 11, valid => 0 },
841 for my $date ( @dates ) {
843 my $dt = dt_from_string($date->{today});
845 Time::Fake->offset( $dt->epoch );
847 for my $k ( keys %$date ) {
848 next if $k eq 'today';
850 my $dob = $date->{$k};
851 $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
853 $patron->is_valid_age,
854 $dob->{valid},
855 sprintf(
856 "Today=%s, dob=%s, is %s, should be valid=%s",
857 $date->{today}, $dob->{date}, $dob->{expected_age}, $dob->{valid}
862 Time::Fake->reset;
866 $patron->delete;
867 $category->delete;
870 subtest 'account' => sub {
871 plan tests => 1;
873 my $patron = $builder->build({source => 'Borrower'});
875 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
876 my $account = $patron->account;
877 is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' );
879 $patron->delete;
882 subtest 'search_upcoming_membership_expires' => sub {
883 plan tests => 9;
885 my $expiry_days = 15;
886 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
887 my $nb_of_days_before = 1;
888 my $nb_of_days_after = 2;
890 my $builder = t::lib::TestBuilder->new();
892 my $library = $builder->build({ source => 'Branch' });
894 # before we add borrowers to this branch, add the expires we have now
895 # note that this pertains to the current mocked setting of the pref
896 # for this reason we add the new branchcode to most of the tests
897 my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
899 my $patron_1 = $builder->build({
900 source => 'Borrower',
901 value => {
902 branchcode => $library->{branchcode},
903 dateexpiry => dt_from_string->add( days => $expiry_days )
907 my $patron_2 = $builder->build({
908 source => 'Borrower',
909 value => {
910 branchcode => $library->{branchcode},
911 dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
915 my $patron_3 = $builder->build({
916 source => 'Borrower',
917 value => {
918 branchcode => $library->{branchcode},
919 dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
923 # Test without extra parameters
924 my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
925 is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
927 # Test with branch
928 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
929 is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
930 my $expired = $upcoming_mem_expires->next;
931 is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
932 is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
933 is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
935 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
936 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
937 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
939 # Test MembershipExpiryDaysNotice == undef
940 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
941 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
942 is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
944 # Test the before parameter
945 t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
946 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
947 is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
948 # Test after parameter also
949 $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
950 is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
951 Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
954 subtest 'holds and old_holds' => sub {
955 plan tests => 6;
957 my $library = $builder->build( { source => 'Branch' } );
958 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
959 my $item_1 = $builder->build(
961 source => 'Item',
962 value => {
963 homebranch => $library->{branchcode},
964 holdingbranch => $library->{branchcode},
965 biblionumber => $biblionumber_1
969 my $item_2 = $builder->build(
971 source => 'Item',
972 value => {
973 homebranch => $library->{branchcode},
974 holdingbranch => $library->{branchcode},
975 biblionumber => $biblionumber_1
979 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
980 my $item_3 = $builder->build(
982 source => 'Item',
983 value => {
984 homebranch => $library->{branchcode},
985 holdingbranch => $library->{branchcode},
986 biblionumber => $biblionumber_2
990 my $patron = $builder->build(
992 source => 'Borrower',
993 value => { branchcode => $library->{branchcode} }
997 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
998 my $holds = $patron->holds;
999 is( ref($holds), 'Koha::Holds',
1000 'Koha::Patron->holds should return a Koha::Holds objects' );
1001 is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
1003 C4::Reserves::AddReserve(
1005 branchcode => $library->{branchcode},
1006 borrowernumber => $patron->borrowernumber,
1007 biblionumber => $biblionumber_1
1010 # In the future
1011 C4::Reserves::AddReserve(
1013 branchcode => $library->{branchcode},
1014 borrowernumber => $patron->borrowernumber,
1015 biblionumber => $biblionumber_2,
1016 expiration_date => dt_from_string->add( days => 2 )
1020 $holds = $patron->holds;
1021 is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
1023 my $old_holds = $patron->old_holds;
1024 is( ref($old_holds), 'Koha::Old::Holds',
1025 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
1026 is( $old_holds->count, 0, 'There should not be any old holds yet');
1028 my $hold = $holds->next;
1029 $hold->cancel;
1031 $old_holds = $patron->old_holds;
1032 is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold');
1034 $old_holds->delete;
1035 $holds->delete;
1036 $patron->delete;
1039 subtest 'notice_email_address' => sub {
1040 plan tests => 2;
1042 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1044 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'OFF' );
1045 is ($patron->notice_email_address, $patron->email, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is off");
1047 t::lib::Mocks::mock_preference( 'AutoEmailPrimaryAddress', 'emailpro' );
1048 is ($patron->notice_email_address, $patron->emailpro, "Koha::Patron->notice_email_address returns correct value when AutoEmailPrimaryAddress is emailpro");
1050 $patron->delete;
1053 subtest 'search_patrons_to_anonymise & anonymise_issue_history' => sub {
1054 plan tests => 4;
1056 # TODO create a subroutine in t::lib::Mocks
1057 my $branch = $builder->build({ source => 'Branch' });
1058 my $userenv_patron = $builder->build_object({
1059 class => 'Koha::Patrons',
1060 value => { branchcode => $branch->{branchcode}, flags => 0 },
1062 t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
1064 my $anonymous = $builder->build( { source => 'Borrower', }, );
1066 t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
1068 subtest 'patron privacy is 1 (default)' => sub {
1069 plan tests => 9;
1071 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1072 my $patron = $builder->build(
1073 { source => 'Borrower',
1074 value => { privacy => 1, }
1077 my $item_1 = $builder->build(
1078 { source => 'Item',
1079 value => {
1080 itemlost => 0,
1081 withdrawn => 0,
1085 my $issue_1 = $builder->build(
1086 { source => 'Issue',
1087 value => {
1088 borrowernumber => $patron->{borrowernumber},
1089 itemnumber => $item_1->{itemnumber},
1093 my $item_2 = $builder->build(
1094 { source => 'Item',
1095 value => {
1096 itemlost => 0,
1097 withdrawn => 0,
1101 my $issue_2 = $builder->build(
1102 { source => 'Issue',
1103 value => {
1104 borrowernumber => $patron->{borrowernumber},
1105 itemnumber => $item_2->{itemnumber},
1110 my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1111 my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->{barcode}, undef, undef, dt_from_string('2011-11-11') );
1112 is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
1114 my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
1115 is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
1117 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history( { before => '2010-10-11' } );
1118 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1120 $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1121 is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
1123 my $dbh = C4::Context->dbh;
1124 my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
1125 $sth->execute($item_1->{itemnumber});
1126 my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1127 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
1128 $sth->execute($item_2->{itemnumber});
1129 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1130 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
1132 $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } )->anonymise_issue_history;
1133 $sth->execute($item_2->{itemnumber});
1134 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1135 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
1137 my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
1138 $sth_reset->execute( $patron->{borrowernumber}, $item_1->{itemnumber} );
1139 $sth_reset->execute( $patron->{borrowernumber}, $item_2->{itemnumber} );
1140 $rows_affected = Koha::Patrons->search_patrons_to_anonymise->anonymise_issue_history;
1141 $sth->execute($item_1->{itemnumber});
1142 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1143 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
1144 $sth->execute($item_2->{itemnumber});
1145 ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1146 is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
1148 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1151 subtest 'patron privacy is 0 (forever)' => sub {
1152 plan tests => 2;
1154 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1155 my $patron = $builder->build(
1156 { source => 'Borrower',
1157 value => { privacy => 0, }
1160 my $item = $builder->build(
1161 { source => 'Item',
1162 value => {
1163 itemlost => 0,
1164 withdrawn => 0,
1168 my $issue = $builder->build(
1169 { source => 'Issue',
1170 value => {
1171 borrowernumber => $patron->{borrowernumber},
1172 itemnumber => $item->{itemnumber},
1177 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1178 is( $returned, 1, 'The item should have been returned' );
1180 my $dbh = C4::Context->dbh;
1181 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1182 SELECT borrowernumber FROM old_issues where itemnumber = ?
1183 |, undef, $item->{itemnumber});
1184 is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1185 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1188 t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1190 subtest 'AnonymousPatron is not defined' => sub {
1191 plan tests => 3;
1193 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1194 my $patron = $builder->build(
1195 { source => 'Borrower',
1196 value => { privacy => 1, }
1199 my $item = $builder->build(
1200 { source => 'Item',
1201 value => {
1202 itemlost => 0,
1203 withdrawn => 0,
1207 my $issue = $builder->build(
1208 { source => 'Issue',
1209 value => {
1210 borrowernumber => $patron->{borrowernumber},
1211 itemnumber => $item->{itemnumber},
1216 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1217 is( $returned, 1, 'The item should have been returned' );
1218 my $rows_affected = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->anonymise_issue_history( { before => '2010-10-11' } );
1219 ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1221 my $dbh = C4::Context->dbh;
1222 my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1223 SELECT borrowernumber FROM old_issues where itemnumber = ?
1224 |, undef, $item->{itemnumber});
1225 is( $borrowernumber_used_to_anonymised, undef, 'With AnonymousPatron is not defined, the issue should have been anonymised anyway' );
1226 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1229 subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1230 plan tests => 1;
1231 t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1232 my $patron = $builder->build(
1233 { source => 'Borrower',
1234 value => { privacy => 1 } # Another branchcode than the logged in librarian
1237 my $item = $builder->build(
1238 { source => 'Item',
1239 value => {
1240 itemlost => 0,
1241 withdrawn => 0,
1245 my $issue = $builder->build(
1246 { source => 'Issue',
1247 value => {
1248 borrowernumber => $patron->{borrowernumber},
1249 itemnumber => $item->{itemnumber},
1254 my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->{barcode}, undef, undef, dt_from_string('2010-10-10') );
1255 is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1256 Koha::Patrons->find( $patron->{borrowernumber})->delete;
1259 Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1260 $userenv_patron->delete;
1262 # Reset IndependentBranches for further tests
1263 t::lib::Mocks::mock_preference('IndependentBranches', 0);
1266 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1267 plan tests => 3;
1269 # group1
1270 # + library_11
1271 # + library_12
1272 # group2
1273 # + library21
1274 $nb_of_patrons = Koha::Patrons->search->count;
1275 my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1276 my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1277 my $library_11 = $builder->build( { source => 'Branch' } );
1278 my $library_12 = $builder->build( { source => 'Branch' } );
1279 my $library_21 = $builder->build( { source => 'Branch' } );
1280 $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1281 $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1282 $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1283 Koha::Library::Group->new(
1284 { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1285 Koha::Library::Group->new(
1286 { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1287 Koha::Library::Group->new(
1288 { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1290 my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1291 # 2 patrons from library_11 (group1)
1292 # patron_11_1 see patron's infos from outside its group
1293 # Setting flags => undef to not be considered as superlibrarian
1294 my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1295 $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1296 $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1297 $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1298 # patron_11_2 can only see patron's info from its group
1299 my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1300 $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1301 $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1302 # 1 patron from library_12 (group1)
1303 my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1304 $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1305 # 1 patron from library_21 (group2) can only see patron's info from its group
1306 my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1307 $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1308 $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1310 # Pfiou, we can start now!
1311 subtest 'libraries_where_can_see_patrons' => sub {
1312 plan tests => 3;
1314 my @branchcodes;
1316 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1317 @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1318 is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1320 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1321 @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1322 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| );
1324 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1325 @branchcodes = $patron_21->libraries_where_can_see_patrons;
1326 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| );
1328 subtest 'can_see_patron_infos' => sub {
1329 plan tests => 6;
1331 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1332 is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1333 is( $patron_11_1->can_see_patron_infos( $patron_12 ), 1, q|patron_11_1 can see patron_12, from its group| );
1334 is( $patron_11_1->can_see_patron_infos( $patron_21 ), 1, q|patron_11_1 can see patron_11_2, from another group| );
1336 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1337 is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1338 is( $patron_11_2->can_see_patron_infos( $patron_12 ), 1, q|patron_11_2 can see patron_12, from its group| );
1339 is( $patron_11_2->can_see_patron_infos( $patron_21 ), 0, q|patron_11_2 can NOT see patron_21, from another group| );
1341 subtest 'search_limited' => sub {
1342 plan tests => 6;
1344 t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1345 my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1346 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1347 is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1349 t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1350 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1351 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' );
1353 t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1354 is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1355 is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1357 $patron_11_1->delete;
1358 $patron_11_2->delete;
1359 $patron_12->delete;
1360 $patron_21->delete;
1363 subtest 'account_locked' => sub {
1364 plan tests => 13;
1365 my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1366 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1367 for my $value ( undef, '', 0 ) {
1368 t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1369 $patron->login_attempts(0)->store;
1370 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1371 $patron->login_attempts(1)->store;
1372 is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1373 $patron->login_attempts(-1)->store;
1374 is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1377 t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1378 $patron->login_attempts(2)->store;
1379 is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1380 $patron->login_attempts(3)->store;
1381 is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1382 $patron->login_attempts(4)->store;
1383 is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1384 $patron->login_attempts(-1)->store;
1385 is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1387 $patron->delete;
1390 subtest 'is_child | is_adult' => sub {
1391 plan tests => 8;
1392 my $category = $builder->build_object(
1394 class => 'Koha::Patron::Categories',
1395 value => { category_type => 'A' }
1398 my $patron_adult = $builder->build_object(
1400 class => 'Koha::Patrons',
1401 value => { categorycode => $category->categorycode }
1404 $category = $builder->build_object(
1406 class => 'Koha::Patron::Categories',
1407 value => { category_type => 'I' }
1410 my $patron_adult_i = $builder->build_object(
1412 class => 'Koha::Patrons',
1413 value => { categorycode => $category->categorycode }
1416 $category = $builder->build_object(
1418 class => 'Koha::Patron::Categories',
1419 value => { category_type => 'C' }
1422 my $patron_child = $builder->build_object(
1424 class => 'Koha::Patrons',
1425 value => { categorycode => $category->categorycode }
1428 $category = $builder->build_object(
1430 class => 'Koha::Patron::Categories',
1431 value => { category_type => 'O' }
1434 my $patron_other = $builder->build_object(
1436 class => 'Koha::Patrons',
1437 value => { categorycode => $category->categorycode }
1440 is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1441 is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1442 is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1443 is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1445 is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1446 is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1447 is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1448 is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1450 # Clean up
1451 $patron_adult->delete;
1452 $patron_adult_i->delete;
1453 $patron_child->delete;
1454 $patron_other->delete;
1457 subtest 'get_overdues' => sub {
1458 plan tests => 7;
1460 my $library = $builder->build( { source => 'Branch' } );
1461 my ($biblionumber_1) = AddBiblio( MARC::Record->new, '' );
1462 my $item_1 = $builder->build(
1464 source => 'Item',
1465 value => {
1466 homebranch => $library->{branchcode},
1467 holdingbranch => $library->{branchcode},
1468 biblionumber => $biblionumber_1
1472 my $item_2 = $builder->build(
1474 source => 'Item',
1475 value => {
1476 homebranch => $library->{branchcode},
1477 holdingbranch => $library->{branchcode},
1478 biblionumber => $biblionumber_1
1482 my ($biblionumber_2) = AddBiblio( MARC::Record->new, '' );
1483 my $item_3 = $builder->build(
1485 source => 'Item',
1486 value => {
1487 homebranch => $library->{branchcode},
1488 holdingbranch => $library->{branchcode},
1489 biblionumber => $biblionumber_2
1493 my $patron = $builder->build(
1495 source => 'Borrower',
1496 value => { branchcode => $library->{branchcode} }
1500 t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1502 AddIssue( $patron, $item_1->{barcode}, DateTime->now->subtract( days => 1 ) );
1503 AddIssue( $patron, $item_2->{barcode}, DateTime->now->subtract( days => 5 ) );
1504 AddIssue( $patron, $item_3->{barcode} );
1506 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1507 my $overdues = $patron->get_overdues;
1508 is( $overdues->count, 2, 'Patron should have 2 overdues');
1509 is( $overdues->next->itemnumber, $item_1->{itemnumber}, 'The issue should be returned in the same order as they have been done, first is correct' );
1510 is( $overdues->next->itemnumber, $item_2->{itemnumber}, 'The issue should be returned in the same order as they have been done, second is correct' );
1512 my $o = $overdues->reset->next;
1513 my $unblessed_overdue = $o->unblessed_all_relateds;
1514 is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1515 is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1516 is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1517 is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1519 # Clean stuffs
1520 $patron->checkouts->delete;
1521 $patron->delete;
1524 subtest 'userid_is_valid' => sub {
1525 plan tests => 9;
1527 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1528 my $patron_category = $builder->build_object(
1530 class => 'Koha::Patron::Categories',
1531 value => { category_type => 'P', enrolmentfee => 0 }
1534 my %data = (
1535 cardnumber => "123456789",
1536 firstname => "Tomasito",
1537 surname => "None",
1538 categorycode => $patron_category->categorycode,
1539 branchcode => $library->branchcode,
1542 my $expected_userid_patron_1 = 'tomasito.none';
1543 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1544 my $patron_1 = Koha::Patrons->find($borrowernumber);
1545 is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1546 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1548 $patron_1->userid( 'tomasito.non' );
1549 is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1550 1, 'recently created userid -> unique (borrowernumber passed)' );
1552 $patron_1->userid( 'tomasitoxxx' );
1553 is( $patron_1->has_valid_userid,
1554 1, 'non-existent userid -> unique (borrowernumber passed)' );
1555 $patron_1->discard_changes; # We compare with the original userid later
1557 my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1558 is( $patron_not_in_storage->has_valid_userid,
1559 0, 'userid exists for another patron, patron is not in storage yet' );
1561 $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1562 is( $patron_not_in_storage->has_valid_userid,
1563 1, 'non-existent userid, patron is not in storage yet' );
1565 # Regression tests for BZ12226
1566 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1567 is( $db_patron->has_valid_userid,
1568 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1570 # Add a new borrower with the same userid but different cardnumber
1571 $data{cardnumber} = "987654321";
1572 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1573 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1574 $patron_2->userid($patron_1->userid);
1575 is( $patron_2->has_valid_userid,
1576 0, 'The userid is already in used, it cannot be used for another patron' );
1578 my $new_userid = 'a_user_id';
1579 $data{cardnumber} = "234567890";
1580 $data{userid} = 'a_user_id';
1581 $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1582 my $patron_3 = Koha::Patrons->find($borrowernumber);
1583 is( $patron_3->userid, $new_userid,
1584 'Koha::Patron->store should insert the given userid' );
1586 # Cleanup
1587 $patron_1->delete;
1588 $patron_2->delete;
1589 $patron_3->delete;
1592 subtest 'generate_userid' => sub {
1593 plan tests => 7;
1595 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1596 my $patron_category = $builder->build_object(
1598 class => 'Koha::Patron::Categories',
1599 value => { category_type => 'P', enrolmentfee => 0 }
1602 my %data = (
1603 cardnumber => "123456789",
1604 firstname => "Tômàsító",
1605 surname => "Ñoné",
1606 categorycode => $patron_category->categorycode,
1607 branchcode => $library->branchcode,
1610 my $expected_userid_patron_1 = 'tomasito.none';
1611 my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } );
1612 $new_patron->generate_userid;
1613 my $userid = $new_patron->userid;
1614 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1615 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1616 my $patron_1 = Koha::Patrons->find($borrowernumber);
1617 is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1619 $new_patron->generate_userid;
1620 $userid = $new_patron->userid;
1621 is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' );
1622 $data{cardnumber} = '987654321';
1623 my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1624 my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1625 isnt( $patron_2->userid, 'tomasito',
1626 "Patron with duplicate userid has new userid generated" );
1627 is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable
1628 "Patron with duplicate userid has new userid generated (1 is appened" );
1630 $new_patron->generate_userid;
1631 $userid = $new_patron->userid;
1632 is( $userid, $expected_userid_patron_1 . '2', 'generate_userid should generate the userid we expect' );
1634 $patron_1 = Koha::Patrons->find($borrowernumber);
1635 $patron_1->userid(undef);
1636 $patron_1->generate_userid;
1637 $userid = $patron_1->userid;
1638 is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' );
1640 # Cleanup
1641 $patron_1->delete;
1642 $patron_2->delete;
1645 $nb_of_patrons = Koha::Patrons->search->count;
1646 $retrieved_patron_1->delete;
1647 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1649 subtest 'BorrowersLog tests' => sub {
1650 plan tests => 4;
1652 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1653 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1655 my $cardnumber = $patron->cardnumber;
1656 $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1657 $patron->store;
1659 my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1660 my $log_info = from_json( $logs[0]->info );
1661 is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1662 is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1663 is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1665 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1666 $patron->track_login();
1667 @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1668 is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1671 $schema->storage->txn_rollback;
1673 subtest 'Test Koha::Patrons::merge' => sub {
1674 plan tests => 110;
1676 my $schema = Koha::Database->new()->schema();
1678 my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1680 $schema->storage->txn_begin;
1682 my $keeper = $builder->build_object({ class => 'Koha::Patrons' });
1683 my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1684 my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1686 while (my ($r, $field) = each(%$resultsets)) {
1687 $builder->build({ source => $r, value => { $field => $keeper->id } });
1688 $builder->build({ source => $r, value => { $field => $loser_1 } });
1689 $builder->build({ source => $r, value => { $field => $loser_2 } });
1691 my $keeper_rs =
1692 $schema->resultset($r)->search( { $field => $keeper->id } );
1693 is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1695 my $loser_1_rs =
1696 $schema->resultset($r)->search( { $field => $loser_1 } );
1697 is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1699 my $loser_2_rs =
1700 $schema->resultset($r)->search( { $field => $loser_2 } );
1701 is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1704 my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1706 while (my ($r, $field) = each(%$resultsets)) {
1707 my $keeper_rs =
1708 $schema->resultset($r)->search( {$field => $keeper->id } );
1709 is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1712 is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1713 is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1715 $schema->storage->txn_rollback;
1718 subtest '->store' => sub {
1719 plan tests => 7;
1720 my $schema = Koha::Database->new->schema;
1721 $schema->storage->txn_begin;
1723 my $print_error = $schema->storage->dbh->{PrintError};
1724 $schema->storage->dbh->{PrintError} = 0; ; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
1726 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1727 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1729 throws_ok
1730 { $patron_2->userid($patron_1->userid)->store; }
1731 'Koha::Exceptions::Object::DuplicateID',
1732 'Koha::Patron->store raises an exception on duplicate ID';
1734 # Test password
1735 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1736 my $password = 'password';
1737 $patron_1->set_password({ password => $password });
1738 like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1739 my $digest = $patron_1->password;
1740 $patron_1->surname('xxx')->store;
1741 is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1743 # Test uppercasesurnames
1744 t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 );
1745 my $surname = lc $patron_1->surname;
1746 $patron_1->surname($surname)->store;
1747 isnt( $patron_1->surname, $surname,
1748 'Surname converts to uppercase on store.');
1749 t::lib::Mocks::mock_preference( 'uppercasesurnames', 0 );
1750 $patron_1->surname($surname)->store;
1751 is( $patron_1->surname, $surname,
1752 'Surname remains unchanged on store.');
1754 # Test relationship
1755 $patron_1->relationship("")->store;
1756 is( $patron_1->relationship, undef, );
1758 $schema->storage->dbh->{PrintError} = $print_error;
1759 $schema->storage->txn_rollback;
1761 subtest 'skip updated_on for BorrowersLog' => sub {
1762 plan tests => 1;
1763 $schema->storage->txn_begin;
1764 t::lib::Mocks::mock_preference('BorrowersLog', 1);
1765 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1766 $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1767 my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1768 is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1769 $schema->storage->txn_rollback;
1773 subtest '->set_password' => sub {
1775 plan tests => 14;
1777 $schema->storage->txn_begin;
1779 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1781 # Disable logging password changes for this tests
1782 t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1784 # Password-length tests
1785 t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1786 throws_ok { $patron->set_password({ password => 'ab' }); }
1787 'Koha::Exceptions::Password::TooShort',
1788 'minPasswordLength is undef, fall back to 3, fail test';
1789 is( "$@",
1790 'Password length (2) is shorter than required (3)',
1791 'Exception parameters passed correctly'
1794 t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1795 throws_ok { $patron->set_password({ password => 'ab' }); }
1796 'Koha::Exceptions::Password::TooShort',
1797 'minPasswordLength is 2, fall back to 3, fail test';
1799 t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1800 throws_ok { $patron->set_password({ password => 'abcb' }); }
1801 'Koha::Exceptions::Password::TooShort',
1802 'minPasswordLength is 5, fail test';
1804 # Trailing spaces tests
1805 throws_ok { $patron->set_password({ password => 'abcD12d ' }); }
1806 'Koha::Exceptions::Password::WhitespaceCharacters',
1807 'Password contains trailing spaces, exception is thrown';
1809 # Require strong password tests
1810 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1811 throws_ok { $patron->set_password({ password => 'abcd a' }); }
1812 'Koha::Exceptions::Password::TooWeak',
1813 'Password is too weak, exception is thrown';
1815 # Refresh patron from DB, just to make sure
1816 $patron->discard_changes;
1817 is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1819 $patron->set_password({ password => 'abcD12 34' });
1820 $patron->discard_changes;
1822 is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1824 lives_ok { $patron->set_password({ password => 'abcd a', skip_validation => 1 }) }
1825 'Password is weak, but skip_validation was passed, so no exception thrown';
1827 # Completeness
1828 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1829 $patron->login_attempts(3)->store;
1830 my $old_digest = $patron->password;
1831 $patron->set_password({ password => 'abcd a' });
1832 $patron->discard_changes;
1834 isnt( $patron->password, $old_digest, 'Password has been updated' );
1835 ok( checkpw_hash('abcd a', $patron->password), 'Password hash is correct' );
1836 is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1838 my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1839 is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1841 # Enable logging password changes
1842 t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1843 $patron->set_password({ password => 'abcd b' });
1845 $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1846 is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1848 $schema->storage->txn_rollback;
1851 $schema->storage->txn_begin;
1852 subtest 'search_unsubscribed' => sub {
1853 plan tests => 4;
1855 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1856 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
1857 is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
1859 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1860 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1862 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
1863 Koha::Patron::Consents->delete; # for correct counts
1864 Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string })->store;
1865 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
1867 # Add another refusal but shift the period
1868 t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
1869 Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string->subtract(days=>2) })->store;
1870 is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
1872 # Try another (special) attempts setting
1873 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
1874 # Lockout is now disabled
1875 # Patron2 still matches: refused earlier, not locked
1876 is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
1879 subtest 'search_anonymize_candidates' => sub {
1880 plan tests => 7;
1881 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1882 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1883 $patron1->anonymized(0);
1884 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1885 $patron2->anonymized(0);
1886 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1888 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
1889 is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
1891 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
1892 my $cnt = Koha::Patrons->search_anonymize_candidates->count;
1893 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1894 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1895 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
1897 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
1898 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1899 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1900 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1901 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1902 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1903 is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
1905 t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
1906 $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
1907 $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
1908 $cnt = Koha::Patrons->search_anonymize_candidates->count;
1909 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1910 $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
1911 is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
1913 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1914 $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1915 $patron1->login_attempts(0)->store;
1916 $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
1917 $patron2->login_attempts(0)->store;
1918 $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
1919 $patron1->login_attempts(3)->store;
1920 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1921 $cnt+1, 'Locked flag' );
1923 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1924 # Patron 1 still on 3 == locked
1925 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1926 $cnt+1, 'Still expect same number for FailedLoginAttempts empty' );
1927 $patron1->login_attempts(0)->store;
1928 # Patron 1 unlocked
1929 is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
1930 $cnt, 'Patron 1 unlocked' );
1933 subtest 'search_anonymized' => sub {
1934 plan tests => 3;
1935 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1937 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
1938 is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
1940 t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
1941 $patron1->dateexpiry( dt_from_string );
1942 $patron1->anonymized(0)->store;
1943 my $cnt = Koha::Patrons->search_anonymized->count;
1944 $patron1->anonymized(1)->store;
1945 is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
1946 $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
1947 is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
1950 subtest 'lock' => sub {
1951 plan tests => 8;
1953 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1954 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1955 my $hold = $builder->build_object({
1956 class => 'Koha::Holds',
1957 value => { borrowernumber => $patron1->borrowernumber },
1960 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
1961 my $expiry = dt_from_string->add(days => 1);
1962 $patron1->dateexpiry( $expiry );
1963 $patron1->lock;
1964 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1965 is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
1966 is( $patron1->holds->count, 1, 'No holds removed' );
1968 $patron1->lock({ expire => 1, remove => 1});
1969 isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
1970 is( $patron1->holds->count, 0, 'Holds removed' );
1972 # Disable lockout feature
1973 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
1974 $patron1->login_attempts(0);
1975 $patron1->dateexpiry( $expiry );
1976 $patron1->store;
1977 $patron1->lock;
1978 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
1980 # Trivial wrapper test (Koha::Patrons->lock)
1981 $patron1->login_attempts(0)->store;
1982 Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
1983 $patron1->discard_changes; # refresh
1984 $patron2->discard_changes;
1985 is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
1986 is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
1989 subtest 'anonymize' => sub {
1990 plan tests => 10;
1992 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
1993 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
1995 # First try patron with issues
1996 my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
1997 warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
1998 $issue->delete;
2000 t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
2001 my $surname = $patron1->surname; # expect change, no clear
2002 my $branchcode = $patron1->branchcode; # expect skip
2003 $patron1->anonymize;
2004 is($patron1->anonymized, 1, 'Check flag' );
2006 is( $patron1->dateofbirth, undef, 'Birth date cleared' );
2007 is( $patron1->firstname, undef, 'First name cleared' );
2008 isnt( $patron1->surname, $surname, 'Surname changed' );
2009 ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
2010 is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
2011 is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
2013 # Test wrapper in Koha::Patrons
2014 $patron1->surname($surname)->store; # restore
2015 my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
2016 $patron1->discard_changes; # refresh
2017 isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
2018 $patron2->discard_changes; # refresh
2019 is( $patron2->firstname, undef, 'First name patron2 cleared' );
2021 $schema->storage->txn_rollback;
2023 subtest 'extended_attributes' => sub {
2024 plan tests => 14;
2025 my $schema = Koha::Database->new->schema;
2026 $schema->storage->txn_begin;
2028 my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
2029 my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
2031 t::lib::Mocks::mock_userenv({ patron => $patron_1 });
2033 my $attribute_type1 = Koha::Patron::Attribute::Type->new(
2035 code => 'my code1',
2036 description => 'my description1',
2037 unique_id => 1
2039 )->store;
2040 my $attribute_type2 = Koha::Patron::Attribute::Type->new(
2042 code => 'my code2',
2043 description => 'my description2',
2044 opac_display => 1,
2045 staff_searchable => 1
2047 )->store;
2049 my $attribute_type3 = $builder->build_object({ class => 'Koha::Patron::Attribute::Types' });
2051 my $deleted_attribute_type = $builder->build_object({ class => 'Koha::Patron::Attribute::Types' });
2052 my $deleted_attribute_type_code = $deleted_attribute_type->code;
2053 $deleted_attribute_type->delete;
2055 my $new_library = $builder->build( { source => 'Branch' } );
2056 my $attribute_type_limited = Koha::Patron::Attribute::Type->new(
2057 { code => 'my code3', description => 'my description3' } )->store;
2058 $attribute_type_limited->library_limits( [ $new_library->{branchcode} ] );
2060 my $attributes_for_1 = [
2062 attribute => 'my attribute1',
2063 code => $attribute_type1->code(),
2066 attribute => 'my attribute2',
2067 code => $attribute_type2->code(),
2070 attribute => 'my attribute limited',
2071 code => $attribute_type_limited->code(),
2075 my $attributes_for_2 = [
2077 attribute => 'my attribute12',
2078 code => $attribute_type1->code(),
2081 attribute => 'my attribute limited 2',
2082 code => $attribute_type_limited->code(),
2085 attribute => 'my nonexistent attribute 2',
2086 code => $deleted_attribute_type_code,
2090 my $extended_attributes = $patron_1->extended_attributes;
2091 is( ref($extended_attributes), 'Koha::Patron::Attributes', 'Koha::Patron->extended_attributes must return a Koha::Patron::Attribute set' );
2092 is( $extended_attributes->count, 0, 'There should not be attribute yet');
2094 $patron_1->extended_attributes->filter_by_branch_limitations->delete;
2095 $patron_2->extended_attributes->filter_by_branch_limitations->delete;
2096 $patron_1->extended_attributes($attributes_for_1);
2098 my $print_error = $schema->storage->dbh->{PrintError};
2099 $schema->storage->dbh->{PrintError} = 0;
2100 warning_like {
2101 $patron_2->extended_attributes($attributes_for_2);
2102 } [ qr/a foreign key constraint fails/, qr/a foreign key constraint fails/ ], 'nonexistent attribute should have not exploded but print a warning';
2103 $schema->storage->dbh->{PrintError} = $print_error;
2105 my $extended_attributes_for_1 = $patron_1->extended_attributes;
2106 is( $extended_attributes_for_1->count, 3, 'There should be 3 attributes now for patron 1');
2108 my $extended_attributes_for_2 = $patron_2->extended_attributes;
2109 is( $extended_attributes_for_2->count, 2, 'There should be 2 attributes now for patron 2');
2111 my $attribute_12 = $extended_attributes_for_2->search({ code => $attribute_type1->code });
2112 is( $attribute_12->next->attribute, 'my attribute12', 'search by code should return the correct attribute' );
2114 $attribute_12 = $patron_2->get_extended_attribute( $attribute_type1->code );
2115 is( $attribute_12->attribute, 'my attribute12', 'Koha::Patron->get_extended_attribute should return the correct attribute value' );
2117 warning_is {
2118 $extended_attributes_for_2 = $patron_2->extended_attributes->merge_with(
2121 attribute => 'my attribute12 XXX',
2122 code => $attribute_type1->code(),
2125 attribute => 'my nonexistent attribute 2',
2126 code => $deleted_attribute_type_code,
2129 attribute => 'my attribute 3', # Adding a new attribute using merge_with
2130 code => $attribute_type3->code,
2135 "Cannot merge element: unrecognized code = '$deleted_attribute_type_code'",
2136 "Trying to merge_with using a nonexistent attribute code should display a warning";
2138 is( @$extended_attributes_for_2, 3, 'There should be 3 attributes now for patron 3');
2139 my $expected_attributes_for_2 = [
2141 code => $attribute_type1->code(),
2142 attribute => 'my attribute12 XXX',
2145 code => $attribute_type_limited->code(),
2146 attribute => 'my attribute limited 2',
2149 attribute => 'my attribute 3',
2150 code => $attribute_type3->code,
2153 # Sorting them by code
2154 $expected_attributes_for_2 = [ sort { $a->{code} cmp $b->{code} } @$expected_attributes_for_2 ];
2156 is_deeply(
2159 code => $extended_attributes_for_2->[0]->{code},
2160 attribute => $extended_attributes_for_2->[0]->{attribute}
2163 code => $extended_attributes_for_2->[1]->{code},
2164 attribute => $extended_attributes_for_2->[1]->{attribute}
2167 code => $extended_attributes_for_2->[2]->{code},
2168 attribute => $extended_attributes_for_2->[2]->{attribute}
2171 $expected_attributes_for_2
2174 # TODO - What about multiple? POD explains the problem
2175 my $non_existent = $patron_2->get_extended_attribute( 'not_exist' );
2176 is( $non_existent, undef, 'Koha::Patron->get_extended_attribute must return undef if the attribute does not exist' );
2178 # Test branch limitations
2179 t::lib::Mocks::mock_userenv({ patron => $patron_2 });
2180 # Return all
2181 $extended_attributes_for_1 = $patron_1->extended_attributes;
2182 is( $extended_attributes_for_1->count, 3, 'There should be 2 attributes for patron 1, the limited one should be returned');
2184 # Return filtered
2185 $extended_attributes_for_1 = $patron_1->extended_attributes->filter_by_branch_limitations;
2186 is( $extended_attributes_for_1->count, 2, 'There should be 2 attributes for patron 1, the limited one should be returned');
2188 # Not filtered
2189 my $limited_value = $patron_1->get_extended_attribute( $attribute_type_limited->code );
2190 is( $limited_value->attribute, 'my attribute limited', );
2192 ## Do we need a filtered?
2193 #$limited_value = $patron_1->get_extended_attribute( $attribute_type_limited->code );
2194 #is( $limited_value, undef, );
2196 $schema->storage->txn_rollback;