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(
83 { source => 'Itemtype', value => { notforloan => undef } } )->{itemtype};
85 t::lib::Mocks::mock_userenv({ branchcode => $branch_1 });
87 my $bibnum = $builder->build_sample_biblio({frameworkcode => $frameworkcode})->biblionumber;
89 # Create a helper item instance for testing
90 my $item = $builder->build_sample_item({ biblionumber => $bibnum, library => $branch_1, itype => $itemtype });
92 my $biblio_with_no_item = $builder->build_sample_biblio;
94 # Modify item; setting barcode.
95 my $testbarcode = '97531';
96 $item->barcode($testbarcode)->store; # FIXME We should not hardcode a barcode! Also, what's the purpose of this?
101 firstname => 'my firstname',
102 surname => 'my surname',
103 categorycode => $category_1,
104 branchcode => $branch_1,
106 Koha::Patron::Categories->find($category_1)->set({ enrolmentfee => 0})->store;
107 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
108 my $patron = Koha::Patrons->find( $borrowernumber );
109 my $borrower = $patron->unblessed;
110 my $biblionumber = $bibnum;
112 my $branchcode = Koha::Libraries->search->next->branchcode;
116 branchcode => $branchcode,
117 borrowernumber => $borrowernumber,
118 biblionumber => $biblionumber,
123 my ($status, $reserve, $all_reserves) = CheckReserves( $item );
125 is($status, "Reserved", "CheckReserves Test 1");
127 ok(exists($reserve->{reserve_id}), 'CheckReserves() include reserve_id in its response');
129 ($status, $reserve, $all_reserves) = CheckReserves( $item );
130 is($status, "Reserved", "CheckReserves Test 2");
133 ### Regression test for bug 10272
136 $requesters{$branch_1} = Koha::Patron->new({
137 branchcode => $branch_1,
138 categorycode => $category_2,
139 surname => "borrower from $branch_1",
140 })->store->borrowernumber;
141 for my $i ( 2 .. 5 ) {
142 $requesters{"CPL$i"} = Koha::Patron->new({
143 branchcode => $branch_1,
144 categorycode => $category_2,
145 surname => "borrower $i from $branch_1",
146 })->store->borrowernumber;
148 $requesters{$branch_2} = Koha::Patron->new({
149 branchcode => $branch_2,
150 categorycode => $category_2,
151 surname => "borrower from $branch_2",
152 })->store->borrowernumber;
153 $requesters{$branch_3} = Koha::Patron->new({
154 branchcode => $branch_3,
155 categorycode => $category_2,
156 surname => "borrower from $branch_3",
157 })->store->borrowernumber;
159 # Configure rules so that $branch_1 allows only $branch_1 patrons
160 # to request its items, while $branch_2 will allow its items
161 # to fill holds from anywhere.
163 $dbh->do('DELETE FROM circulation_rules');
164 Koha::CirculationRules->set_rules(
167 categorycode => undef,
170 reservesallowed => 25,
171 holds_per_record => 1,
176 # CPL allows only its own patrons to request its items
177 Koha::CirculationRules->set_rules(
179 branchcode => $branch_1,
182 holdallowed => 'from_home_library',
183 returnbranch => 'homebranch',
188 # ... while FPL allows anybody to request its items
189 Koha::CirculationRules->set_rules(
191 branchcode => $branch_2,
194 holdallowed => 'from_any_library',
195 returnbranch => 'homebranch',
200 my $bibnum2 = $builder->build_sample_biblio({frameworkcode => $frameworkcode})->biblionumber;
202 my ($itemnum_cpl, $itemnum_fpl);
203 $itemnum_cpl = $builder->build_sample_item(
205 biblionumber => $bibnum2,
206 library => $branch_1,
207 barcode => 'bug10272_CPL',
211 $itemnum_fpl = $builder->build_sample_item(
213 biblionumber => $bibnum2,
214 library => $branch_2,
215 barcode => 'bug10272_FPL',
220 # Ensure that priorities are numbered correcly when a hold is moved to waiting
222 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
225 branchcode => $branch_3,
226 borrowernumber => $requesters{$branch_3},
227 biblionumber => $bibnum2,
233 branchcode => $branch_2,
234 borrowernumber => $requesters{$branch_2},
235 biblionumber => $bibnum2,
241 branchcode => $branch_1,
242 borrowernumber => $requesters{$branch_1},
243 biblionumber => $bibnum2,
247 ModReserveAffect($itemnum_cpl, $requesters{$branch_3}, 0);
249 # Now it should have different priorities.
250 my $biblio = Koha::Biblios->find( $bibnum2 );
251 my $holds = $biblio->holds({}, { order_by => 'reserve_id' });;
252 is($holds->next->priority, 0, 'Item is correctly waiting');
253 is($holds->next->priority, 1, 'Item is correctly priority 1');
254 is($holds->next->priority, 2, 'Item is correctly priority 2');
256 my @reserves = Koha::Holds->search({ borrowernumber => $requesters{$branch_3} })->waiting->as_list;
257 is( @reserves, 1, 'GetWaiting got only the waiting reserve' );
258 is( $reserves[0]->borrowernumber(), $requesters{$branch_3}, 'GetWaiting got the reserve for the correct borrower' );
261 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
264 branchcode => $branch_3,
265 borrowernumber => $requesters{$branch_3},
266 biblionumber => $bibnum2,
272 branchcode => $branch_2,
273 borrowernumber => $requesters{$branch_2},
274 biblionumber => $bibnum2,
281 branchcode => $branch_1,
282 borrowernumber => $requesters{$branch_1},
283 biblionumber => $bibnum2,
288 # Ensure that the item's home library controls hold policy lookup
289 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
292 # Return the CPL item at FPL. The hold that should be triggered is
293 # the one placed by the CPL patron, as the other two patron's hold
294 # requests cannot be filled by that item per policy.
295 (undef, $messages, undef, undef) = AddReturn('bug10272_CPL', $branch_2);
296 is( $messages->{ResFound}->{borrowernumber},
297 $requesters{$branch_1},
298 'restrictive library\'s items only fill requests by own patrons (bug 10272)');
300 # Return the FPL item at FPL. The hold that should be triggered is
301 # the one placed by the RPL patron, as that patron is first in line
302 # and RPL imposes no restrictions on whose holds its items can fill.
304 # Ensure that the preference 'LocalHoldsPriority' is not set (Bug 15244):
305 t::lib::Mocks::mock_preference( 'LocalHoldsPriority', '' );
307 (undef, $messages, undef, undef) = AddReturn('bug10272_FPL', $branch_2);
308 is( $messages->{ResFound}->{borrowernumber},
309 $requesters{$branch_3},
310 'for generous library, its items fill first hold request in line (bug 10272)');
312 $biblio = Koha::Biblios->find( $biblionumber );
313 $holds = $biblio->holds;
314 is($holds->count, 1, "Only one reserves for this biblio");
315 $holds->next->reserve_id;
317 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
318 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
319 # Test 9761a: Add a reserve without date, CheckReserve should return it
320 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
323 branchcode => $branch_1,
324 borrowernumber => $requesters{$branch_1},
325 biblionumber => $bibnum,
329 ($status)=CheckReserves( $item );
330 is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead');
331 ($status)=CheckReserves( $item, 7 );
332 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
334 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
335 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
336 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
337 my $resdate= dt_from_string();
338 $resdate->add_duration(DateTime::Duration->new(days => 4));
339 my $reserve_id = AddReserve(
341 branchcode => $branch_1,
342 borrowernumber => $requesters{$branch_1},
343 biblionumber => $bibnum,
345 reservation_date => $resdate,
348 ($status)=CheckReserves( $item );
349 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
351 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
352 ($status)=CheckReserves( $item, 3 );
353 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
354 ($status)=CheckReserves( $item, 4 );
355 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
357 # Test 9761d: Check ResFound message of AddReturn for future hold
358 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
359 # In this test we do not need an issued item; it is just a 'checkin'
360 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
361 (my $doreturn, $messages)= AddReturn($testbarcode,$branch_1);
362 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
363 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 3);
364 ($doreturn, $messages)= AddReturn($testbarcode,$branch_1);
365 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
366 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 7);
367 ($doreturn, $messages)= AddReturn($testbarcode,$branch_1);
368 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
370 my $now_holder = $builder->build_object({ class => 'Koha::Patrons', value => {
371 branchcode => $branch_1,
373 my $now_reserve_id = AddReserve(
375 branchcode => $branch_1,
376 borrowernumber => $requesters{$branch_1},
377 biblionumber => $bibnum,
379 reservation_date => dt_from_string(),
383 ($status,$which_highest)=CheckReserves( $item, 3 );
384 is( $which_highest->{reserve_id}, $now_reserve_id, 'CheckReserves returns lower priority current reserve with insufficient lookahead');
385 ($status, $which_highest)=CheckReserves( $item, 4 );
386 is( $which_highest->{reserve_id}, $reserve_id, 'CheckReserves returns higher priority future reserve with sufficient lookahead');
387 ModReserve({ reserve_id => $now_reserve_id, rank => 'del', cancellation_reason => 'test reserve' });
390 # End of tests for bug 9761 (ConfirmFutureHolds)
393 # test marking a hold as captured
394 my $hold_notice_count = count_hold_print_messages();
395 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
396 my $new_count = count_hold_print_messages();
397 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
399 # test that duplicate notices aren't generated
400 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
401 $new_count = count_hold_print_messages();
402 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
404 # avoiding the not_same_branch error
405 t::lib::Mocks::mock_preference('IndependentBranches', 0);
406 $item = Koha::Items->find($item->itemnumber);
408 @{$item->safe_delete->messages}[0]->message,
410 'item that is captured to fill a hold cannot be deleted',
413 my $letter = ReserveSlip( { branchcode => $branch_1, reserve_id => $reserve_id } );
414 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
416 # Tests for bug 9788: Does Koha::Item->current_holds return a future wait?
417 # 9788a: current_holds does not return future next available hold
418 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
419 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
420 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
421 $resdate= dt_from_string();
422 $resdate->add_duration(DateTime::Duration->new(days => 2));
425 branchcode => $branch_1,
426 borrowernumber => $requesters{$branch_1},
427 biblionumber => $bibnum,
429 reservation_date => $resdate,
433 $holds = $item->current_holds;
434 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
435 my $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
436 is( $future_holds->count, 0, 'current_holds does not return a future next available hold');
437 # 9788b: current_holds does not return future item level hold
438 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
441 branchcode => $branch_1,
442 borrowernumber => $requesters{$branch_1},
443 biblionumber => $bibnum,
445 reservation_date => $resdate,
446 itemnumber => $item->itemnumber,
449 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
450 is( $future_holds->count, 0, 'current_holds does not return a future item level hold' );
451 # 9788c: current_holds returns future wait (confirmed future hold)
452 ModReserveAffect( $item->itemnumber, $requesters{$branch_1} , 0); #confirm hold
453 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
454 is( $future_holds->count, 1, 'current_holds returns a future wait (confirmed future hold)' );
455 # End of tests for bug 9788
457 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
458 # Tests for CalculatePriority (bug 8918)
459 my $p = C4::Reserves::CalculatePriority($bibnum2);
460 is($p, 4, 'CalculatePriority should now return priority 4');
463 branchcode => $branch_1,
464 borrowernumber => $requesters{'CPL2'},
465 biblionumber => $bibnum2,
469 $p = C4::Reserves::CalculatePriority($bibnum2);
470 is($p, 5, 'CalculatePriority should now return priority 5');
471 #some tests on bibnum
472 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
473 $p = C4::Reserves::CalculatePriority($bibnum);
474 is($p, 1, 'CalculatePriority should now return priority 1');
475 #add a new reserve and confirm it to waiting
478 branchcode => $branch_1,
479 borrowernumber => $requesters{$branch_1},
480 biblionumber => $bibnum,
482 itemnumber => $item->itemnumber,
485 $p = C4::Reserves::CalculatePriority($bibnum);
486 is($p, 2, 'CalculatePriority should now return priority 2');
487 ModReserveAffect( $item->itemnumber, $requesters{$branch_1} , 0);
488 $p = C4::Reserves::CalculatePriority($bibnum);
489 is($p, 1, 'CalculatePriority should now return priority 1');
490 #add another biblio hold, no resdate
493 branchcode => $branch_1,
494 borrowernumber => $requesters{'CPL2'},
495 biblionumber => $bibnum,
499 $p = C4::Reserves::CalculatePriority($bibnum);
500 is($p, 2, 'CalculatePriority should now return priority 2');
501 #add another future hold
502 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
503 $resdate= dt_from_string();
504 $resdate->add_duration(DateTime::Duration->new(days => 1));
507 branchcode => $branch_1,
508 borrowernumber => $requesters{'CPL2'},
509 biblionumber => $bibnum,
511 reservation_date => $resdate,
514 $p = C4::Reserves::CalculatePriority($bibnum);
515 is($p, 2, 'CalculatePriority should now still return priority 2');
516 #calc priority with future resdate
517 $p = C4::Reserves::CalculatePriority($bibnum, $resdate);
518 is($p, 3, 'CalculatePriority should now return priority 3');
519 # End of tests for bug 8918
521 # regression test for bug 12630
522 # Now there are 2 reserves on $bibnum
523 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
524 my $bor_tmp_1 = $builder->build_object({ class => 'Koha::Patrons',value =>{
525 firstname => 'my firstname tmp 1',
526 surname => 'my surname tmp 1',
530 my $bor_tmp_2 = $builder->build_object({ class => 'Koha::Patrons',value =>{
531 firstname => 'my firstname tmp 2',
532 surname => 'my surname tmp 2',
536 my $borrowernumber_tmp_1 = $bor_tmp_1->borrowernumber;
537 my $borrowernumber_tmp_2 = $bor_tmp_2->borrowernumber;
538 my $date_in_future = dt_from_string();
539 $date_in_future = $date_in_future->add_duration(DateTime::Duration->new(days => 1));
542 borrowernumber => $borrowernumber_tmp_1,
543 biblionumber => $bibnum,
545 reservation_date => $date_in_future
549 borrowernumber => $borrowernumber_tmp_2,
550 biblionumber => $bibnum,
552 reservation_date => $date_in_future
554 my @r1 = Koha::Holds->search({ borrowernumber => $borrowernumber_tmp_1 })->as_list;
555 my @r2 = Koha::Holds->search({ borrowernumber => $borrowernumber_tmp_2 })->as_list;
556 is( $r1[0]->priority, 3, 'priority for hold in future should be correct');
557 is( $r2[0]->priority, 4, 'priority for hold not in future should be correct');
558 # end of tests for bug 12630
560 # Tests for cancel reserves by users from OPAC.
561 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
564 branchcode => $branch_1,
565 borrowernumber => $requesters{$branch_1},
566 biblionumber => $bibnum,
570 my (undef, $canres, undef) = CheckReserves( $item );
572 is( CanReserveBeCanceledFromOpac(), undef,
573 'CanReserveBeCanceledFromOpac should return undef if called without any parameter'
576 CanReserveBeCanceledFromOpac( $canres->{resserve_id} ),
578 'CanReserveBeCanceledFromOpac should return undef if called without the reserve_id'
581 CanReserveBeCanceledFromOpac( undef, $requesters{CPL} ),
583 'CanReserveBeCanceledFromOpac should return undef if called without borrowernumber'
586 my $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
587 is($cancancel, 1, 'Can user cancel its own reserve');
589 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_2});
590 is($cancancel, 0, 'Other user cant cancel reserve');
592 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 1);
593 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
594 is($cancancel, 0, 'Reserve in transfer status cant be canceled');
596 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
597 is( CanReserveBeCanceledFromOpac($canres->{resserve_id}, $requesters{$branch_1}), undef,
598 'Cannot cancel a deleted hold' );
602 branchcode => $branch_1,
603 borrowernumber => $requesters{$branch_1},
604 biblionumber => $bibnum,
608 (undef, $canres, undef) = CheckReserves( $item );
610 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
611 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
612 is($cancancel, 0, 'Reserve in waiting status cant be canceled');
614 # End of tests for bug 12876
617 ####### Testing Bug 13113 - Prevent juvenile/children from reserving ageRestricted material >>>
620 t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' );
622 #Reserving an not-agerestricted Biblio by a Borrower with no dateofbirth is tested previously.
624 #Set the ageRestriction for the Biblio
625 $biblio = Koha::Biblios->find($bibnum);
626 my $record = $biblio->metadata->record;
627 my ( $ageres_tagid, $ageres_subfieldid ) = GetMarcFromKohaField( "biblioitems.agerestriction" );
628 $record->append_fields( MARC::Field->new($ageres_tagid, '', '', $ageres_subfieldid => 'PEGI 16') );
629 C4::Biblio::ModBiblio( $record, $bibnum, $frameworkcode );
631 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'OK', "Reserving an ageRestricted Biblio without a borrower dateofbirth succeeds" );
633 #Set the dateofbirth for the Borrower making them "too young".
634 $borrower->{dateofbirth} = DateTime->now->add( years => -15 );
635 Koha::Patrons->find( $borrowernumber )->set({ dateofbirth => $borrower->{dateofbirth} })->store;
637 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'ageRestricted', "Reserving a 'PEGI 16' Biblio by a 15 year old borrower fails");
639 #Set the dateofbirth for the Borrower making them "too old".
640 $borrower->{dateofbirth} = DateTime->now->add( years => -30 );
641 Koha::Patrons->find( $borrowernumber )->set({ dateofbirth => $borrower->{dateofbirth} })->store;
643 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'OK', "Reserving a 'PEGI 16' Biblio by a 30 year old borrower succeeds");
645 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblio_with_no_item->biblionumber)->{status} , '', "Biblio with no item. Status is empty");
647 ####### EO Bug 13113 <<<
650 ok( C4::Reserves::IsAvailableForItemLevelRequest($item, $patron), "Reserving a book on item level" );
652 my $pickup_branch = $builder->build({ source => 'Branch' })->{ branchcode };
653 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' );
654 t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' );
655 my $limit = Koha::Item::Transfer::Limit->new(
657 toBranch => $pickup_branch,
658 fromBranch => $item->holdingbranch,
659 itemtype => $item->effective_itemtype,
662 is( C4::Reserves::IsAvailableForItemLevelRequest($item, $patron, $pickup_branch), 0, "Item level request not available due to transfer limit" );
663 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' );
665 my $categorycode = $borrower->{categorycode};
666 my $holdingbranch = $item->{holdingbranch};
667 Koha::CirculationRules->set_rules(
669 categorycode => $categorycode,
670 itemtype => $item->effective_itemtype,
671 branchcode => $holdingbranch,
678 # tests for MoveReserve in relation to ConfirmFutureHolds (BZ 14526)
679 # hold from A pos 1, today, no fut holds: MoveReserve should fill it
680 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
681 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
682 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
685 branchcode => $branch_1,
686 borrowernumber => $borrowernumber,
687 biblionumber => $bibnum,
691 MoveReserve( $item->itemnumber, $borrowernumber );
692 ($status)=CheckReserves( $item );
693 is( $status, '', 'MoveReserve filled hold');
694 # hold from A waiting, today, no fut holds: MoveReserve should fill it
695 my $other_item = $builder->build_sample_item({ biblionumber => $biblio->id });
698 branchcode => $branch_1,
699 borrowernumber => $borrowernumber,
700 biblionumber => $bibnum,
703 itemnumber => $other_item->id,
706 MoveReserve( $item->itemnumber, $borrowernumber );
707 ($status)=CheckReserves( $item );
708 is( $status, '', 'MoveReserve filled waiting hold');
709 # hold from A pos 1, tomorrow, no fut holds: not filled
710 $resdate= dt_from_string();
711 $resdate->add_duration(DateTime::Duration->new(days => 1));
714 branchcode => $branch_1,
715 borrowernumber => $borrowernumber,
716 biblionumber => $bibnum,
718 reservation_date => $resdate,
721 MoveReserve( $item->itemnumber, $borrowernumber );
722 ($status)=CheckReserves( $item, 1 );
723 is( $status, 'Reserved', 'MoveReserve did not fill future hold');
724 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
725 # hold from A pos 1, tomorrow, fut holds=2: MoveReserve should fill it
726 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
729 branchcode => $branch_1,
730 borrowernumber => $borrowernumber,
731 biblionumber => $bibnum,
733 reservation_date => $resdate,
736 MoveReserve( $item->itemnumber, $borrowernumber );
737 ($status)=CheckReserves( $item, undef, 2 );
738 is( $status, '', 'MoveReserve filled future hold now');
739 # hold from A waiting, tomorrow, fut holds=2: MoveReserve should fill it
742 branchcode => $branch_1,
743 borrowernumber => $borrowernumber,
744 biblionumber => $bibnum,
746 reservation_date => $resdate,
749 MoveReserve( $item->itemnumber, $borrowernumber );
750 ($status)=CheckReserves( $item, undef, 2 );
751 is( $status, '', 'MoveReserve filled future waiting hold now');
752 # hold from A pos 1, today+3, fut holds=2: MoveReserve should not fill it
753 $resdate= dt_from_string();
754 $resdate->add_duration(DateTime::Duration->new(days => 3));
757 branchcode => $branch_1,
758 borrowernumber => $borrowernumber,
759 biblionumber => $bibnum,
761 reservation_date => $resdate,
764 MoveReserve( $item->itemnumber, $borrowernumber );
765 ($status)=CheckReserves( $item, 3 );
766 is( $status, 'Reserved', 'MoveReserve did not fill future hold of 3 days');
767 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
769 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
770 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
771 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
773 subtest '_koha_notify_reserve() tests' => sub {
777 my $branch = $builder->build_object({
778 class => 'Koha::Libraries',
780 branchemail => 'branch@e.mail',
781 branchreplyto => 'branch@reply.to',
785 my $item = $builder->build_sample_item({
786 homebranch => $branch->branchcode,
787 holdingbranch => $branch->branchcode
790 my $wants_hold_and_email = {
796 letter_code => 'HOLD'
799 my $mp = Test::MockModule->new( 'C4::Members::Messaging' );
801 $mp->mock("GetMessagingPreferences",$wants_hold_and_email);
803 $dbh->do('DELETE FROM letter');
805 my $email_hold_notice = $builder->build({
808 message_transport_type => 'email',
811 module => 'reserves',
816 my $sms_hold_notice = $builder->build({
819 message_transport_type => 'sms',
822 module => 'reserves',
827 my $hold_borrower = $builder->build({
828 source => 'Borrower',
830 smsalertnumber=>'5555555555',
833 })->{borrowernumber};
835 C4::Reserves::AddReserve(
837 branchcode => $item->homebranch,
838 borrowernumber => $hold_borrower,
839 biblionumber => $item->biblionumber,
843 ModReserveAffect($item->itemnumber, $hold_borrower, 0);
844 my $sms_message_address = $schema->resultset('MessageQueue')->search({
845 letter_code => 'HOLD',
846 message_transport_type => 'sms',
847 borrowernumber => $hold_borrower,
848 })->next()->to_address();
849 is($sms_message_address, undef ,"We should not populate the sms message with the sms number, sending will do so");
851 my $email = $schema->resultset('MessageQueue')->search({
852 letter_code => 'HOLD',
853 message_transport_type => 'email',
854 borrowernumber => $hold_borrower,
856 my $email_to_address = $email->to_address();
857 is($email_to_address, undef ,"We should not populate the hold message with the email address, sending will do so");
858 my $email_from_address = $email->from_address();
859 is($email_from_address,'branch@e.mail',"Library's from address is used for sending");
863 subtest 'ReservesNeedReturns' => sub {
866 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
868 homebranch => $library->branchcode,
869 holdingbranch => $library->branchcode,
871 my $item = $builder->build_sample_item($item_info);
872 my $patron = $builder->build_object(
874 class => 'Koha::Patrons',
875 value => { branchcode => $library->branchcode, }
878 my $patron_2 = $builder->build_object(
880 class => 'Koha::Patrons',
881 value => { branchcode => $library->branchcode, }
887 t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Test with feature disabled
888 my $hold = place_item_hold( $patron, $item, $library, $priority );
889 is( $hold->priority, $priority, 'If ReservesNeedReturns is 1, priority must not have been set to changed' );
890 is( $hold->found, undef, 'If ReservesNeedReturns is 1, found must not have been set waiting' );
893 t::lib::Mocks::mock_preference('ReservesNeedReturns', 0); # '0' means 'Automatically mark a hold as found and waiting'
894 $hold = place_item_hold( $patron, $item, $library, $priority );
895 is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
896 is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
899 $item->onloan('2010-01-01')->store;
900 $hold = place_item_hold( $patron, $item, $library, $priority );
901 is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item onloan priority must be set to 1' );
904 t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 0); # '0' means damaged holds not allowed
905 $item->onloan(undef)->damaged(1)->store;
906 $hold = place_item_hold( $patron, $item, $library, $priority );
907 is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item damaged and not allowed holds on damaged items priority must be set to 1' );
909 t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 1); # '0' means damaged holds not allowed
910 $hold = place_item_hold( $patron, $item, $library, $priority );
911 is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and damaged holds allowed, priority must have been set to 0' );
912 is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and damaged holds allowed, found must have been set waiting' );
915 my $hold_1 = place_item_hold( $patron, $item, $library, $priority );
916 is( $hold_1->found, 'W', 'First hold on item is set to waiting with ReservesNeedReturns set to 0' );
917 is( $hold_1->priority, 0, 'First hold on item is set to waiting with ReservesNeedReturns set to 0' );
918 $hold = place_item_hold( $patron_2, $item, $library, $priority );
919 is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item already on hold priority must be set to 1' );
923 my $transfer = $builder->build_object({
924 class => "Koha::Item::Transfers",
926 itemnumber => $item->itemnumber,
927 datearrived => undef,
928 datecancelled => undef
931 $item->damaged(0)->store;
932 $hold = place_item_hold( $patron, $item, $library, $priority );
933 is( $hold->found, undef, 'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
934 is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
938 $hold = place_item_hold( $patron, $item, $library, $priority );
939 is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
940 is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
941 $hold_1 = place_item_hold( $patron, $item, $library, $priority );
942 is( $hold_1->priority, 1, 'If ReservesNeedReturns is 0 but item has a hold priority is 1' );
943 $hold_1->suspend(1)->store; # We suspend the hold
944 $hold->delete; # Delete the waiting hold
945 $hold = place_item_hold( $patron, $item, $library, $priority );
946 is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and other hold(s) suspended, priority must have been set to 0' );
947 is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and other hold(s) suspended, found must have been set waiting' );
952 t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Don't affect other tests
955 subtest 'ChargeReserveFee tests' => sub {
959 my $library = $builder->build_object({ class => 'Koha::Libraries' });
960 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
963 my $title = 'A title';
965 my $context = Test::MockModule->new('C4::Context');
966 $context->mock( userenv => { branch => $library->id } );
968 my $line = C4::Reserves::ChargeReserveFee( $patron->id, $fee, $title );
970 is( ref($line), 'Koha::Account::Line' , 'Returns a Koha::Account::Line object');
971 ok( $line->is_debit, 'Generates a debit line' );
972 is( $line->debit_type_code, 'RESERVE' , 'generates RESERVE debit_type');
973 is( $line->borrowernumber, $patron->id , 'generated line belongs to the passed patron');
974 is( $line->amount, $fee , 'amount set correctly');
975 is( $line->amountoutstanding, $fee , 'amountoutstanding set correctly');
976 is( $line->description, "$title" , 'description is title of reserved item');
977 is( $line->branchcode, $library->id , "Library id is picked from userenv and stored correctly" );
980 subtest 'reserves.item_level_hold' => sub {
983 my $item = $builder->build_sample_item;
984 my $patron = $builder->build_object(
986 class => 'Koha::Patrons',
987 value => { branchcode => $item->homebranch }
991 subtest 'item level hold' => sub {
993 my $reserve_id = AddReserve(
995 branchcode => $item->homebranch,
996 borrowernumber => $patron->borrowernumber,
997 biblionumber => $item->biblionumber,
999 itemnumber => $item->itemnumber,
1003 my $hold = Koha::Holds->find($reserve_id);
1004 is( $hold->item_level_hold, 1, 'item_level_hold should be set when AddReserve is called with a specific item' );
1007 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
1009 my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1010 $mock->mock( 'enqueue', sub {
1011 my ( $self, $args ) = @_;
1013 $args->{biblio_ids},
1014 [ $hold->biblionumber ],
1015 "AlterPriority triggers a holds queue update for the related biblio"
1019 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1020 t::lib::Mocks::mock_preference( 'HoldsLog', 1 );
1022 # Revert the waiting status
1023 C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1025 $hold = Koha::Holds->find($reserve_id);
1028 $hold->itemnumber, $item->itemnumber,
1029 'Itemnumber should not be removed when the waiting status is revert'
1033 Koha::ActionLogs->search( { module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id } )->next;
1034 my $expected = sprintf q{'timestamp' => '%s'}, $hold->timestamp;
1035 like( $log->info, qr{$expected}, 'Timestamp logged is the current one' );
1037 Koha::ActionLogs->search( { module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id } )->count;
1039 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1040 t::lib::Mocks::mock_preference( 'HoldsLog', 0 );
1044 # Revert the waiting status, RealTimeHoldsQueue => shouldn't add a test
1045 C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1047 $hold->delete; # cleanup
1049 my $log_count_after =
1050 Koha::ActionLogs->search( { module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id } )->count;
1051 is( $log_count, $log_count_after, "No logging is added for RevertWaitingStatus when HoldsLog is disabled" );
1055 subtest 'biblio level hold' => sub {
1057 my $reserve_id = AddReserve(
1059 branchcode => $item->homebranch,
1060 borrowernumber => $patron->borrowernumber,
1061 biblionumber => $item->biblionumber,
1066 my $hold = Koha::Holds->find($reserve_id);
1067 is( $hold->item_level_hold, 0, 'item_level_hold should not be set when AddReserve is called without a specific item' );
1070 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
1072 $hold = Koha::Holds->find($reserve_id);
1073 is( $hold->itemnumber, $item->itemnumber, 'Itemnumber should be set on hold confirmation' );
1075 # Revert the waiting status
1076 C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1078 $hold = Koha::Holds->find($reserve_id);
1079 is( $hold->itemnumber, undef, 'Itemnumber should be removed when the waiting status is revert' );
1086 subtest 'MoveReserve additional test' => sub {
1090 # Create the items and patrons we need
1091 my $biblio = $builder->build_sample_biblio();
1092 my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
1093 my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1094 my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber, notforloan => 0, itype => $itype->itemtype });
1095 my $patron_1 = $builder->build_object({ class => "Koha::Patrons" });
1096 my $patron_2 = $builder->build_object({ class => "Koha::Patrons" });
1098 # Place a hold on the title for both patrons
1099 my $reserve_1 = AddReserve(
1101 branchcode => $item_1->homebranch,
1102 borrowernumber => $patron_1->borrowernumber,
1103 biblionumber => $biblio->biblionumber,
1105 itemnumber => $item_1->itemnumber,
1108 my $reserve_2 = AddReserve(
1110 branchcode => $item_2->homebranch,
1111 borrowernumber => $patron_2->borrowernumber,
1112 biblionumber => $biblio->biblionumber,
1114 itemnumber => $item_1->itemnumber,
1117 is($patron_1->holds->next()->reserve_id, $reserve_1, "The 1st patron has a hold");
1118 is($patron_2->holds->next()->reserve_id, $reserve_2, "The 2nd patron has a hold");
1120 # Fake the holds queue
1121 $dbh->do(q{INSERT INTO hold_fill_targets VALUES (?, ?, ?, ?, ?,?)},undef,($patron_1->borrowernumber,$biblio->biblionumber,$item_1->itemnumber,$item_1->homebranch,0,$reserve_1));
1123 # The 2nd hold should be filed even if the item is preselected for the first hold
1124 MoveReserve($item_1->itemnumber,$patron_2->borrowernumber);
1125 is($patron_2->holds->count, 0, "The 2nd patrons no longer has a hold");
1126 is($patron_2->old_holds->next()->reserve_id, $reserve_2, "The 2nd patrons hold was filled and moved to old holds");
1130 subtest 'RevertWaitingStatus' => sub {
1134 # Create the items and patrons we need
1135 my $biblio = $builder->build_sample_biblio();
1136 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1137 my $itype = $builder->build_object(
1138 { class => "Koha::ItemTypes", value => { notforloan => 0 } } );
1139 my $item_1 = $builder->build_sample_item(
1141 biblionumber => $biblio->biblionumber,
1142 itype => $itype->itemtype,
1143 library => $library->branchcode
1146 my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1147 my $patron_2 = $builder->build_object( { class => "Koha::Patrons" } );
1148 my $patron_3 = $builder->build_object( { class => "Koha::Patrons" } );
1149 my $patron_4 = $builder->build_object( { class => "Koha::Patrons" } );
1151 # Place a hold on the title for both patrons
1153 my $hold_1 = place_item_hold( $patron_1, $item_1, $library, $priority );
1154 my $hold_2 = place_item_hold( $patron_2, $item_1, $library, $priority );
1155 my $hold_3 = place_item_hold( $patron_3, $item_1, $library, $priority );
1156 my $hold_4 = place_item_hold( $patron_4, $item_1, $library, $priority );
1158 $hold_1->set_waiting;
1159 AddIssue( $patron_3, $item_1->barcode, undef, 'revert' );
1161 my $holds = $biblio->holds;
1162 is( $holds->count, 3, 'One hold has been deleted' );
1165 $holds->next->priority, $holds->next->priority,
1166 $holds->next->priority
1169 'priorities have been reordered'
1173 subtest 'CheckReserves additional tests' => sub {
1177 my $item = $builder->build_sample_item;
1178 my $reserve1 = $builder->build_object(
1180 class => "Koha::Holds",
1184 itemnumber => undef,
1185 biblionumber => $item->biblionumber,
1186 waitingdate => undef,
1187 cancellationdate => undef,
1188 item_level_hold => 0,
1189 lowestPriority => 0,
1190 expirationdate => undef,
1191 suspend_until => undef,
1197 my $reserve2 = $builder->build_object(
1199 class => "Koha::Holds",
1203 biblionumber => $item->biblionumber,
1204 borrowernumber => $reserve1->borrowernumber,
1205 itemnumber => undef,
1206 waitingdate => undef,
1207 cancellationdate => undef,
1208 item_level_hold => 0,
1209 lowestPriority => 0,
1210 expirationdate => undef,
1211 suspend_until => undef,
1218 my $tmp_holdsqueue = $builder->build(
1220 source => 'TmpHoldsqueue',
1222 borrowernumber => $reserve1->borrowernumber,
1223 biblionumber => $reserve1->biblionumber,
1227 my $fill_target = $builder->build(
1229 source => 'HoldFillTarget',
1231 borrowernumber => $reserve1->borrowernumber,
1232 biblionumber => $reserve1->biblionumber,
1233 itemnumber => $item->itemnumber,
1234 item_level_request => 0,
1239 ModReserveAffect( $item->itemnumber, $reserve1->borrowernumber, 1,
1240 $reserve1->reserve_id );
1241 my ( $status, $matched_reserve, $possible_reserves ) =
1242 CheckReserves( $item );
1244 is( $status, 'Transferred', "We found a reserve" );
1245 is( $matched_reserve->{reserve_id},
1246 $reserve1->reserve_id, "We got the Transit reserve" );
1247 is( scalar @$possible_reserves, 2, 'We do get both reserves' );
1249 my $patron_B = $builder->build_object({ class => "Koha::Patrons" });
1250 my $item_A = $builder->build_sample_item;
1251 my $item_B = $builder->build_sample_item({
1252 homebranch => $patron_B->branchcode,
1253 biblionumber => $item_A->biblionumber,
1254 itype => $item_A->itype
1256 Koha::CirculationRules->set_rules(
1258 branchcode => undef,
1259 categorycode => undef,
1260 itemtype => $item_A->itype,
1262 reservesallowed => 25,
1263 holds_per_record => 1,
1267 Koha::CirculationRules->set_rule({
1268 branchcode => undef,
1269 itemtype => $item_A->itype,
1270 rule_name => 'holdallowed',
1271 rule_value => 'from_home_library'
1273 my $reserve_id = AddReserve(
1275 branchcode => $patron_B->branchcode,
1276 borrowernumber => $patron_B->borrowernumber,
1277 biblionumber => $item_A->biblionumber,
1279 itemnumber => undef,
1283 ok( $reserve_id, "We can place a record level hold because one item is owned by patron's home library");
1284 t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary');
1285 ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1286 is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch");
1287 Koha::CirculationRules->set_rule({
1288 branchcode => $item_A->homebranch,
1289 itemtype => $item_A->itype,
1290 rule_name => 'holdallowed',
1291 rule_value => 'from_any_library'
1293 ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1294 is( $status, "Reserved", "We fill the hold with item A because item's branch rule says allow any");
1297 # Changing the control branch should change only the rule we get
1298 t::lib::Mocks::mock_preference('ReservesControlBranch', 'PatronLibrary');
1299 ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1300 is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch");
1301 Koha::CirculationRules->set_rule({
1302 branchcode => $patron_B->branchcode,
1303 itemtype => $item_A->itype,
1304 rule_name => 'holdallowed',
1305 rule_value => 'from_any_library'
1307 ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1308 is( $status, "Reserved", "We fill the hold with item A because patron's branch rule says allow any");
1312 subtest 'AllowHoldOnPatronPossession test' => sub {
1316 # Create the items and patrons we need
1317 my $biblio = $builder->build_sample_biblio();
1318 my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
1319 my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1320 my $patron = $builder->build_object({ class => "Koha::Patrons",
1321 value => { branchcode => $item->homebranch }});
1323 C4::Circulation::AddIssue($patron,
1325 t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 0);
1327 is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1328 $item->biblionumber)->{status},
1329 'alreadypossession',
1330 'Patron cannot place hold on a book loaned to itself');
1332 is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status},
1333 'alreadypossession',
1334 'Patron cannot place hold on an item loaned to itself');
1336 t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 1);
1338 is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1339 $item->biblionumber)->{status},
1341 'Patron can place hold on a book loaned to itself');
1343 is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status},
1345 'Patron can place hold on an item loaned to itself');
1348 subtest 'MergeHolds' => sub {
1352 my $biblio_1 = $builder->build_sample_biblio();
1353 my $biblio_2 = $builder->build_sample_biblio();
1354 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1355 my $itype = $builder->build_object(
1356 { class => "Koha::ItemTypes", value => { notforloan => 0 } } );
1357 my $item_1 = $builder->build_sample_item(
1359 biblionumber => $biblio_1->biblionumber,
1360 itype => $itype->itemtype,
1361 library => $library->branchcode
1364 my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1366 # Place a hold on $biblio_1
1368 place_item_hold( $patron_1, $item_1, $library, $priority );
1370 # Move and make sure hold is now on $biblio_2
1371 C4::Reserves::MergeHolds($dbh, $biblio_2->biblionumber, $biblio_1->biblionumber);
1372 is( $biblio_2->holds->count, 1, 'Hold has been transferred' );
1375 subtest 'ModReserveAffect logging' => sub {
1379 my $item = $builder->build_sample_item;
1380 my $patron = $builder->build_object(
1382 class => "Koha::Patrons",
1383 value => { branchcode => $item->homebranch }
1387 t::lib::Mocks::mock_userenv({ patron => $patron });
1388 t::lib::Mocks::mock_preference('HoldsLog', 1);
1390 my $reserve_id = AddReserve(
1392 branchcode => $item->homebranch,
1393 borrowernumber => $patron->borrowernumber,
1394 biblionumber => $item->biblionumber,
1396 itemnumber => $item->itemnumber,
1400 my $hold = Koha::Holds->find($reserve_id);
1401 my $previous_timestamp = '1970-01-01 12:34:56';
1402 $hold->timestamp($previous_timestamp)->store;
1404 $hold = Koha::Holds->find($reserve_id);
1405 is( $hold->timestamp, $previous_timestamp, 'Make sure the previous timestamp has been used' );
1408 my $reserve_mock = Test::MockModule->new('C4::Reserves');
1409 $reserve_mock->mock( '_koha_notify_reserve', undef );
1412 ModReserveAffect( $item->itemnumber, $patron->borrowernumber );
1414 $hold->discard_changes;
1415 ok( $hold->is_waiting, 'Hold has been set waiting' );
1416 isnt( $hold->timestamp, $previous_timestamp, 'The timestamp has been modified' );
1418 my $log = Koha::ActionLogs->search({ module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id })->next;
1419 my $expected = sprintf q{'timestamp' => '%s'}, $hold->timestamp;
1420 like( $log->info, qr{$expected}, 'Timestamp logged is the current one' );
1423 sub count_hold_print_messages {
1424 my $message_count = $dbh->selectall_arrayref(q{
1427 WHERE letter_code = 'HOLD'
1428 AND message_transport_type = 'print'
1430 return $message_count->[0]->[0];
1433 sub place_item_hold {
1434 my ($patron,$item,$library,$priority) = @_;
1436 my $hold_id = C4::Reserves::AddReserve(
1438 branchcode => $library->branchcode,
1439 borrowernumber => $patron->borrowernumber,
1440 biblionumber => $item->biblionumber,
1441 priority => $priority,
1442 title => "title for fee",
1443 itemnumber => $item->itemnumber,
1447 my $hold = Koha::Holds->find($hold_id);
1451 # we reached the finish
1452 $schema->storage->txn_rollback();
1454 subtest 'IsAvailableForItemLevelRequest() tests' => sub {
1458 $schema->storage->txn_begin;
1460 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1462 my $item_type = undef;
1464 my $item_mock = Test::MockModule->new('Koha::Item');
1465 $item_mock->mock( 'effective_itemtype', sub { return $item_type; } );
1467 my $item = $builder->build_sample_item;
1470 !C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ),
1471 "Item not available for item-level hold because no effective item type"
1474 # Weird use case to highlight issue
1476 Koha::ItemTypes->search( { itemtype => $item_type } )->delete;
1477 my $itemtype = $builder->build_object(
1479 class => 'Koha::ItemTypes',
1480 value => { itemtype => $item_type }
1484 C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ),
1485 "Item not available for item-level hold because no effective item type"
1488 Koha::CirculationRules->set_rules(
1490 categorycode => '*',
1498 my $item_1 = $builder->build_sample_item( { notforloan => -1 } );
1500 C4::Reserves::IsAvailableForItemLevelRequest( $item_1, $patron ),
1501 "We can placing hold on item with negative not for loan values when 'On shelf holds allowed' is set to 'If any unavailable'"
1503 $schema->storage->txn_rollback;
1506 subtest 'AddReserve() tests' => sub {
1510 $schema->storage->txn_begin;
1512 t::lib::Mocks::mock_preference( 'TrackLastPatronActivityTriggers', 'hold' );
1514 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1515 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { lastseen => undef } } );
1516 my $biblio = $builder->build_sample_biblio;
1518 my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1519 $mock->mock( 'enqueue', sub {
1520 my ( $self, $args ) = @_;
1522 $args->{biblio_ids},
1524 "AddReserve triggers a holds queue update for the related biblio"
1528 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1532 branchcode => $library->branchcode,
1533 borrowernumber => $patron->id,
1534 biblionumber => $biblio->id,
1538 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1542 branchcode => $library->branchcode,
1543 borrowernumber => $patron->id,
1544 biblionumber => $biblio->id,
1548 $patron->discard_changes;
1549 isnt( $patron->lastseen, undef, "Patron activity tracked when hold is a valid trigger" );
1551 $schema->storage->txn_rollback;
1554 subtest 'AlterPriorty() tests' => sub {
1558 $schema->storage->txn_begin;
1560 my $library = $builder->build_object({ class => 'Koha::Libraries' });
1561 my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' });
1562 my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
1563 my $patron_3 = $builder->build_object({ class => 'Koha::Patrons' });
1564 my $biblio = $builder->build_sample_biblio;
1566 my $reserve_id = AddReserve(
1568 branchcode => $library->branchcode,
1569 borrowernumber => $patron_1->id,
1570 biblionumber => $biblio->id,
1575 branchcode => $library->branchcode,
1576 borrowernumber => $patron_2->id,
1577 biblionumber => $biblio->id,
1582 branchcode => $library->branchcode,
1583 borrowernumber => $patron_3->id,
1584 biblionumber => $biblio->id,
1588 my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1589 $mock->mock( 'enqueue', sub {
1590 my ( $self, $args ) = @_;
1592 $args->{biblio_ids},
1594 "AlterPriority triggers a holds queue update for the related biblio"
1598 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1600 AlterPriority( "bottom", $reserve_id, 1, 2, 1, 3 );
1602 my $hold = Koha::Holds->find($reserve_id);
1604 is($hold->priority,3,'Successfully altered priority to bottom');
1606 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1608 AlterPriority( "bottom", $reserve_id, 1, 2, 1, 3 );
1610 $schema->storage->txn_rollback;
1613 subtest 'CanBookBeReserved() tests' => sub {
1617 $schema->storage->txn_begin;
1619 my $library = $builder->build_object(
1620 { class => 'Koha::Libraries', value => { pickup_location => 1 } } );
1621 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1622 my $itype = $builder->build_object( { class => 'Koha::ItemTypes' } );
1624 my $biblio = $builder->build_sample_biblio();
1625 my $item_1 = $builder->build_sample_item(
1626 { biblionumber => $biblio->id, itype => $itype->id } );
1627 my $item_2 = $builder->build_sample_item(
1628 { biblionumber => $biblio->id, itype => $itype->id } );
1630 Koha::CirculationRules->delete;
1631 Koha::CirculationRules->set_rules(
1633 branchcode => undef,
1634 categorycode => undef,
1637 holds_per_record => 100,
1641 Koha::CirculationRules->set_rules(
1643 branchcode => undef,
1644 categorycode => undef,
1645 itemtype => $itype->id,
1647 reservesallowed => 2,
1652 C4::Reserves::AddReserve(
1654 branchcode => $library->id,
1655 borrowernumber => $patron->id,
1656 biblionumber => $biblio->id,
1657 title => $biblio->title,
1658 itemnumber => $item_1->id
1662 ## Limit on item type is 2, only one hold, success tests
1664 my $res = CanBookBeReserved( $patron->id, $biblio->id, $library->id,
1665 { itemtype => $itype->id } );
1666 is_deeply( $res, { status => 'OK' },
1667 'Holds on itemtype limit not reached' );
1669 # Add a second hold, biblio-level and item type-constrained
1670 C4::Reserves::AddReserve(
1672 branchcode => $library->id,
1673 borrowernumber => $patron->id,
1674 biblionumber => $biblio->id,
1675 title => $biblio->title,
1676 itemtype => $itype->id,
1680 ## Limit on item type is 2, two holds, one of them biblio-level/item type-constrained
1682 $res = CanBookBeReserved( $patron->id, $biblio->id, $library->id,
1683 { itemtype => $itype->id } );
1684 is_deeply( $res, { status => '' }, 'Holds on itemtype limit reached' );
1686 $schema->storage->txn_rollback;
1689 subtest 'CanItemBeReserved() tests' => sub {
1693 $schema->storage->txn_begin;
1695 my $library = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } );
1696 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1697 my $itype = $builder->build_object( { class => 'Koha::ItemTypes' } );
1699 my $biblio = $builder->build_sample_biblio();
1700 my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->id, itype => $itype->id });
1701 my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->id, itype => $itype->id });
1703 Koha::CirculationRules->delete;
1704 Koha::CirculationRules->set_rules(
1705 { branchcode => undef,
1706 categorycode => undef,
1709 holds_per_record => 100,
1713 Koha::CirculationRules->set_rules(
1714 { branchcode => undef,
1715 categorycode => undef,
1716 itemtype => $itype->id,
1718 reservesallowed => 2,
1723 C4::Reserves::AddReserve(
1725 branchcode => $library->id,
1726 borrowernumber => $patron->id,
1727 biblionumber => $biblio->id,
1728 title => $biblio->title,
1729 itemnumber => $item_1->id
1733 ## Limit on item type is 2, only one hold, success tests
1735 my $res = CanItemBeReserved( $patron, $item_2, $library->id );
1736 is_deeply( $res, { status => 'OK' }, 'Holds on itemtype limit not reached' );
1738 # Add a second hold, biblio-level and item type-constrained
1739 C4::Reserves::AddReserve(
1741 branchcode => $library->id,
1742 borrowernumber => $patron->id,
1743 biblionumber => $biblio->id,
1744 title => $biblio->title,
1745 itemtype => $itype->id,
1749 ## Limit on item type is 2, two holds, one of them biblio-level/item type-constrained
1751 $res = CanItemBeReserved( $patron, $item_2, $library->id );
1752 is_deeply( $res, { status => 'tooManyReserves', limit => 2 }, 'Holds on itemtype limit reached' );
1754 $schema->storage->txn_rollback;
1757 subtest 'DefaultHoldExpiration tests' => sub {
1759 $schema->storage->txn_begin;
1761 t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdate', 1 );
1762 t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdatePeriod', 365 );
1763 t::lib::Mocks::mock_preference( 'DefaultHoldExpirationUnitOfTime', 'days;' );
1765 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1766 my $item = $builder->build_sample_item();
1768 my $reserve_id = AddReserve({
1769 branchcode => $item->homebranch,
1770 borrowernumber => $patron->id,
1771 biblionumber => $item->biblionumber,
1774 my $today = dt_from_string();
1775 my $hold = Koha::Holds->find( $reserve_id );
1777 is( $hold->reservedate, $today->ymd, "Hold created today" );
1778 is( $hold->expirationdate, $today->add( days => 365)->ymd, "Reserve date set 1 year from today" );
1780 $schema->txn_rollback;
1783 subtest '_Findgroupreserves' => sub {
1785 $schema->storage->txn_begin;
1787 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } );
1788 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } );
1789 my $item = $builder->build_sample_item();
1790 my $item_2 = $builder->build_sample_item( { biblionumber => $item->biblionumber } );
1792 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1793 my $reserve_id_1 = AddReserve(
1795 branchcode => $item->homebranch,
1796 borrowernumber => $patron_1->id,
1797 biblionumber => $item->biblionumber,
1800 my $reserve_id_2 = AddReserve(
1802 branchcode => $item->homebranch,
1803 borrowernumber => $patron_2->id,
1804 biblionumber => $item->biblionumber,
1808 C4::HoldsQueue::AddToHoldTargetMap(
1811 borrowernumber => $patron_1->id, biblionumber => $item->biblionumber,
1812 holdingbranch => $item->holdingbranch, item_level => 0, reserve_id => $reserve_id_1
1817 # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1818 my @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item->id, 0, [] );
1819 is( scalar @reserves, 1, "We should only get the hold that is in the map" );
1820 is( $reserves[0]->{reserve_id}, $reserve_id_1, "We got the expected reserve" );
1822 C4::HoldsQueue::AddToHoldTargetMap(
1825 borrowernumber => $patron_2->id, biblionumber => $item->biblionumber,
1826 holdingbranch => $item->holdingbranch, item_level => 1, reserve_id => $reserve_id_2
1831 # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1832 @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item_2->id, 0, [] );
1833 is( scalar @reserves, 1, "We should only get the item level hold that is in the map" );
1834 is( $reserves[0]->{reserve_id}, $reserve_id_2, "We got the expected reserve" );
1836 C4::HoldsQueue::AddToHoldTargetMap(
1839 borrowernumber => $patron_2->id, biblionumber => $item->biblionumber,
1840 holdingbranch => $item->holdingbranch, item_level => 1, reserve_id => $reserve_id_1
1845 # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1846 @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item_2->id, 0, [] );
1847 is( scalar @reserves, 1, "We should still only get the item level hold that is in the map" );
1848 is( $reserves[0]->{reserve_id}, $reserve_id_1, "We got the expected reserve which has been updated" );
1852 $schema->txn_rollback;
1855 subtest 'HOLDDGST tests' => sub {
1858 $schema->storage->txn_begin;
1860 my $branch = $builder->build_object(
1862 class => 'Koha::Libraries',
1864 branchemail => 'branch@e.mail',
1865 branchreplyto => 'branch@reply.to',
1866 pickup_location => 1
1870 my $item = $builder->build_sample_item(
1872 homebranch => $branch->branchcode,
1873 holdingbranch => $branch->branchcode
1876 my $item2 = $builder->build_sample_item(
1878 homebranch => $branch->branchcode,
1879 holdingbranch => $branch->branchcode
1883 my $wants_hold_and_email = {
1884 wants_digest => '1',
1887 email => 'HOLDDGST',
1889 letter_code => 'HOLDDGST'
1892 my $mp = Test::MockModule->new('C4::Members::Messaging');
1894 $mp->mock( "GetMessagingPreferences", $wants_hold_and_email );
1896 $dbh->do('DELETE FROM letter');
1898 my $email_hold_notice = $builder->build(
1902 message_transport_type => 'email',
1905 module => 'reserves',
1911 my $sms_hold_notice = $builder->build(
1915 message_transport_type => 'sms',
1918 module => 'reserves',
1924 my $hold_borrower = $builder->build(
1926 source => 'Borrower',
1928 smsalertnumber => '5555555551',
1932 )->{borrowernumber};
1934 C4::Reserves::AddReserve(
1936 branchcode => $item->homebranch,
1937 borrowernumber => $hold_borrower,
1938 biblionumber => $item->biblionumber,
1942 C4::Reserves::AddReserve(
1944 branchcode => $item2->homebranch,
1945 borrowernumber => $hold_borrower,
1946 biblionumber => $item2->biblionumber,
1950 ModReserveAffect( $item->itemnumber, $hold_borrower, 0 );
1951 ModReserveAffect( $item2->itemnumber, $hold_borrower, 0 );
1953 my $sms_count = $schema->resultset('MessageQueue')->search(
1955 letter_code => 'HOLDDGST',
1956 message_transport_type => 'sms',
1957 borrowernumber => $hold_borrower,
1960 is( $sms_count, 1, "Only one sms hold digest message created for two holds" );
1962 my $email_count = $schema->resultset('MessageQueue')->search(
1964 letter_code => 'HOLDDGST',
1965 message_transport_type => 'email',
1966 borrowernumber => $hold_borrower,
1969 is( $email_count, 1, "Only one email hold digest message created for two holds" );
1971 $schema->txn_rollback;