3 # This file is part of Koha.
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20 use Test::More tests => 77;
25 use t::lib::TestBuilder;
28 use DateTime::Duration;
30 use C4::Circulation qw( AddReturn AddIssue );
32 use C4::Biblio qw( GetMarcFromKohaField ModBiblio );
35 use C4::Reserves qw( AddReserve AlterPriority CheckReserves ModReserve ModReserveAffect ReserveSlip CalculatePriority CanReserveBeCanceledFromOpac CanBookBeReserved IsAvailableForItemLevelRequest MoveReserve ChargeReserveFee RevertWaitingStatus CanItemBeReserved MergeHolds );
39 use Koha::DateUtils qw( dt_from_string output_pref );
43 use Koha::Notice::Templates;
45 use Koha::Patron::Categories;
46 use Koha::CirculationRules;
49 require_ok('C4::Reserves');
53 my $database = Koha::Database->new();
54 my $schema = $database->schema();
55 $schema->storage->txn_begin();
56 my $dbh = C4::Context->dbh;
57 $dbh->do('DELETE FROM circulation_rules');
59 my $builder = t::lib::TestBuilder->new;
61 my $frameworkcode = q//;
64 t::lib::Mocks::mock_preference('ReservesNeedReturns', 1);
66 # Somewhat arbitrary field chosen for age restriction unit tests. Must be added to db before the framework is cached
67 $dbh->do("update marc_subfield_structure set kohafield='biblioitems.agerestriction' where tagfield='521' and tagsubfield='a' and frameworkcode=?", undef, $frameworkcode);
68 my $cache = Koha::Caches->get_instance;
69 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
70 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
71 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
75 my $branch_1 = $builder->build({ source => 'Branch' })->{ branchcode };
76 my $branch_2 = $builder->build({ source => 'Branch' })->{ branchcode };
77 my $branch_3 = $builder->build({ source => 'Branch' })->{ branchcode };
79 my $category_1 = $builder->build({ source => 'Category' })->{ categorycode };
80 my $category_2 = $builder->build({ source => 'Category' })->{ categorycode };
82 my $itemtype = $builder->build( { source => 'Itemtype', value => { notforloan => 0 } } )->{itemtype};
84 t::lib::Mocks::mock_userenv({ branchcode => $branch_1 });
86 my $bibnum = $builder->build_sample_biblio({frameworkcode => $frameworkcode})->biblionumber;
88 # Create a helper item instance for testing
89 my $item = $builder->build_sample_item({ biblionumber => $bibnum, library => $branch_1, itype => $itemtype });
91 my $biblio_with_no_item = $builder->build_sample_biblio;
93 # Modify item; setting barcode.
94 my $testbarcode = '97531';
95 $item->barcode($testbarcode)->store; # FIXME We should not hardcode a barcode! Also, what's the purpose of this?
100 firstname => 'my firstname',
101 surname => 'my surname',
102 categorycode => $category_1,
103 branchcode => $branch_1,
105 Koha::Patron::Categories->find($category_1)->set({ enrolmentfee => 0})->store;
106 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
107 my $patron = Koha::Patrons->find( $borrowernumber );
108 my $borrower = $patron->unblessed;
109 my $biblionumber = $bibnum;
111 my $branchcode = Koha::Libraries->search->next->branchcode;
115 branchcode => $branchcode,
116 borrowernumber => $borrowernumber,
117 biblionumber => $biblionumber,
122 my ($status, $reserve, $all_reserves) = CheckReserves( $item );
124 is($status, "Reserved", "CheckReserves Test 1");
126 ok(exists($reserve->{reserve_id}), 'CheckReserves() include reserve_id in its response');
128 ($status, $reserve, $all_reserves) = CheckReserves( $item );
129 is($status, "Reserved", "CheckReserves Test 2");
132 ### Regression test for bug 10272
135 $requesters{$branch_1} = Koha::Patron->new({
136 branchcode => $branch_1,
137 categorycode => $category_2,
138 surname => "borrower from $branch_1",
139 })->store->borrowernumber;
140 for my $i ( 2 .. 5 ) {
141 $requesters{"CPL$i"} = Koha::Patron->new({
142 branchcode => $branch_1,
143 categorycode => $category_2,
144 surname => "borrower $i from $branch_1",
145 })->store->borrowernumber;
147 $requesters{$branch_2} = Koha::Patron->new({
148 branchcode => $branch_2,
149 categorycode => $category_2,
150 surname => "borrower from $branch_2",
151 })->store->borrowernumber;
152 $requesters{$branch_3} = Koha::Patron->new({
153 branchcode => $branch_3,
154 categorycode => $category_2,
155 surname => "borrower from $branch_3",
156 })->store->borrowernumber;
158 # Configure rules so that $branch_1 allows only $branch_1 patrons
159 # to request its items, while $branch_2 will allow its items
160 # to fill holds from anywhere.
162 $dbh->do('DELETE FROM circulation_rules');
163 Koha::CirculationRules->set_rules(
166 categorycode => undef,
169 reservesallowed => 25,
170 holds_per_record => 1,
175 # CPL allows only its own patrons to request its items
176 Koha::CirculationRules->set_rules(
178 branchcode => $branch_1,
181 holdallowed => 'from_home_library',
182 returnbranch => 'homebranch',
187 # ... while FPL allows anybody to request its items
188 Koha::CirculationRules->set_rules(
190 branchcode => $branch_2,
193 holdallowed => 'from_any_library',
194 returnbranch => 'homebranch',
199 my $bibnum2 = $builder->build_sample_biblio({frameworkcode => $frameworkcode})->biblionumber;
201 my ($itemnum_cpl, $itemnum_fpl);
202 $itemnum_cpl = $builder->build_sample_item(
204 biblionumber => $bibnum2,
205 library => $branch_1,
206 barcode => 'bug10272_CPL',
210 $itemnum_fpl = $builder->build_sample_item(
212 biblionumber => $bibnum2,
213 library => $branch_2,
214 barcode => 'bug10272_FPL',
219 # Ensure that priorities are numbered correcly when a hold is moved to waiting
221 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
224 branchcode => $branch_3,
225 borrowernumber => $requesters{$branch_3},
226 biblionumber => $bibnum2,
232 branchcode => $branch_2,
233 borrowernumber => $requesters{$branch_2},
234 biblionumber => $bibnum2,
240 branchcode => $branch_1,
241 borrowernumber => $requesters{$branch_1},
242 biblionumber => $bibnum2,
246 ModReserveAffect($itemnum_cpl, $requesters{$branch_3}, 0);
248 # Now it should have different priorities.
249 my $biblio = Koha::Biblios->find( $bibnum2 );
250 my $holds = $biblio->holds({}, { order_by => 'reserve_id' });;
251 is($holds->next->priority, 0, 'Item is correctly waiting');
252 is($holds->next->priority, 1, 'Item is correctly priority 1');
253 is($holds->next->priority, 2, 'Item is correctly priority 2');
255 my @reserves = Koha::Holds->search({ borrowernumber => $requesters{$branch_3} })->waiting->as_list;
256 is( @reserves, 1, 'GetWaiting got only the waiting reserve' );
257 is( $reserves[0]->borrowernumber(), $requesters{$branch_3}, 'GetWaiting got the reserve for the correct borrower' );
260 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
263 branchcode => $branch_3,
264 borrowernumber => $requesters{$branch_3},
265 biblionumber => $bibnum2,
271 branchcode => $branch_2,
272 borrowernumber => $requesters{$branch_2},
273 biblionumber => $bibnum2,
280 branchcode => $branch_1,
281 borrowernumber => $requesters{$branch_1},
282 biblionumber => $bibnum2,
287 # Ensure that the item's home library controls hold policy lookup
288 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
291 # Return the CPL item at FPL. The hold that should be triggered is
292 # the one placed by the CPL patron, as the other two patron's hold
293 # requests cannot be filled by that item per policy.
294 (undef, $messages, undef, undef) = AddReturn('bug10272_CPL', $branch_2);
295 is( $messages->{ResFound}->{borrowernumber},
296 $requesters{$branch_1},
297 'restrictive library\'s items only fill requests by own patrons (bug 10272)');
299 # Return the FPL item at FPL. The hold that should be triggered is
300 # the one placed by the RPL patron, as that patron is first in line
301 # and RPL imposes no restrictions on whose holds its items can fill.
303 # Ensure that the preference 'LocalHoldsPriority' is not set (Bug 15244):
304 t::lib::Mocks::mock_preference( 'LocalHoldsPriority', '' );
306 (undef, $messages, undef, undef) = AddReturn('bug10272_FPL', $branch_2);
307 is( $messages->{ResFound}->{borrowernumber},
308 $requesters{$branch_3},
309 'for generous library, its items fill first hold request in line (bug 10272)');
311 $biblio = Koha::Biblios->find( $biblionumber );
312 $holds = $biblio->holds;
313 is($holds->count, 1, "Only one reserves for this biblio");
314 $holds->next->reserve_id;
316 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
317 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
318 # Test 9761a: Add a reserve without date, CheckReserve should return it
319 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
322 branchcode => $branch_1,
323 borrowernumber => $requesters{$branch_1},
324 biblionumber => $bibnum,
328 ($status)=CheckReserves( $item );
329 is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead');
330 ($status)=CheckReserves( $item, 7 );
331 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
333 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
334 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
335 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
336 my $resdate= dt_from_string();
337 $resdate->add_duration(DateTime::Duration->new(days => 4));
338 my $reserve_id = AddReserve(
340 branchcode => $branch_1,
341 borrowernumber => $requesters{$branch_1},
342 biblionumber => $bibnum,
344 reservation_date => $resdate,
347 ($status)=CheckReserves( $item );
348 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
350 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
351 ($status)=CheckReserves( $item, 3 );
352 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
353 ($status)=CheckReserves( $item, 4 );
354 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
356 # Test 9761d: Check ResFound message of AddReturn for future hold
357 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
358 # In this test we do not need an issued item; it is just a 'checkin'
359 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
360 (my $doreturn, $messages)= AddReturn($testbarcode,$branch_1);
361 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
362 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 3);
363 ($doreturn, $messages)= AddReturn($testbarcode,$branch_1);
364 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
365 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 7);
366 ($doreturn, $messages)= AddReturn($testbarcode,$branch_1);
367 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
369 my $now_holder = $builder->build_object({ class => 'Koha::Patrons', value => {
370 branchcode => $branch_1,
372 my $now_reserve_id = AddReserve(
374 branchcode => $branch_1,
375 borrowernumber => $requesters{$branch_1},
376 biblionumber => $bibnum,
378 reservation_date => dt_from_string(),
382 ($status,$which_highest)=CheckReserves( $item, 3 );
383 is( $which_highest->{reserve_id}, $now_reserve_id, 'CheckReserves returns lower priority current reserve with insufficient lookahead');
384 ($status, $which_highest)=CheckReserves( $item, 4 );
385 is( $which_highest->{reserve_id}, $reserve_id, 'CheckReserves returns higher priority future reserve with sufficient lookahead');
386 ModReserve({ reserve_id => $now_reserve_id, rank => 'del', cancellation_reason => 'test reserve' });
389 # End of tests for bug 9761 (ConfirmFutureHolds)
392 # test marking a hold as captured
393 my $hold_notice_count = count_hold_print_messages();
394 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
395 my $new_count = count_hold_print_messages();
396 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
398 # test that duplicate notices aren't generated
399 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
400 $new_count = count_hold_print_messages();
401 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
403 # avoiding the not_same_branch error
404 t::lib::Mocks::mock_preference('IndependentBranches', 0);
405 $item = Koha::Items->find($item->itemnumber);
407 @{$item->safe_delete->messages}[0]->message,
409 'item that is captured to fill a hold cannot be deleted',
412 my $letter = ReserveSlip( { branchcode => $branch_1, reserve_id => $reserve_id } );
413 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
415 # Tests for bug 9788: Does Koha::Item->current_holds return a future wait?
416 # 9788a: current_holds does not return future next available hold
417 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
418 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
419 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
420 $resdate= dt_from_string();
421 $resdate->add_duration(DateTime::Duration->new(days => 2));
424 branchcode => $branch_1,
425 borrowernumber => $requesters{$branch_1},
426 biblionumber => $bibnum,
428 reservation_date => $resdate,
432 $holds = $item->current_holds;
433 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
434 my $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
435 is( $future_holds->count, 0, 'current_holds does not return a future next available hold');
436 # 9788b: current_holds does not return future item level hold
437 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
440 branchcode => $branch_1,
441 borrowernumber => $requesters{$branch_1},
442 biblionumber => $bibnum,
444 reservation_date => $resdate,
445 itemnumber => $item->itemnumber,
448 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
449 is( $future_holds->count, 0, 'current_holds does not return a future item level hold' );
450 # 9788c: current_holds returns future wait (confirmed future hold)
451 ModReserveAffect( $item->itemnumber, $requesters{$branch_1} , 0); #confirm hold
452 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
453 is( $future_holds->count, 1, 'current_holds returns a future wait (confirmed future hold)' );
454 # End of tests for bug 9788
456 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
457 # Tests for CalculatePriority (bug 8918)
458 my $p = C4::Reserves::CalculatePriority($bibnum2);
459 is($p, 4, 'CalculatePriority should now return priority 4');
462 branchcode => $branch_1,
463 borrowernumber => $requesters{'CPL2'},
464 biblionumber => $bibnum2,
468 $p = C4::Reserves::CalculatePriority($bibnum2);
469 is($p, 5, 'CalculatePriority should now return priority 5');
470 #some tests on bibnum
471 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
472 $p = C4::Reserves::CalculatePriority($bibnum);
473 is($p, 1, 'CalculatePriority should now return priority 1');
474 #add a new reserve and confirm it to waiting
477 branchcode => $branch_1,
478 borrowernumber => $requesters{$branch_1},
479 biblionumber => $bibnum,
481 itemnumber => $item->itemnumber,
484 $p = C4::Reserves::CalculatePriority($bibnum);
485 is($p, 2, 'CalculatePriority should now return priority 2');
486 ModReserveAffect( $item->itemnumber, $requesters{$branch_1} , 0);
487 $p = C4::Reserves::CalculatePriority($bibnum);
488 is($p, 1, 'CalculatePriority should now return priority 1');
489 #add another biblio hold, no resdate
492 branchcode => $branch_1,
493 borrowernumber => $requesters{'CPL2'},
494 biblionumber => $bibnum,
498 $p = C4::Reserves::CalculatePriority($bibnum);
499 is($p, 2, 'CalculatePriority should now return priority 2');
500 #add another future hold
501 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
502 $resdate= dt_from_string();
503 $resdate->add_duration(DateTime::Duration->new(days => 1));
506 branchcode => $branch_1,
507 borrowernumber => $requesters{'CPL2'},
508 biblionumber => $bibnum,
510 reservation_date => $resdate,
513 $p = C4::Reserves::CalculatePriority($bibnum);
514 is($p, 2, 'CalculatePriority should now still return priority 2');
515 #calc priority with future resdate
516 $p = C4::Reserves::CalculatePriority($bibnum, $resdate);
517 is($p, 3, 'CalculatePriority should now return priority 3');
518 # End of tests for bug 8918
520 # regression test for bug 12630
521 # Now there are 2 reserves on $bibnum
522 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
523 my $bor_tmp_1 = $builder->build_object({ class => 'Koha::Patrons',value =>{
524 firstname => 'my firstname tmp 1',
525 surname => 'my surname tmp 1',
529 my $bor_tmp_2 = $builder->build_object({ class => 'Koha::Patrons',value =>{
530 firstname => 'my firstname tmp 2',
531 surname => 'my surname tmp 2',
535 my $borrowernumber_tmp_1 = $bor_tmp_1->borrowernumber;
536 my $borrowernumber_tmp_2 = $bor_tmp_2->borrowernumber;
537 my $date_in_future = dt_from_string();
538 $date_in_future = $date_in_future->add_duration(DateTime::Duration->new(days => 1));
541 borrowernumber => $borrowernumber_tmp_1,
542 biblionumber => $bibnum,
544 reservation_date => $date_in_future
548 borrowernumber => $borrowernumber_tmp_2,
549 biblionumber => $bibnum,
551 reservation_date => $date_in_future
553 my @r1 = Koha::Holds->search({ borrowernumber => $borrowernumber_tmp_1 })->as_list;
554 my @r2 = Koha::Holds->search({ borrowernumber => $borrowernumber_tmp_2 })->as_list;
555 is( $r1[0]->priority, 3, 'priority for hold in future should be correct');
556 is( $r2[0]->priority, 4, 'priority for hold not in future should be correct');
557 # end of tests for bug 12630
559 # Tests for cancel reserves by users from OPAC.
560 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
563 branchcode => $branch_1,
564 borrowernumber => $requesters{$branch_1},
565 biblionumber => $bibnum,
569 my (undef, $canres, undef) = CheckReserves( $item );
571 is( CanReserveBeCanceledFromOpac(), undef,
572 'CanReserveBeCanceledFromOpac should return undef if called without any parameter'
575 CanReserveBeCanceledFromOpac( $canres->{resserve_id} ),
577 'CanReserveBeCanceledFromOpac should return undef if called without the reserve_id'
580 CanReserveBeCanceledFromOpac( undef, $requesters{CPL} ),
582 'CanReserveBeCanceledFromOpac should return undef if called without borrowernumber'
585 my $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
586 is($cancancel, 1, 'Can user cancel its own reserve');
588 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_2});
589 is($cancancel, 0, 'Other user cant cancel reserve');
591 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 1);
592 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
593 is($cancancel, 0, 'Reserve in transfer status cant be canceled');
595 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
596 is( CanReserveBeCanceledFromOpac($canres->{resserve_id}, $requesters{$branch_1}), undef,
597 'Cannot cancel a deleted hold' );
601 branchcode => $branch_1,
602 borrowernumber => $requesters{$branch_1},
603 biblionumber => $bibnum,
607 (undef, $canres, undef) = CheckReserves( $item );
609 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
610 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
611 is($cancancel, 0, 'Reserve in waiting status cant be canceled');
613 # End of tests for bug 12876
616 ####### Testing Bug 13113 - Prevent juvenile/children from reserving ageRestricted material >>>
619 t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' );
621 #Reserving an not-agerestricted Biblio by a Borrower with no dateofbirth is tested previously.
623 #Set the ageRestriction for the Biblio
624 $biblio = Koha::Biblios->find($bibnum);
625 my $record = $biblio->metadata->record;
626 my ( $ageres_tagid, $ageres_subfieldid ) = GetMarcFromKohaField( "biblioitems.agerestriction" );
627 $record->append_fields( MARC::Field->new($ageres_tagid, '', '', $ageres_subfieldid => 'PEGI 16') );
628 C4::Biblio::ModBiblio( $record, $bibnum, $frameworkcode );
630 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'OK', "Reserving an ageRestricted Biblio without a borrower dateofbirth succeeds" );
632 #Set the dateofbirth for the Borrower making them "too young".
633 $borrower->{dateofbirth} = DateTime->now->add( years => -15 );
634 Koha::Patrons->find( $borrowernumber )->set({ dateofbirth => $borrower->{dateofbirth} })->store;
636 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'ageRestricted', "Reserving a 'PEGI 16' Biblio by a 15 year old borrower fails");
638 #Set the dateofbirth for the Borrower making them "too old".
639 $borrower->{dateofbirth} = DateTime->now->add( years => -30 );
640 Koha::Patrons->find( $borrowernumber )->set({ dateofbirth => $borrower->{dateofbirth} })->store;
642 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'OK', "Reserving a 'PEGI 16' Biblio by a 30 year old borrower succeeds");
644 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblio_with_no_item->biblionumber)->{status} , '', "Biblio with no item. Status is empty");
646 ####### EO Bug 13113 <<<
649 ok( C4::Reserves::IsAvailableForItemLevelRequest($item, $patron), "Reserving a book on item level" );
651 my $pickup_branch = $builder->build({ source => 'Branch' })->{ branchcode };
652 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' );
653 t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' );
654 my $limit = Koha::Item::Transfer::Limit->new(
656 toBranch => $pickup_branch,
657 fromBranch => $item->holdingbranch,
658 itemtype => $item->effective_itemtype,
661 is( C4::Reserves::IsAvailableForItemLevelRequest($item, $patron, $pickup_branch), 0, "Item level request not available due to transfer limit" );
662 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' );
664 my $categorycode = $borrower->{categorycode};
665 my $holdingbranch = $item->{holdingbranch};
666 Koha::CirculationRules->set_rules(
668 categorycode => $categorycode,
669 itemtype => $item->effective_itemtype,
670 branchcode => $holdingbranch,
677 # tests for MoveReserve in relation to ConfirmFutureHolds (BZ 14526)
678 # hold from A pos 1, today, no fut holds: MoveReserve should fill it
679 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
680 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
681 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
684 branchcode => $branch_1,
685 borrowernumber => $borrowernumber,
686 biblionumber => $bibnum,
690 MoveReserve( $item->itemnumber, $borrowernumber );
691 ($status)=CheckReserves( $item );
692 is( $status, '', 'MoveReserve filled hold');
693 # hold from A waiting, today, no fut holds: MoveReserve should fill it
694 my $other_item = $builder->build_sample_item({ biblionumber => $biblio->id });
697 branchcode => $branch_1,
698 borrowernumber => $borrowernumber,
699 biblionumber => $bibnum,
702 itemnumber => $other_item->id,
705 MoveReserve( $item->itemnumber, $borrowernumber );
706 ($status)=CheckReserves( $item );
707 is( $status, '', 'MoveReserve filled waiting hold');
708 # hold from A pos 1, tomorrow, no fut holds: not filled
709 $resdate= dt_from_string();
710 $resdate->add_duration(DateTime::Duration->new(days => 1));
713 branchcode => $branch_1,
714 borrowernumber => $borrowernumber,
715 biblionumber => $bibnum,
717 reservation_date => $resdate,
720 MoveReserve( $item->itemnumber, $borrowernumber );
721 ($status)=CheckReserves( $item, 1 );
722 is( $status, 'Reserved', 'MoveReserve did not fill future hold');
723 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
724 # hold from A pos 1, tomorrow, fut holds=2: MoveReserve should fill it
725 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
728 branchcode => $branch_1,
729 borrowernumber => $borrowernumber,
730 biblionumber => $bibnum,
732 reservation_date => $resdate,
735 MoveReserve( $item->itemnumber, $borrowernumber );
736 ($status)=CheckReserves( $item, undef, 2 );
737 is( $status, '', 'MoveReserve filled future hold now');
738 # hold from A waiting, tomorrow, fut holds=2: MoveReserve should fill it
741 branchcode => $branch_1,
742 borrowernumber => $borrowernumber,
743 biblionumber => $bibnum,
745 reservation_date => $resdate,
748 MoveReserve( $item->itemnumber, $borrowernumber );
749 ($status)=CheckReserves( $item, undef, 2 );
750 is( $status, '', 'MoveReserve filled future waiting hold now');
751 # hold from A pos 1, today+3, fut holds=2: MoveReserve should not fill it
752 $resdate= dt_from_string();
753 $resdate->add_duration(DateTime::Duration->new(days => 3));
756 branchcode => $branch_1,
757 borrowernumber => $borrowernumber,
758 biblionumber => $bibnum,
760 reservation_date => $resdate,
763 MoveReserve( $item->itemnumber, $borrowernumber );
764 ($status)=CheckReserves( $item, 3 );
765 is( $status, 'Reserved', 'MoveReserve did not fill future hold of 3 days');
766 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
768 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
769 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
770 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
772 subtest '_koha_notify_reserve() tests' => sub {
776 my $branch = $builder->build_object({
777 class => 'Koha::Libraries',
779 branchemail => 'branch@e.mail',
780 branchreplyto => 'branch@reply.to',
784 my $item = $builder->build_sample_item({
785 homebranch => $branch->branchcode,
786 holdingbranch => $branch->branchcode
789 my $wants_hold_and_email = {
795 letter_code => 'HOLD'
798 my $mp = Test::MockModule->new( 'C4::Members::Messaging' );
800 $mp->mock("GetMessagingPreferences",$wants_hold_and_email);
802 $dbh->do('DELETE FROM letter');
804 my $email_hold_notice = $builder->build({
807 message_transport_type => 'email',
810 module => 'reserves',
815 my $sms_hold_notice = $builder->build({
818 message_transport_type => 'sms',
821 module => 'reserves',
826 my $hold_borrower = $builder->build({
827 source => 'Borrower',
829 smsalertnumber=>'5555555555',
832 })->{borrowernumber};
834 C4::Reserves::AddReserve(
836 branchcode => $item->homebranch,
837 borrowernumber => $hold_borrower,
838 biblionumber => $item->biblionumber,
842 ModReserveAffect($item->itemnumber, $hold_borrower, 0);
843 my $sms_message_address = $schema->resultset('MessageQueue')->search({
844 letter_code => 'HOLD',
845 message_transport_type => 'sms',
846 borrowernumber => $hold_borrower,
847 })->next()->to_address();
848 is($sms_message_address, undef ,"We should not populate the sms message with the sms number, sending will do so");
850 my $email = $schema->resultset('MessageQueue')->search({
851 letter_code => 'HOLD',
852 message_transport_type => 'email',
853 borrowernumber => $hold_borrower,
855 my $email_to_address = $email->to_address();
856 is($email_to_address, undef ,"We should not populate the hold message with the email address, sending will do so");
857 my $email_from_address = $email->from_address();
858 is($email_from_address,'branch@e.mail',"Library's from address is used for sending");
862 subtest 'ReservesNeedReturns' => sub {
865 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
867 homebranch => $library->branchcode,
868 holdingbranch => $library->branchcode,
870 my $item = $builder->build_sample_item($item_info);
871 my $patron = $builder->build_object(
873 class => 'Koha::Patrons',
874 value => { branchcode => $library->branchcode, }
877 my $patron_2 = $builder->build_object(
879 class => 'Koha::Patrons',
880 value => { branchcode => $library->branchcode, }
886 t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Test with feature disabled
887 my $hold = place_item_hold( $patron, $item, $library, $priority );
888 is( $hold->priority, $priority, 'If ReservesNeedReturns is 1, priority must not have been set to changed' );
889 is( $hold->found, undef, 'If ReservesNeedReturns is 1, found must not have been set waiting' );
892 t::lib::Mocks::mock_preference('ReservesNeedReturns', 0); # '0' means 'Automatically mark a hold as found and waiting'
893 $hold = place_item_hold( $patron, $item, $library, $priority );
894 is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
895 is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
898 $item->onloan('2010-01-01')->store;
899 $hold = place_item_hold( $patron, $item, $library, $priority );
900 is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item onloan priority must be set to 1' );
903 t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 0); # '0' means damaged holds not allowed
904 $item->onloan(undef)->damaged(1)->store;
905 $hold = place_item_hold( $patron, $item, $library, $priority );
906 is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item damaged and not allowed holds on damaged items priority must be set to 1' );
908 t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 1); # '0' means damaged holds not allowed
909 $hold = place_item_hold( $patron, $item, $library, $priority );
910 is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and damaged holds allowed, priority must have been set to 0' );
911 is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and damaged holds allowed, found must have been set waiting' );
914 my $hold_1 = place_item_hold( $patron, $item, $library, $priority );
915 is( $hold_1->found, 'W', 'First hold on item is set to waiting with ReservesNeedReturns set to 0' );
916 is( $hold_1->priority, 0, 'First hold on item is set to waiting with ReservesNeedReturns set to 0' );
917 $hold = place_item_hold( $patron_2, $item, $library, $priority );
918 is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item already on hold priority must be set to 1' );
922 my $transfer = $builder->build_object({
923 class => "Koha::Item::Transfers",
925 itemnumber => $item->itemnumber,
926 datearrived => undef,
927 datecancelled => undef
930 $item->damaged(0)->store;
931 $hold = place_item_hold( $patron, $item, $library, $priority );
932 is( $hold->found, undef, 'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
933 is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
937 $hold = place_item_hold( $patron, $item, $library, $priority );
938 is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
939 is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
940 $hold_1 = place_item_hold( $patron, $item, $library, $priority );
941 is( $hold_1->priority, 1, 'If ReservesNeedReturns is 0 but item has a hold priority is 1' );
942 $hold_1->suspend(1)->store; # We suspend the hold
943 $hold->delete; # Delete the waiting hold
944 $hold = place_item_hold( $patron, $item, $library, $priority );
945 is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and other hold(s) suspended, priority must have been set to 0' );
946 is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and other hold(s) suspended, found must have been set waiting' );
951 t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Don't affect other tests
954 subtest 'ChargeReserveFee tests' => sub {
958 my $library = $builder->build_object({ class => 'Koha::Libraries' });
959 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
962 my $title = 'A title';
964 my $context = Test::MockModule->new('C4::Context');
965 $context->mock( userenv => { branch => $library->id } );
967 my $line = C4::Reserves::ChargeReserveFee( $patron->id, $fee, $title );
969 is( ref($line), 'Koha::Account::Line' , 'Returns a Koha::Account::Line object');
970 ok( $line->is_debit, 'Generates a debit line' );
971 is( $line->debit_type_code, 'RESERVE' , 'generates RESERVE debit_type');
972 is( $line->borrowernumber, $patron->id , 'generated line belongs to the passed patron');
973 is( $line->amount, $fee , 'amount set correctly');
974 is( $line->amountoutstanding, $fee , 'amountoutstanding set correctly');
975 is( $line->description, "$title" , 'description is title of reserved item');
976 is( $line->branchcode, $library->id , "Library id is picked from userenv and stored correctly" );
979 subtest 'reserves.item_level_hold' => sub {
982 my $item = $builder->build_sample_item;
983 my $patron = $builder->build_object(
985 class => 'Koha::Patrons',
986 value => { branchcode => $item->homebranch }
990 subtest 'item level hold' => sub {
992 my $reserve_id = AddReserve(
994 branchcode => $item->homebranch,
995 borrowernumber => $patron->borrowernumber,
996 biblionumber => $item->biblionumber,
998 itemnumber => $item->itemnumber,
1002 my $hold = Koha::Holds->find($reserve_id);
1003 is( $hold->item_level_hold, 1, 'item_level_hold should be set when AddReserve is called with a specific item' );
1006 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
1008 my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1009 $mock->mock( 'enqueue', sub {
1010 my ( $self, $args ) = @_;
1012 $args->{biblio_ids},
1013 [ $hold->biblionumber ],
1014 "AlterPriority triggers a holds queue update for the related biblio"
1018 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1019 t::lib::Mocks::mock_preference( 'HoldsLog', 1 );
1021 # Revert the waiting status
1022 C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1024 $hold = Koha::Holds->find($reserve_id);
1027 $hold->itemnumber, $item->itemnumber,
1028 'Itemnumber should not be removed when the waiting status is revert'
1032 Koha::ActionLogs->search( { module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id } )->next;
1033 my $expected = sprintf q{'timestamp' => '%s'}, $hold->timestamp;
1034 like( $log->info, qr{$expected}, 'Timestamp logged is the current one' );
1036 Koha::ActionLogs->search( { module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id } )->count;
1038 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1039 t::lib::Mocks::mock_preference( 'HoldsLog', 0 );
1043 # Revert the waiting status, RealTimeHoldsQueue => shouldn't add a test
1044 C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1046 $hold->delete; # cleanup
1048 my $log_count_after =
1049 Koha::ActionLogs->search( { module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id } )->count;
1050 is( $log_count, $log_count_after, "No logging is added for RevertWaitingStatus when HoldsLog is disabled" );
1054 subtest 'biblio level hold' => sub {
1056 my $reserve_id = AddReserve(
1058 branchcode => $item->homebranch,
1059 borrowernumber => $patron->borrowernumber,
1060 biblionumber => $item->biblionumber,
1065 my $hold = Koha::Holds->find($reserve_id);
1066 is( $hold->item_level_hold, 0, 'item_level_hold should not be set when AddReserve is called without a specific item' );
1069 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
1071 $hold = Koha::Holds->find($reserve_id);
1072 is( $hold->itemnumber, $item->itemnumber, 'Itemnumber should be set on hold confirmation' );
1074 # Revert the waiting status
1075 C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1077 $hold = Koha::Holds->find($reserve_id);
1078 is( $hold->itemnumber, undef, 'Itemnumber should be removed when the waiting status is revert' );
1085 subtest 'MoveReserve additional test' => sub {
1089 # Create the items and patrons we need
1090 my $biblio = $builder->build_sample_biblio();
1091 my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
1092 my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1093 my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber, notforloan => 0, itype => $itype->itemtype });
1094 my $patron_1 = $builder->build_object({ class => "Koha::Patrons" });
1095 my $patron_2 = $builder->build_object({ class => "Koha::Patrons" });
1097 # Place a hold on the title for both patrons
1098 my $reserve_1 = AddReserve(
1100 branchcode => $item_1->homebranch,
1101 borrowernumber => $patron_1->borrowernumber,
1102 biblionumber => $biblio->biblionumber,
1104 itemnumber => $item_1->itemnumber,
1107 my $reserve_2 = AddReserve(
1109 branchcode => $item_2->homebranch,
1110 borrowernumber => $patron_2->borrowernumber,
1111 biblionumber => $biblio->biblionumber,
1113 itemnumber => $item_1->itemnumber,
1116 is($patron_1->holds->next()->reserve_id, $reserve_1, "The 1st patron has a hold");
1117 is($patron_2->holds->next()->reserve_id, $reserve_2, "The 2nd patron has a hold");
1119 # Fake the holds queue
1120 $dbh->do(q{INSERT INTO hold_fill_targets VALUES (?, ?, ?, ?, ?,?)},undef,($patron_1->borrowernumber,$biblio->biblionumber,$item_1->itemnumber,$item_1->homebranch,0,$reserve_1));
1122 # The 2nd hold should be filed even if the item is preselected for the first hold
1123 MoveReserve($item_1->itemnumber,$patron_2->borrowernumber);
1124 is($patron_2->holds->count, 0, "The 2nd patrons no longer has a hold");
1125 is($patron_2->old_holds->next()->reserve_id, $reserve_2, "The 2nd patrons hold was filled and moved to old holds");
1129 subtest 'RevertWaitingStatus' => sub {
1133 # Create the items and patrons we need
1134 my $biblio = $builder->build_sample_biblio();
1135 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1136 my $itype = $builder->build_object(
1137 { class => "Koha::ItemTypes", value => { notforloan => 0 } } );
1138 my $item_1 = $builder->build_sample_item(
1140 biblionumber => $biblio->biblionumber,
1141 itype => $itype->itemtype,
1142 library => $library->branchcode
1145 my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1146 my $patron_2 = $builder->build_object( { class => "Koha::Patrons" } );
1147 my $patron_3 = $builder->build_object( { class => "Koha::Patrons" } );
1148 my $patron_4 = $builder->build_object( { class => "Koha::Patrons" } );
1150 # Place a hold on the title for both patrons
1152 my $hold_1 = place_item_hold( $patron_1, $item_1, $library, $priority );
1153 my $hold_2 = place_item_hold( $patron_2, $item_1, $library, $priority );
1154 my $hold_3 = place_item_hold( $patron_3, $item_1, $library, $priority );
1155 my $hold_4 = place_item_hold( $patron_4, $item_1, $library, $priority );
1157 $hold_1->set_waiting;
1158 AddIssue( $patron_3, $item_1->barcode, undef, 'revert' );
1160 my $holds = $biblio->holds;
1161 is( $holds->count, 3, 'One hold has been deleted' );
1164 $holds->next->priority, $holds->next->priority,
1165 $holds->next->priority
1168 'priorities have been reordered'
1172 subtest 'CheckReserves additional tests' => sub {
1176 my $item = $builder->build_sample_item;
1177 my $reserve1 = $builder->build_object(
1179 class => "Koha::Holds",
1183 itemnumber => undef,
1184 biblionumber => $item->biblionumber,
1185 waitingdate => undef,
1186 cancellationdate => undef,
1187 item_level_hold => 0,
1188 lowestPriority => 0,
1189 expirationdate => undef,
1190 suspend_until => undef,
1196 my $reserve2 = $builder->build_object(
1198 class => "Koha::Holds",
1202 biblionumber => $item->biblionumber,
1203 borrowernumber => $reserve1->borrowernumber,
1204 itemnumber => undef,
1205 waitingdate => undef,
1206 cancellationdate => undef,
1207 item_level_hold => 0,
1208 lowestPriority => 0,
1209 expirationdate => undef,
1210 suspend_until => undef,
1217 my $tmp_holdsqueue = $builder->build(
1219 source => 'TmpHoldsqueue',
1221 borrowernumber => $reserve1->borrowernumber,
1222 biblionumber => $reserve1->biblionumber,
1226 my $fill_target = $builder->build(
1228 source => 'HoldFillTarget',
1230 borrowernumber => $reserve1->borrowernumber,
1231 biblionumber => $reserve1->biblionumber,
1232 itemnumber => $item->itemnumber,
1233 item_level_request => 0,
1238 ModReserveAffect( $item->itemnumber, $reserve1->borrowernumber, 1,
1239 $reserve1->reserve_id );
1240 my ( $status, $matched_reserve, $possible_reserves ) =
1241 CheckReserves( $item );
1243 is( $status, 'Transferred', "We found a reserve" );
1244 is( $matched_reserve->{reserve_id},
1245 $reserve1->reserve_id, "We got the Transit reserve" );
1246 is( scalar @$possible_reserves, 2, 'We do get both reserves' );
1248 my $patron_B = $builder->build_object({ class => "Koha::Patrons" });
1249 my $item_A = $builder->build_sample_item;
1250 my $item_B = $builder->build_sample_item({
1251 homebranch => $patron_B->branchcode,
1252 biblionumber => $item_A->biblionumber,
1253 itype => $item_A->itype
1255 Koha::CirculationRules->set_rules(
1257 branchcode => undef,
1258 categorycode => undef,
1259 itemtype => $item_A->itype,
1261 reservesallowed => 25,
1262 holds_per_record => 1,
1266 Koha::CirculationRules->set_rule({
1267 branchcode => undef,
1268 itemtype => $item_A->itype,
1269 rule_name => 'holdallowed',
1270 rule_value => 'from_home_library'
1272 my $reserve_id = AddReserve(
1274 branchcode => $patron_B->branchcode,
1275 borrowernumber => $patron_B->borrowernumber,
1276 biblionumber => $item_A->biblionumber,
1278 itemnumber => undef,
1282 ok( $reserve_id, "We can place a record level hold because one item is owned by patron's home library");
1283 t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary');
1284 ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1285 is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch");
1286 Koha::CirculationRules->set_rule({
1287 branchcode => $item_A->homebranch,
1288 itemtype => $item_A->itype,
1289 rule_name => 'holdallowed',
1290 rule_value => 'from_any_library'
1292 ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1293 is( $status, "Reserved", "We fill the hold with item A because item's branch rule says allow any");
1296 # Changing the control branch should change only the rule we get
1297 t::lib::Mocks::mock_preference('ReservesControlBranch', 'PatronLibrary');
1298 ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1299 is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch");
1300 Koha::CirculationRules->set_rule({
1301 branchcode => $patron_B->branchcode,
1302 itemtype => $item_A->itype,
1303 rule_name => 'holdallowed',
1304 rule_value => 'from_any_library'
1306 ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1307 is( $status, "Reserved", "We fill the hold with item A because patron's branch rule says allow any");
1311 subtest 'AllowHoldOnPatronPossession test' => sub {
1315 # Create the items and patrons we need
1316 my $biblio = $builder->build_sample_biblio();
1317 my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
1318 my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1319 my $patron = $builder->build_object({ class => "Koha::Patrons",
1320 value => { branchcode => $item->homebranch }});
1322 C4::Circulation::AddIssue($patron,
1324 t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 0);
1326 is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1327 $item->biblionumber)->{status},
1328 'alreadypossession',
1329 'Patron cannot place hold on a book loaned to itself');
1331 is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status},
1332 'alreadypossession',
1333 'Patron cannot place hold on an item loaned to itself');
1335 t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 1);
1337 is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1338 $item->biblionumber)->{status},
1340 'Patron can place hold on a book loaned to itself');
1342 is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status},
1344 'Patron can place hold on an item loaned to itself');
1347 subtest 'MergeHolds' => sub {
1351 my $biblio_1 = $builder->build_sample_biblio();
1352 my $biblio_2 = $builder->build_sample_biblio();
1353 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1354 my $itype = $builder->build_object(
1355 { class => "Koha::ItemTypes", value => { notforloan => 0 } } );
1356 my $item_1 = $builder->build_sample_item(
1358 biblionumber => $biblio_1->biblionumber,
1359 itype => $itype->itemtype,
1360 library => $library->branchcode
1363 my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1365 # Place a hold on $biblio_1
1367 place_item_hold( $patron_1, $item_1, $library, $priority );
1369 # Move and make sure hold is now on $biblio_2
1370 C4::Reserves::MergeHolds($dbh, $biblio_2->biblionumber, $biblio_1->biblionumber);
1371 is( $biblio_2->holds->count, 1, 'Hold has been transferred' );
1374 subtest 'ModReserveAffect logging' => sub {
1378 my $item = $builder->build_sample_item;
1379 my $patron = $builder->build_object(
1381 class => "Koha::Patrons",
1382 value => { branchcode => $item->homebranch }
1386 t::lib::Mocks::mock_userenv({ patron => $patron });
1387 t::lib::Mocks::mock_preference('HoldsLog', 1);
1389 my $reserve_id = AddReserve(
1391 branchcode => $item->homebranch,
1392 borrowernumber => $patron->borrowernumber,
1393 biblionumber => $item->biblionumber,
1395 itemnumber => $item->itemnumber,
1399 my $hold = Koha::Holds->find($reserve_id);
1400 my $previous_timestamp = '1970-01-01 12:34:56';
1401 $hold->timestamp($previous_timestamp)->store;
1403 $hold = Koha::Holds->find($reserve_id);
1404 is( $hold->timestamp, $previous_timestamp, 'Make sure the previous timestamp has been used' );
1407 my $reserve_mock = Test::MockModule->new('C4::Reserves');
1408 $reserve_mock->mock( '_koha_notify_reserve', undef );
1411 ModReserveAffect( $item->itemnumber, $patron->borrowernumber );
1413 $hold->discard_changes;
1414 ok( $hold->is_waiting, 'Hold has been set waiting' );
1415 isnt( $hold->timestamp, $previous_timestamp, 'The timestamp has been modified' );
1417 my $log = Koha::ActionLogs->search({ module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id })->next;
1418 my $expected = sprintf q{'timestamp' => '%s'}, $hold->timestamp;
1419 like( $log->info, qr{$expected}, 'Timestamp logged is the current one' );
1422 sub count_hold_print_messages {
1423 my $message_count = $dbh->selectall_arrayref(q{
1426 WHERE letter_code = 'HOLD'
1427 AND message_transport_type = 'print'
1429 return $message_count->[0]->[0];
1432 sub place_item_hold {
1433 my ($patron,$item,$library,$priority) = @_;
1435 my $hold_id = C4::Reserves::AddReserve(
1437 branchcode => $library->branchcode,
1438 borrowernumber => $patron->borrowernumber,
1439 biblionumber => $item->biblionumber,
1440 priority => $priority,
1441 title => "title for fee",
1442 itemnumber => $item->itemnumber,
1446 my $hold = Koha::Holds->find($hold_id);
1450 # we reached the finish
1451 $schema->storage->txn_rollback();
1453 subtest 'IsAvailableForItemLevelRequest() tests' => sub {
1457 $schema->storage->txn_begin;
1459 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1461 my $item_type = undef;
1463 my $item_mock = Test::MockModule->new('Koha::Item');
1464 $item_mock->mock( 'effective_itemtype', sub { return $item_type; } );
1466 my $item = $builder->build_sample_item;
1469 !C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ),
1470 "Item not available for item-level hold because no effective item type"
1473 # Weird use case to highlight issue
1475 Koha::ItemTypes->search( { itemtype => $item_type } )->delete;
1476 my $itemtype = $builder->build_object(
1478 class => 'Koha::ItemTypes',
1479 value => { itemtype => $item_type }
1483 C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ),
1484 "Item not available for item-level hold because no effective item type"
1487 Koha::CirculationRules->set_rules(
1489 categorycode => '*',
1497 my $item_1 = $builder->build_sample_item( { notforloan => -1 } );
1499 C4::Reserves::IsAvailableForItemLevelRequest( $item_1, $patron ),
1500 "We can placing hold on item with negative not for loan values when 'On shelf holds allowed' is set to 'If any unavailable'"
1502 $schema->storage->txn_rollback;
1505 subtest 'AddReserve() tests' => sub {
1509 $schema->storage->txn_begin;
1511 t::lib::Mocks::mock_preference( 'TrackLastPatronActivityTriggers', 'hold' );
1513 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1514 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { lastseen => undef } } );
1515 my $biblio = $builder->build_sample_biblio;
1517 my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1518 $mock->mock( 'enqueue', sub {
1519 my ( $self, $args ) = @_;
1521 $args->{biblio_ids},
1523 "AddReserve triggers a holds queue update for the related biblio"
1527 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1531 branchcode => $library->branchcode,
1532 borrowernumber => $patron->id,
1533 biblionumber => $biblio->id,
1537 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1541 branchcode => $library->branchcode,
1542 borrowernumber => $patron->id,
1543 biblionumber => $biblio->id,
1547 $patron->discard_changes;
1548 isnt( $patron->lastseen, undef, "Patron activity tracked when hold is a valid trigger" );
1550 $schema->storage->txn_rollback;
1553 subtest 'AlterPriorty() tests' => sub {
1557 $schema->storage->txn_begin;
1559 my $library = $builder->build_object({ class => 'Koha::Libraries' });
1560 my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' });
1561 my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
1562 my $patron_3 = $builder->build_object({ class => 'Koha::Patrons' });
1563 my $biblio = $builder->build_sample_biblio;
1565 my $reserve_id = AddReserve(
1567 branchcode => $library->branchcode,
1568 borrowernumber => $patron_1->id,
1569 biblionumber => $biblio->id,
1574 branchcode => $library->branchcode,
1575 borrowernumber => $patron_2->id,
1576 biblionumber => $biblio->id,
1581 branchcode => $library->branchcode,
1582 borrowernumber => $patron_3->id,
1583 biblionumber => $biblio->id,
1587 my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1588 $mock->mock( 'enqueue', sub {
1589 my ( $self, $args ) = @_;
1591 $args->{biblio_ids},
1593 "AlterPriority triggers a holds queue update for the related biblio"
1597 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1599 AlterPriority( "bottom", $reserve_id, 1, 2, 1, 3 );
1601 my $hold = Koha::Holds->find($reserve_id);
1603 is($hold->priority,3,'Successfully altered priority to bottom');
1605 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1607 AlterPriority( "bottom", $reserve_id, 1, 2, 1, 3 );
1609 $schema->storage->txn_rollback;
1612 subtest 'CanBookBeReserved() tests' => sub {
1616 $schema->storage->txn_begin;
1618 my $library = $builder->build_object(
1619 { class => 'Koha::Libraries', value => { pickup_location => 1 } } );
1620 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1621 my $itype = $builder->build_object( { class => 'Koha::ItemTypes' } );
1623 my $biblio = $builder->build_sample_biblio();
1624 my $item_1 = $builder->build_sample_item(
1625 { biblionumber => $biblio->id, itype => $itype->id } );
1626 my $item_2 = $builder->build_sample_item(
1627 { biblionumber => $biblio->id, itype => $itype->id } );
1629 Koha::CirculationRules->delete;
1630 Koha::CirculationRules->set_rules(
1632 branchcode => undef,
1633 categorycode => undef,
1636 holds_per_record => 100,
1640 Koha::CirculationRules->set_rules(
1642 branchcode => undef,
1643 categorycode => undef,
1644 itemtype => $itype->id,
1646 reservesallowed => 2,
1651 C4::Reserves::AddReserve(
1653 branchcode => $library->id,
1654 borrowernumber => $patron->id,
1655 biblionumber => $biblio->id,
1656 title => $biblio->title,
1657 itemnumber => $item_1->id
1661 ## Limit on item type is 2, only one hold, success tests
1663 my $res = CanBookBeReserved( $patron->id, $biblio->id, $library->id,
1664 { itemtype => $itype->id } );
1665 is_deeply( $res, { status => 'OK' },
1666 'Holds on itemtype limit not reached' );
1668 # Add a second hold, biblio-level and item type-constrained
1669 C4::Reserves::AddReserve(
1671 branchcode => $library->id,
1672 borrowernumber => $patron->id,
1673 biblionumber => $biblio->id,
1674 title => $biblio->title,
1675 itemtype => $itype->id,
1679 ## Limit on item type is 2, two holds, one of them biblio-level/item type-constrained
1681 $res = CanBookBeReserved( $patron->id, $biblio->id, $library->id,
1682 { itemtype => $itype->id } );
1683 is_deeply( $res, { status => '' }, 'Holds on itemtype limit reached' );
1685 $schema->storage->txn_rollback;
1688 subtest 'CanItemBeReserved() tests' => sub {
1692 $schema->storage->txn_begin;
1694 my $library = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } );
1695 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1696 my $itype = $builder->build_object( { class => 'Koha::ItemTypes' } );
1698 my $biblio = $builder->build_sample_biblio();
1699 my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->id, itype => $itype->id });
1700 my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->id, itype => $itype->id });
1702 Koha::CirculationRules->delete;
1703 Koha::CirculationRules->set_rules(
1704 { branchcode => undef,
1705 categorycode => undef,
1708 holds_per_record => 100,
1712 Koha::CirculationRules->set_rules(
1713 { branchcode => undef,
1714 categorycode => undef,
1715 itemtype => $itype->id,
1717 reservesallowed => 2,
1722 C4::Reserves::AddReserve(
1724 branchcode => $library->id,
1725 borrowernumber => $patron->id,
1726 biblionumber => $biblio->id,
1727 title => $biblio->title,
1728 itemnumber => $item_1->id
1732 ## Limit on item type is 2, only one hold, success tests
1734 my $res = CanItemBeReserved( $patron, $item_2, $library->id );
1735 is_deeply( $res, { status => 'OK' }, 'Holds on itemtype limit not reached' );
1737 # Add a second hold, biblio-level and item type-constrained
1738 C4::Reserves::AddReserve(
1740 branchcode => $library->id,
1741 borrowernumber => $patron->id,
1742 biblionumber => $biblio->id,
1743 title => $biblio->title,
1744 itemtype => $itype->id,
1748 ## Limit on item type is 2, two holds, one of them biblio-level/item type-constrained
1750 $res = CanItemBeReserved( $patron, $item_2, $library->id );
1751 is_deeply( $res, { status => 'tooManyReserves', limit => 2 }, 'Holds on itemtype limit reached' );
1753 $schema->storage->txn_rollback;
1756 subtest 'DefaultHoldExpiration tests' => sub {
1758 $schema->storage->txn_begin;
1760 t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdate', 1 );
1761 t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdatePeriod', 365 );
1762 t::lib::Mocks::mock_preference( 'DefaultHoldExpirationUnitOfTime', 'days;' );
1764 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1765 my $item = $builder->build_sample_item();
1767 my $reserve_id = AddReserve({
1768 branchcode => $item->homebranch,
1769 borrowernumber => $patron->id,
1770 biblionumber => $item->biblionumber,
1773 my $today = dt_from_string();
1774 my $hold = Koha::Holds->find( $reserve_id );
1776 is( $hold->reservedate, $today->ymd, "Hold created today" );
1777 is( $hold->expirationdate, $today->add( days => 365)->ymd, "Reserve date set 1 year from today" );
1779 $schema->txn_rollback;
1782 subtest '_Findgroupreserves' => sub {
1784 $schema->storage->txn_begin;
1786 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } );
1787 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } );
1788 my $item = $builder->build_sample_item();
1789 my $item_2 = $builder->build_sample_item( { biblionumber => $item->biblionumber } );
1791 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1792 my $reserve_id_1 = AddReserve(
1794 branchcode => $item->homebranch,
1795 borrowernumber => $patron_1->id,
1796 biblionumber => $item->biblionumber,
1799 my $reserve_id_2 = AddReserve(
1801 branchcode => $item->homebranch,
1802 borrowernumber => $patron_2->id,
1803 biblionumber => $item->biblionumber,
1807 C4::HoldsQueue::AddToHoldTargetMap(
1810 borrowernumber => $patron_1->id, biblionumber => $item->biblionumber,
1811 holdingbranch => $item->holdingbranch, item_level => 0, reserve_id => $reserve_id_1
1816 # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1817 my @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item->id, 0, [] );
1818 is( scalar @reserves, 1, "We should only get the hold that is in the map" );
1819 is( $reserves[0]->{reserve_id}, $reserve_id_1, "We got the expected reserve" );
1821 C4::HoldsQueue::AddToHoldTargetMap(
1824 borrowernumber => $patron_2->id, biblionumber => $item->biblionumber,
1825 holdingbranch => $item->holdingbranch, item_level => 1, reserve_id => $reserve_id_2
1830 # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1831 @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item_2->id, 0, [] );
1832 is( scalar @reserves, 1, "We should only get the item level hold that is in the map" );
1833 is( $reserves[0]->{reserve_id}, $reserve_id_2, "We got the expected reserve" );
1835 C4::HoldsQueue::AddToHoldTargetMap(
1838 borrowernumber => $patron_2->id, biblionumber => $item->biblionumber,
1839 holdingbranch => $item->holdingbranch, item_level => 1, reserve_id => $reserve_id_1
1844 # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1845 @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item_2->id, 0, [] );
1846 is( scalar @reserves, 1, "We should still only get the item level hold that is in the map" );
1847 is( $reserves[0]->{reserve_id}, $reserve_id_1, "We got the expected reserve which has been updated" );
1851 $schema->txn_rollback;
1854 subtest 'HOLDDGST tests' => sub {
1857 $schema->storage->txn_begin;
1859 my $branch = $builder->build_object(
1861 class => 'Koha::Libraries',
1863 branchemail => 'branch@e.mail',
1864 branchreplyto => 'branch@reply.to',
1865 pickup_location => 1
1869 my $item = $builder->build_sample_item(
1871 homebranch => $branch->branchcode,
1872 holdingbranch => $branch->branchcode
1875 my $item2 = $builder->build_sample_item(
1877 homebranch => $branch->branchcode,
1878 holdingbranch => $branch->branchcode
1882 my $wants_hold_and_email = {
1883 wants_digest => '1',
1886 email => 'HOLDDGST',
1888 letter_code => 'HOLDDGST'
1891 my $mp = Test::MockModule->new('C4::Members::Messaging');
1893 $mp->mock( "GetMessagingPreferences", $wants_hold_and_email );
1895 $dbh->do('DELETE FROM letter');
1897 my $email_hold_notice = $builder->build(
1901 message_transport_type => 'email',
1904 module => 'reserves',
1910 my $sms_hold_notice = $builder->build(
1914 message_transport_type => 'sms',
1917 module => 'reserves',
1923 my $hold_borrower = $builder->build(
1925 source => 'Borrower',
1927 smsalertnumber => '5555555551',
1931 )->{borrowernumber};
1933 C4::Reserves::AddReserve(
1935 branchcode => $item->homebranch,
1936 borrowernumber => $hold_borrower,
1937 biblionumber => $item->biblionumber,
1941 C4::Reserves::AddReserve(
1943 branchcode => $item2->homebranch,
1944 borrowernumber => $hold_borrower,
1945 biblionumber => $item2->biblionumber,
1949 ModReserveAffect( $item->itemnumber, $hold_borrower, 0 );
1950 ModReserveAffect( $item2->itemnumber, $hold_borrower, 0 );
1952 my $sms_count = $schema->resultset('MessageQueue')->search(
1954 letter_code => 'HOLDDGST',
1955 message_transport_type => 'sms',
1956 borrowernumber => $hold_borrower,
1959 is( $sms_count, 1, "Only one sms hold digest message created for two holds" );
1961 my $email_count = $schema->resultset('MessageQueue')->search(
1963 letter_code => 'HOLDDGST',
1964 message_transport_type => 'email',
1965 borrowernumber => $hold_borrower,
1968 is( $email_count, 1, "Only one email hold digest message created for two holds" );
1970 $schema->txn_rollback;