Bug 34678: Unit test
[koha.git] / t / db_dependent / Reserves.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
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.
9 #
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.
14 #
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>.
17
18 use Modern::Perl;
19
20 use Test::More tests => 78;
21 use Test::MockModule;
22 use Test::Warn;
23
24 use t::lib::Mocks;
25 use t::lib::TestBuilder;
26
27 use MARC::Record;
28 use DateTime::Duration;
29
30 use C4::Circulation qw( AddReturn AddIssue );
31 use C4::Items;
32 use C4::Biblio qw( GetMarcFromKohaField ModBiblio );
33 use C4::HoldsQueue;
34 use C4::Members;
35 use C4::Reserves qw( AddReserve AlterPriority CheckReserves GetReservesControlBranch ModReserve ModReserveAffect ReserveSlip CalculatePriority CanReserveBeCanceledFromOpac CanBookBeReserved IsAvailableForItemLevelRequest MoveReserve ChargeReserveFee RevertWaitingStatus CanItemBeReserved MergeHolds );
36 use Koha::ActionLogs;
37 use Koha::Biblios;
38 use Koha::Caches;
39 use Koha::DateUtils qw( dt_from_string output_pref );
40 use Koha::Holds;
41 use Koha::Items;
42 use Koha::Libraries;
43 use Koha::Notice::Templates;
44 use Koha::Patrons;
45 use Koha::Patron::Categories;
46 use Koha::CirculationRules;
47
48 BEGIN {
49     require_ok('C4::Reserves');
50 }
51
52 # Start transaction
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');
58
59 my $builder = t::lib::TestBuilder->new;
60
61 my $frameworkcode = q//;
62
63
64 t::lib::Mocks::mock_preference('ReservesNeedReturns', 1);
65
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");
72
73 ## Setup Test
74 # Add branches
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 };
78 # Add categories
79 my $category_1 = $builder->build({ source => 'Category' })->{ categorycode };
80 my $category_2 = $builder->build({ source => 'Category' })->{ categorycode };
81 # Add an item type
82 my $itemtype = $builder->build(
83     { source => 'Itemtype', value => { notforloan => undef } } )->{itemtype};
84
85 t::lib::Mocks::mock_userenv({ branchcode => $branch_1 });
86
87 my $bibnum = $builder->build_sample_biblio({frameworkcode => $frameworkcode})->biblionumber;
88
89 # Create a helper item instance for testing
90 my $item = $builder->build_sample_item({ biblionumber => $bibnum, library => $branch_1, itype => $itemtype });
91
92 my $biblio_with_no_item = $builder->build_sample_biblio;
93
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?
97
98
99 # Create a borrower
100 my %data = (
101     firstname =>  'my firstname',
102     surname => 'my surname',
103     categorycode => $category_1,
104     branchcode => $branch_1,
105 );
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;
111
112 my $branchcode = Koha::Libraries->search->next->branchcode;
113
114 AddReserve(
115     {
116         branchcode     => $branchcode,
117         borrowernumber => $borrowernumber,
118         biblionumber   => $biblionumber,
119         priority       => 1,
120     }
121 );
122
123 my ($status, $reserve, $all_reserves) = CheckReserves( $item );
124
125 is($status, "Reserved", "CheckReserves Test 1");
126
127 ok(exists($reserve->{reserve_id}), 'CheckReserves() include reserve_id in its response');
128
129 ($status, $reserve, $all_reserves) = CheckReserves( $item );
130 is($status, "Reserved", "CheckReserves Test 2");
131
132 my $ReservesControlBranch = C4::Context->preference('ReservesControlBranch');
133 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
134 ok(
135     'ItemHomeLib' eq GetReservesControlBranch(
136         { homebranch => 'ItemHomeLib' },
137         { branchcode => 'PatronHomeLib' }
138     ), "GetReservesControlBranch returns item home branch when set to ItemHomeLibrary"
139 );
140 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
141 ok(
142     'PatronHomeLib' eq GetReservesControlBranch(
143         { homebranch => 'ItemHomeLib' },
144         { branchcode => 'PatronHomeLib' }
145     ), "GetReservesControlBranch returns patron home branch when set to PatronLibrary"
146 );
147 t::lib::Mocks::mock_preference( 'ReservesControlBranch', $ReservesControlBranch );
148
149 ###
150 ### Regression test for bug 10272
151 ###
152 my %requesters = ();
153 $requesters{$branch_1} = Koha::Patron->new({
154     branchcode   => $branch_1,
155     categorycode => $category_2,
156     surname      => "borrower from $branch_1",
157 })->store->borrowernumber;
158 for my $i ( 2 .. 5 ) {
159     $requesters{"CPL$i"} = Koha::Patron->new({
160         branchcode   => $branch_1,
161         categorycode => $category_2,
162         surname      => "borrower $i from $branch_1",
163     })->store->borrowernumber;
164 }
165 $requesters{$branch_2} = Koha::Patron->new({
166     branchcode   => $branch_2,
167     categorycode => $category_2,
168     surname      => "borrower from $branch_2",
169 })->store->borrowernumber;
170 $requesters{$branch_3} = Koha::Patron->new({
171     branchcode   => $branch_3,
172     categorycode => $category_2,
173     surname      => "borrower from $branch_3",
174 })->store->borrowernumber;
175
176 # Configure rules so that $branch_1 allows only $branch_1 patrons
177 # to request its items, while $branch_2 will allow its items
178 # to fill holds from anywhere.
179
180 $dbh->do('DELETE FROM circulation_rules');
181 Koha::CirculationRules->set_rules(
182     {
183         branchcode   => undef,
184         categorycode => undef,
185         itemtype     => undef,
186         rules        => {
187             reservesallowed => 25,
188             holds_per_record => 1,
189         }
190     }
191 );
192
193 # CPL allows only its own patrons to request its items
194 Koha::CirculationRules->set_rules(
195     {
196         branchcode   => $branch_1,
197         itemtype     => undef,
198         rules        => {
199             holdallowed  => 'from_home_library',
200             returnbranch => 'homebranch',
201         }
202     }
203 );
204
205 # ... while FPL allows anybody to request its items
206 Koha::CirculationRules->set_rules(
207     {
208         branchcode   => $branch_2,
209         itemtype     => undef,
210         rules        => {
211             holdallowed  => 'from_any_library',
212             returnbranch => 'homebranch',
213         }
214     }
215 );
216
217 my $bibnum2 = $builder->build_sample_biblio({frameworkcode => $frameworkcode})->biblionumber;
218
219 my ($itemnum_cpl, $itemnum_fpl);
220 $itemnum_cpl = $builder->build_sample_item(
221     {
222         biblionumber => $bibnum2,
223         library      => $branch_1,
224         barcode      => 'bug10272_CPL',
225         itype        => $itemtype
226     }
227 )->itemnumber;
228 $itemnum_fpl = $builder->build_sample_item(
229     {
230         biblionumber => $bibnum2,
231         library      => $branch_2,
232         barcode      => 'bug10272_FPL',
233         itype        => $itemtype
234     }
235 )->itemnumber;
236
237 # Ensure that priorities are numbered correcly when a hold is moved to waiting
238 # (bug 11947)
239 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
240 AddReserve(
241     {
242         branchcode     => $branch_3,
243         borrowernumber => $requesters{$branch_3},
244         biblionumber   => $bibnum2,
245         priority       => 1,
246     }
247 );
248 AddReserve(
249     {
250         branchcode     => $branch_2,
251         borrowernumber => $requesters{$branch_2},
252         biblionumber   => $bibnum2,
253         priority       => 2,
254     }
255 );
256 AddReserve(
257     {
258         branchcode     => $branch_1,
259         borrowernumber => $requesters{$branch_1},
260         biblionumber   => $bibnum2,
261         priority       => 3,
262     }
263 );
264 ModReserveAffect($itemnum_cpl, $requesters{$branch_3}, 0);
265
266 # Now it should have different priorities.
267 my $biblio = Koha::Biblios->find( $bibnum2 );
268 my $holds = $biblio->holds({}, { order_by => 'reserve_id' });;
269 is($holds->next->priority, 0, 'Item is correctly waiting');
270 is($holds->next->priority, 1, 'Item is correctly priority 1');
271 is($holds->next->priority, 2, 'Item is correctly priority 2');
272
273 my @reserves = Koha::Holds->search({ borrowernumber => $requesters{$branch_3} })->waiting->as_list;
274 is( @reserves, 1, 'GetWaiting got only the waiting reserve' );
275 is( $reserves[0]->borrowernumber(), $requesters{$branch_3}, 'GetWaiting got the reserve for the correct borrower' );
276
277
278 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
279 AddReserve(
280     {
281         branchcode     => $branch_3,
282         borrowernumber => $requesters{$branch_3},
283         biblionumber   => $bibnum2,
284         priority       => 1,
285     }
286 );
287 AddReserve(
288     {
289         branchcode     => $branch_2,
290         borrowernumber => $requesters{$branch_2},
291         biblionumber   => $bibnum2,
292         priority       => 2,
293     }
294 );
295
296 AddReserve(
297     {
298         branchcode     => $branch_1,
299         borrowernumber => $requesters{$branch_1},
300         biblionumber   => $bibnum2,
301         priority       => 3,
302     }
303 );
304
305 # Ensure that the item's home library controls hold policy lookup
306 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
307
308 my $messages;
309 # Return the CPL item at FPL.  The hold that should be triggered is
310 # the one placed by the CPL patron, as the other two patron's hold
311 # requests cannot be filled by that item per policy.
312 (undef, $messages, undef, undef) = AddReturn('bug10272_CPL', $branch_2);
313 is( $messages->{ResFound}->{borrowernumber},
314     $requesters{$branch_1},
315     'restrictive library\'s items only fill requests by own patrons (bug 10272)');
316
317 # Return the FPL item at FPL.  The hold that should be triggered is
318 # the one placed by the RPL patron, as that patron is first in line
319 # and RPL imposes no restrictions on whose holds its items can fill.
320
321 # Ensure that the preference 'LocalHoldsPriority' is not set (Bug 15244):
322 t::lib::Mocks::mock_preference( 'LocalHoldsPriority', '' );
323
324 (undef, $messages, undef, undef) = AddReturn('bug10272_FPL', $branch_2);
325 is( $messages->{ResFound}->{borrowernumber},
326     $requesters{$branch_3},
327     'for generous library, its items fill first hold request in line (bug 10272)');
328
329 $biblio = Koha::Biblios->find( $biblionumber );
330 $holds = $biblio->holds;
331 is($holds->count, 1, "Only one reserves for this biblio");
332 $holds->next->reserve_id;
333
334 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
335 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
336 # Test 9761a: Add a reserve without date, CheckReserve should return it
337 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
338 AddReserve(
339     {
340         branchcode     => $branch_1,
341         borrowernumber => $requesters{$branch_1},
342         biblionumber   => $bibnum,
343         priority       => 1,
344     }
345 );
346 ($status)=CheckReserves( $item );
347 is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead');
348 ($status)=CheckReserves( $item, 7 );
349 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
350
351 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
352 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
353 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
354 my $resdate= dt_from_string();
355 $resdate->add_duration(DateTime::Duration->new(days => 4));
356 my $reserve_id = AddReserve(
357     {
358         branchcode       => $branch_1,
359         borrowernumber   => $requesters{$branch_1},
360         biblionumber     => $bibnum,
361         priority         => 1,
362         reservation_date => $resdate,
363     }
364 );
365 ($status)=CheckReserves( $item );
366 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
367
368 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
369 ($status)=CheckReserves( $item, 3 );
370 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
371 ($status)=CheckReserves( $item, 4 );
372 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
373
374 # Test 9761d: Check ResFound message of AddReturn for future hold
375 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
376 # In this test we do not need an issued item; it is just a 'checkin'
377 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
378 (my $doreturn, $messages)= AddReturn($testbarcode,$branch_1);
379 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
380 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 3);
381 ($doreturn, $messages)= AddReturn($testbarcode,$branch_1);
382 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
383 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 7);
384 ($doreturn, $messages)= AddReturn($testbarcode,$branch_1);
385 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
386
387 my $now_holder = $builder->build_object({ class => 'Koha::Patrons', value => {
388     branchcode       => $branch_1,
389 }});
390 my $now_reserve_id = AddReserve(
391     {
392         branchcode       => $branch_1,
393         borrowernumber   => $requesters{$branch_1},
394         biblionumber     => $bibnum,
395         priority         => 2,
396         reservation_date => dt_from_string(),
397     }
398 );
399 my $which_highest;
400 ($status,$which_highest)=CheckReserves( $item, 3 );
401 is( $which_highest->{reserve_id}, $now_reserve_id, 'CheckReserves returns lower priority current reserve with insufficient lookahead');
402 ($status, $which_highest)=CheckReserves( $item, 4 );
403 is( $which_highest->{reserve_id}, $reserve_id, 'CheckReserves returns higher priority future reserve with sufficient lookahead');
404 ModReserve({ reserve_id => $now_reserve_id, rank => 'del', cancellation_reason => 'test reserve' });
405
406
407 # End of tests for bug 9761 (ConfirmFutureHolds)
408
409
410 # test marking a hold as captured
411 my $hold_notice_count = count_hold_print_messages();
412 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
413 my $new_count = count_hold_print_messages();
414 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
415
416 # test that duplicate notices aren't generated
417 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
418 $new_count = count_hold_print_messages();
419 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
420
421 # avoiding the not_same_branch error
422 t::lib::Mocks::mock_preference('IndependentBranches', 0);
423 $item = Koha::Items->find($item->itemnumber);
424 is(
425     @{$item->safe_delete->messages}[0]->message,
426     'book_reserved',
427     'item that is captured to fill a hold cannot be deleted',
428 );
429
430 my $letter = ReserveSlip( { branchcode => $branch_1, reserve_id => $reserve_id } );
431 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
432
433 # Tests for bug 9788: Does Koha::Item->current_holds return a future wait?
434 # 9788a: current_holds does not return future next available hold
435 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
436 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
437 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
438 $resdate= dt_from_string();
439 $resdate->add_duration(DateTime::Duration->new(days => 2));
440 AddReserve(
441     {
442         branchcode       => $branch_1,
443         borrowernumber   => $requesters{$branch_1},
444         biblionumber     => $bibnum,
445         priority         => 1,
446         reservation_date => $resdate,
447     }
448 );
449
450 $holds = $item->current_holds;
451 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
452 my $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
453 is( $future_holds->count, 0, 'current_holds does not return a future next available hold');
454 # 9788b: current_holds does not return future item level hold
455 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
456 AddReserve(
457     {
458         branchcode       => $branch_1,
459         borrowernumber   => $requesters{$branch_1},
460         biblionumber     => $bibnum,
461         priority         => 1,
462         reservation_date => $resdate,
463         itemnumber       => $item->itemnumber,
464     }
465 ); #item level hold
466 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
467 is( $future_holds->count, 0, 'current_holds does not return a future item level hold' );
468 # 9788c: current_holds returns future wait (confirmed future hold)
469 ModReserveAffect( $item->itemnumber,  $requesters{$branch_1} , 0); #confirm hold
470 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
471 is( $future_holds->count, 1, 'current_holds returns a future wait (confirmed future hold)' );
472 # End of tests for bug 9788
473
474 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
475 # Tests for CalculatePriority (bug 8918)
476 my $p = C4::Reserves::CalculatePriority($bibnum2);
477 is($p, 4, 'CalculatePriority should now return priority 4');
478 AddReserve(
479     {
480         branchcode     => $branch_1,
481         borrowernumber => $requesters{'CPL2'},
482         biblionumber   => $bibnum2,
483         priority       => $p,
484     }
485 );
486 $p = C4::Reserves::CalculatePriority($bibnum2);
487 is($p, 5, 'CalculatePriority should now return priority 5');
488 #some tests on bibnum
489 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
490 $p = C4::Reserves::CalculatePriority($bibnum);
491 is($p, 1, 'CalculatePriority should now return priority 1');
492 #add a new reserve and confirm it to waiting
493 AddReserve(
494     {
495         branchcode     => $branch_1,
496         borrowernumber => $requesters{$branch_1},
497         biblionumber   => $bibnum,
498         priority       => $p,
499         itemnumber     => $item->itemnumber,
500     }
501 );
502 $p = C4::Reserves::CalculatePriority($bibnum);
503 is($p, 2, 'CalculatePriority should now return priority 2');
504 ModReserveAffect( $item->itemnumber,  $requesters{$branch_1} , 0);
505 $p = C4::Reserves::CalculatePriority($bibnum);
506 is($p, 1, 'CalculatePriority should now return priority 1');
507 #add another biblio hold, no resdate
508 AddReserve(
509     {
510         branchcode     => $branch_1,
511         borrowernumber => $requesters{'CPL2'},
512         biblionumber   => $bibnum,
513         priority       => $p,
514     }
515 );
516 $p = C4::Reserves::CalculatePriority($bibnum);
517 is($p, 2, 'CalculatePriority should now return priority 2');
518 #add another future hold
519 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
520 $resdate= dt_from_string();
521 $resdate->add_duration(DateTime::Duration->new(days => 1));
522 AddReserve(
523     {
524         branchcode     => $branch_1,
525         borrowernumber => $requesters{'CPL2'},
526         biblionumber   => $bibnum,
527         priority       => $p,
528         reservation_date => $resdate,
529     }
530 );
531 $p = C4::Reserves::CalculatePriority($bibnum);
532 is($p, 2, 'CalculatePriority should now still return priority 2');
533 #calc priority with future resdate
534 $p = C4::Reserves::CalculatePriority($bibnum, $resdate);
535 is($p, 3, 'CalculatePriority should now return priority 3');
536 # End of tests for bug 8918
537
538 # regression test for bug 12630
539 # Now there are 2 reserves on $bibnum
540 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
541 my $bor_tmp_1 = $builder->build_object({ class => 'Koha::Patrons',value =>{
542     firstname =>  'my firstname tmp 1',
543     surname => 'my surname tmp 1',
544     categorycode => 'S',
545     branchcode => 'CPL',
546 }});
547 my $bor_tmp_2 = $builder->build_object({ class => 'Koha::Patrons',value =>{
548     firstname =>  'my firstname tmp 2',
549     surname => 'my surname tmp 2',
550     categorycode => 'S',
551     branchcode => 'CPL',
552 }});
553 my $borrowernumber_tmp_1 = $bor_tmp_1->borrowernumber;
554 my $borrowernumber_tmp_2 = $bor_tmp_2->borrowernumber;
555 my $date_in_future = dt_from_string();
556 $date_in_future = $date_in_future->add_duration(DateTime::Duration->new(days => 1));
557 AddReserve({
558     branchcode => 'CPL',
559     borrowernumber => $borrowernumber_tmp_1,
560     biblionumber => $bibnum,
561     priority => 3,
562     reservation_date => $date_in_future
563 });
564 AddReserve({
565     branchcode => 'CPL',
566     borrowernumber => $borrowernumber_tmp_2,
567     biblionumber => $bibnum,
568     priority => 4,
569     reservation_date => $date_in_future
570 });
571 my @r1 = Koha::Holds->search({ borrowernumber => $borrowernumber_tmp_1 })->as_list;
572 my @r2 = Koha::Holds->search({ borrowernumber => $borrowernumber_tmp_2 })->as_list;
573 is( $r1[0]->priority, 3, 'priority for hold in future should be correct');
574 is( $r2[0]->priority, 4, 'priority for hold not in future should be correct');
575 # end of tests for bug 12630
576
577 # Tests for cancel reserves by users from OPAC.
578 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
579 AddReserve(
580     {
581         branchcode     => $branch_1,
582         borrowernumber => $requesters{$branch_1},
583         biblionumber   => $bibnum,
584         priority       => 1,
585     }
586 );
587 my (undef, $canres, undef) = CheckReserves( $item );
588
589 is( CanReserveBeCanceledFromOpac(), undef,
590     'CanReserveBeCanceledFromOpac should return undef if called without any parameter'
591 );
592 is(
593     CanReserveBeCanceledFromOpac( $canres->{resserve_id} ),
594     undef,
595     'CanReserveBeCanceledFromOpac should return undef if called without the reserve_id'
596 );
597 is(
598     CanReserveBeCanceledFromOpac( undef, $requesters{CPL} ),
599     undef,
600     'CanReserveBeCanceledFromOpac should return undef if called without borrowernumber'
601 );
602
603 my $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
604 is($cancancel, 1, 'Can user cancel its own reserve');
605
606 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_2});
607 is($cancancel, 0, 'Other user cant cancel reserve');
608
609 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 1);
610 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
611 is($cancancel, 0, 'Reserve in transfer status cant be canceled');
612
613 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
614 is( CanReserveBeCanceledFromOpac($canres->{resserve_id}, $requesters{$branch_1}), undef,
615     'Cannot cancel a deleted hold' );
616
617 AddReserve(
618     {
619         branchcode     => $branch_1,
620         borrowernumber => $requesters{$branch_1},
621         biblionumber   => $bibnum,
622         priority       => 1,
623     }
624 );
625 (undef, $canres, undef) = CheckReserves( $item );
626
627 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
628 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
629 is($cancancel, 0, 'Reserve in waiting status cant be canceled');
630
631 # End of tests for bug 12876
632
633        ####
634 ####### Testing Bug 13113 - Prevent juvenile/children from reserving ageRestricted material >>>
635        ####
636
637 t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' );
638
639 #Reserving an not-agerestricted Biblio by a Borrower with no dateofbirth is tested previously.
640
641 #Set the ageRestriction for the Biblio
642 $biblio = Koha::Biblios->find($bibnum);
643 my $record = $biblio->metadata->record;
644 my ( $ageres_tagid, $ageres_subfieldid ) = GetMarcFromKohaField( "biblioitems.agerestriction" );
645 $record->append_fields(  MARC::Field->new($ageres_tagid, '', '', $ageres_subfieldid => 'PEGI 16')  );
646 C4::Biblio::ModBiblio( $record, $bibnum, $frameworkcode );
647
648 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'OK', "Reserving an ageRestricted Biblio without a borrower dateofbirth succeeds" );
649
650 #Set the dateofbirth for the Borrower making them "too young".
651 $borrower->{dateofbirth} = DateTime->now->add( years => -15 );
652 Koha::Patrons->find( $borrowernumber )->set({ dateofbirth => $borrower->{dateofbirth} })->store;
653
654 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'ageRestricted', "Reserving a 'PEGI 16' Biblio by a 15 year old borrower fails");
655
656 #Set the dateofbirth for the Borrower making them "too old".
657 $borrower->{dateofbirth} = DateTime->now->add( years => -30 );
658 Koha::Patrons->find( $borrowernumber )->set({ dateofbirth => $borrower->{dateofbirth} })->store;
659
660 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'OK', "Reserving a 'PEGI 16' Biblio by a 30 year old borrower succeeds");
661
662 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblio_with_no_item->biblionumber)->{status} , '', "Biblio with no item. Status is empty");
663        ####
664 ####### EO Bug 13113 <<<
665        ####
666
667 ok( C4::Reserves::IsAvailableForItemLevelRequest($item, $patron), "Reserving a book on item level" );
668
669 my $pickup_branch = $builder->build({ source => 'Branch' })->{ branchcode };
670 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits',  '1' );
671 t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' );
672 my $limit = Koha::Item::Transfer::Limit->new(
673     {
674         toBranch   => $pickup_branch,
675         fromBranch => $item->holdingbranch,
676         itemtype   => $item->effective_itemtype,
677     }
678 )->store();
679 is( C4::Reserves::IsAvailableForItemLevelRequest($item, $patron, $pickup_branch), 0, "Item level request not available due to transfer limit" );
680 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits',  '0' );
681
682 my $categorycode = $borrower->{categorycode};
683 my $holdingbranch = $item->{holdingbranch};
684 Koha::CirculationRules->set_rules(
685     {
686         categorycode => $categorycode,
687         itemtype     => $item->effective_itemtype,
688         branchcode   => $holdingbranch,
689         rules => {
690             onshelfholds => 1,
691         }
692     }
693 );
694
695 # tests for MoveReserve in relation to ConfirmFutureHolds (BZ 14526)
696 #   hold from A pos 1, today, no fut holds: MoveReserve should fill it
697 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
698 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
699 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
700 AddReserve(
701     {
702         branchcode     => $branch_1,
703         borrowernumber => $borrowernumber,
704         biblionumber   => $bibnum,
705         priority       => 1,
706     }
707 );
708 MoveReserve( $item->itemnumber, $borrowernumber );
709 ($status)=CheckReserves( $item );
710 is( $status, '', 'MoveReserve filled hold');
711 #   hold from A waiting, today, no fut holds: MoveReserve should fill it
712 AddReserve(
713     {
714         branchcode     => $branch_1,
715         borrowernumber => $borrowernumber,
716         biblionumber   => $bibnum,
717         priority       => 1,
718         found          => 'W',
719     }
720 );
721 MoveReserve( $item->itemnumber, $borrowernumber );
722 ($status)=CheckReserves( $item );
723 is( $status, '', 'MoveReserve filled waiting hold');
724 #   hold from A pos 1, tomorrow, no fut holds: not filled
725 $resdate= dt_from_string();
726 $resdate->add_duration(DateTime::Duration->new(days => 1));
727 AddReserve(
728     {
729         branchcode     => $branch_1,
730         borrowernumber => $borrowernumber,
731         biblionumber   => $bibnum,
732         priority       => 1,
733         reservation_date => $resdate,
734     }
735 );
736 MoveReserve( $item->itemnumber, $borrowernumber );
737 ($status)=CheckReserves( $item, 1 );
738 is( $status, 'Reserved', 'MoveReserve did not fill future hold');
739 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
740 #   hold from A pos 1, tomorrow, fut holds=2: MoveReserve should fill it
741 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
742 AddReserve(
743     {
744         branchcode     => $branch_1,
745         borrowernumber => $borrowernumber,
746         biblionumber   => $bibnum,
747         priority       => 1,
748         reservation_date => $resdate,
749     }
750 );
751 MoveReserve( $item->itemnumber, $borrowernumber );
752 ($status)=CheckReserves( $item, undef, 2 );
753 is( $status, '', 'MoveReserve filled future hold now');
754 #   hold from A waiting, tomorrow, fut holds=2: MoveReserve should fill it
755 AddReserve(
756     {
757         branchcode     => $branch_1,
758         borrowernumber => $borrowernumber,
759         biblionumber   => $bibnum,
760         priority       => 1,
761         reservation_date => $resdate,
762     }
763 );
764 MoveReserve( $item->itemnumber, $borrowernumber );
765 ($status)=CheckReserves( $item, undef, 2 );
766 is( $status, '', 'MoveReserve filled future waiting hold now');
767 #   hold from A pos 1, today+3, fut holds=2: MoveReserve should not fill it
768 $resdate= dt_from_string();
769 $resdate->add_duration(DateTime::Duration->new(days => 3));
770 AddReserve(
771     {
772         branchcode     => $branch_1,
773         borrowernumber => $borrowernumber,
774         biblionumber   => $bibnum,
775         priority       => 1,
776         reservation_date => $resdate,
777     }
778 );
779 MoveReserve( $item->itemnumber, $borrowernumber );
780 ($status)=CheckReserves( $item, 3 );
781 is( $status, 'Reserved', 'MoveReserve did not fill future hold of 3 days');
782 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
783
784 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
785 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
786 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
787
788 subtest '_koha_notify_reserve() tests' => sub {
789
790     plan tests => 3;
791
792     my $branch = $builder->build_object({
793         class => 'Koha::Libraries',
794         value => {
795             branchemail => 'branch@e.mail',
796             branchreplyto => 'branch@reply.to',
797             pickup_location => 1
798         }
799     });
800     my $item = $builder->build_sample_item({
801         homebranch => $branch->branchcode,
802         holdingbranch => $branch->branchcode
803     });
804
805     my $wants_hold_and_email = {
806         wants_digest => '0',
807         transports => {
808             sms => 'HOLD',
809             email => 'HOLD',
810             },
811         letter_code => 'HOLD'
812     };
813
814     my $mp = Test::MockModule->new( 'C4::Members::Messaging' );
815
816     $mp->mock("GetMessagingPreferences",$wants_hold_and_email);
817
818     $dbh->do('DELETE FROM letter');
819
820     my $email_hold_notice = $builder->build({
821             source => 'Letter',
822             value => {
823                 message_transport_type => 'email',
824                 branchcode => '',
825                 code => 'HOLD',
826                 module => 'reserves',
827                 lang => 'default',
828             }
829         });
830
831     my $sms_hold_notice = $builder->build({
832             source => 'Letter',
833             value => {
834                 message_transport_type => 'sms',
835                 branchcode => '',
836                 code => 'HOLD',
837                 module => 'reserves',
838                 lang=>'default',
839             }
840         });
841
842     my $hold_borrower = $builder->build({
843             source => 'Borrower',
844             value => {
845                 smsalertnumber=>'5555555555',
846                 email=>'a@b.com',
847             }
848         })->{borrowernumber};
849
850     C4::Reserves::AddReserve(
851         {
852             branchcode     => $item->homebranch,
853             borrowernumber => $hold_borrower,
854             biblionumber   => $item->biblionumber,
855         }
856     );
857
858     ModReserveAffect($item->itemnumber, $hold_borrower, 0);
859     my $sms_message_address = $schema->resultset('MessageQueue')->search({
860             letter_code     => 'HOLD',
861             message_transport_type => 'sms',
862             borrowernumber => $hold_borrower,
863         })->next()->to_address();
864     is($sms_message_address, undef ,"We should not populate the sms message with the sms number, sending will do so");
865
866     my $email = $schema->resultset('MessageQueue')->search({
867             letter_code     => 'HOLD',
868             message_transport_type => 'email',
869             borrowernumber => $hold_borrower,
870         })->next();
871     my $email_to_address = $email->to_address();
872     is($email_to_address, undef ,"We should not populate the hold message with the email address, sending will do so");
873     my $email_from_address = $email->from_address();
874     is($email_from_address,'branch@e.mail',"Library's from address is used for sending");
875
876 };
877
878 subtest 'ReservesNeedReturns' => sub {
879     plan tests => 18;
880
881     my $library    = $builder->build_object( { class => 'Koha::Libraries' } );
882     my $item_info  = {
883         homebranch       => $library->branchcode,
884         holdingbranch    => $library->branchcode,
885     };
886     my $item = $builder->build_sample_item($item_info);
887     my $patron   = $builder->build_object(
888         {
889             class => 'Koha::Patrons',
890             value => { branchcode => $library->branchcode, }
891         }
892     );
893     my $patron_2   = $builder->build_object(
894         {
895             class => 'Koha::Patrons',
896             value => { branchcode => $library->branchcode, }
897         }
898     );
899
900     my $priority = 1;
901
902     t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Test with feature disabled
903     my $hold = place_item_hold( $patron, $item, $library, $priority );
904     is( $hold->priority, $priority, 'If ReservesNeedReturns is 1, priority must not have been set to changed' );
905     is( $hold->found, undef, 'If ReservesNeedReturns is 1, found must not have been set waiting' );
906     $hold->delete;
907
908     t::lib::Mocks::mock_preference('ReservesNeedReturns', 0); # '0' means 'Automatically mark a hold as found and waiting'
909     $hold = place_item_hold( $patron, $item, $library, $priority );
910     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
911     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
912     $hold->delete;
913
914     $item->onloan('2010-01-01')->store;
915     $hold = place_item_hold( $patron, $item, $library, $priority );
916     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item onloan priority must be set to 1' );
917     $hold->delete;
918
919     t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 0); # '0' means damaged holds not allowed
920     $item->onloan(undef)->damaged(1)->store;
921     $hold = place_item_hold( $patron, $item, $library, $priority );
922     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item damaged and not allowed holds on damaged items priority must be set to 1' );
923     $hold->delete;
924     t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 1); # '0' means damaged holds not allowed
925     $hold = place_item_hold( $patron, $item, $library, $priority );
926     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and damaged holds allowed, priority must have been set to 0' );
927     is( $hold->found,  'W', 'If ReservesNeedReturns is 0 and damaged holds allowed, found must have been set waiting' );
928     $hold->delete;
929
930     my $hold_1 = place_item_hold( $patron, $item, $library, $priority );
931     is( $hold_1->found,  'W', 'First hold on item is set to waiting with ReservesNeedReturns set to 0' );
932     is( $hold_1->priority, 0, 'First hold on item is set to waiting with ReservesNeedReturns set to 0' );
933     $hold = place_item_hold( $patron_2, $item, $library, $priority );
934     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item already on hold priority must be set to 1' );
935     $hold->delete;
936     $hold_1->delete;
937
938     my $transfer = $builder->build_object({
939         class => "Koha::Item::Transfers",
940         value => {
941           itemnumber  => $item->itemnumber,
942           datearrived => undef,
943           datecancelled => undef
944         }
945     });
946     $item->damaged(0)->store;
947     $hold = place_item_hold( $patron, $item, $library, $priority );
948     is( $hold->found, undef, 'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
949     is( $hold->priority, 1,  'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
950     $hold->delete;
951     $transfer->delete;
952
953     $hold = place_item_hold( $patron, $item, $library, $priority );
954     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
955     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
956     $hold_1 = place_item_hold( $patron, $item, $library, $priority );
957     is( $hold_1->priority, 1, 'If ReservesNeedReturns is 0 but item has a hold priority is 1' );
958     $hold_1->suspend(1)->store; # We suspend the hold
959     $hold->delete; # Delete the waiting hold
960     $hold = place_item_hold( $patron, $item, $library, $priority );
961     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and other hold(s) suspended, priority must have been set to 0' );
962     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and other  hold(s) suspended, found must have been set waiting' );
963
964
965
966
967     t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Don't affect other tests
968 };
969
970 subtest 'ChargeReserveFee tests' => sub {
971
972     plan tests => 8;
973
974     my $library = $builder->build_object({ class => 'Koha::Libraries' });
975     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
976
977     my $fee   = 20;
978     my $title = 'A title';
979
980     my $context = Test::MockModule->new('C4::Context');
981     $context->mock( userenv => { branch => $library->id } );
982
983     my $line = C4::Reserves::ChargeReserveFee( $patron->id, $fee, $title );
984
985     is( ref($line), 'Koha::Account::Line' , 'Returns a Koha::Account::Line object');
986     ok( $line->is_debit, 'Generates a debit line' );
987     is( $line->debit_type_code, 'RESERVE' , 'generates RESERVE debit_type');
988     is( $line->borrowernumber, $patron->id , 'generated line belongs to the passed patron');
989     is( $line->amount, $fee , 'amount set correctly');
990     is( $line->amountoutstanding, $fee , 'amountoutstanding set correctly');
991     is( $line->description, "$title" , 'description is title of reserved item');
992     is( $line->branchcode, $library->id , "Library id is picked from userenv and stored correctly" );
993 };
994
995 subtest 'reserves.item_level_hold' => sub {
996     plan tests => 2;
997
998     my $item   = $builder->build_sample_item;
999     my $patron = $builder->build_object(
1000         {
1001             class => 'Koha::Patrons',
1002             value => { branchcode => $item->homebranch }
1003         }
1004     );
1005
1006     subtest 'item level hold' => sub {
1007         plan tests => 3;
1008         my $reserve_id = AddReserve(
1009             {
1010                 branchcode     => $item->homebranch,
1011                 borrowernumber => $patron->borrowernumber,
1012                 biblionumber   => $item->biblionumber,
1013                 priority       => 1,
1014                 itemnumber     => $item->itemnumber,
1015             }
1016         );
1017
1018         my $hold = Koha::Holds->find($reserve_id);
1019         is( $hold->item_level_hold, 1, 'item_level_hold should be set when AddReserve is called with a specific item' );
1020
1021         # Mark it waiting
1022         ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
1023
1024         my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1025         $mock->mock( 'enqueue', sub {
1026             my ( $self, $args ) = @_;
1027             is_deeply(
1028                 $args->{biblio_ids},
1029                 [ $hold->biblionumber ],
1030                 "AlterPriority triggers a holds queue update for the related biblio"
1031             );
1032         } );
1033
1034         t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1035
1036         # Revert the waiting status
1037         C4::Reserves::RevertWaitingStatus(
1038             { itemnumber => $item->itemnumber } );
1039
1040         $hold = Koha::Holds->find($reserve_id);
1041
1042         is( $hold->itemnumber, $item->itemnumber, 'Itemnumber should not be removed when the waiting status is revert' );
1043
1044         t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1045
1046         $hold->set_waiting;
1047
1048         # Revert the waiting status, RealTimeHoldsQueue => shouldn't add a test
1049         C4::Reserves::RevertWaitingStatus(
1050             { itemnumber => $item->itemnumber } );
1051
1052         $hold->delete;    # cleanup
1053     };
1054
1055     subtest 'biblio level hold' => sub {
1056         plan tests => 3;
1057         my $reserve_id = AddReserve(
1058             {
1059                 branchcode     => $item->homebranch,
1060                 borrowernumber => $patron->borrowernumber,
1061                 biblionumber   => $item->biblionumber,
1062                 priority       => 1,
1063             }
1064         );
1065
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' );
1068
1069         # Mark it waiting
1070         ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
1071
1072         $hold = Koha::Holds->find($reserve_id);
1073         is( $hold->itemnumber, $item->itemnumber, 'Itemnumber should be set on hold confirmation' );
1074
1075         # Revert the waiting status
1076         C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1077
1078         $hold = Koha::Holds->find($reserve_id);
1079         is( $hold->itemnumber, undef, 'Itemnumber should be removed when the waiting status is revert' );
1080
1081         $hold->delete;
1082     };
1083
1084 };
1085
1086 subtest 'MoveReserve additional test' => sub {
1087
1088     plan tests => 4;
1089
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" });
1097
1098     # Place a hold on the title for both patrons
1099     my $reserve_1 = AddReserve(
1100         {
1101             branchcode     => $item_1->homebranch,
1102             borrowernumber => $patron_1->borrowernumber,
1103             biblionumber   => $biblio->biblionumber,
1104             priority       => 1,
1105             itemnumber     => $item_1->itemnumber,
1106         }
1107     );
1108     my $reserve_2 = AddReserve(
1109         {
1110             branchcode     => $item_2->homebranch,
1111             borrowernumber => $patron_2->borrowernumber,
1112             biblionumber   => $biblio->biblionumber,
1113             priority       => 1,
1114             itemnumber     => $item_1->itemnumber,
1115         }
1116     );
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");
1119
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));
1122
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");
1127
1128 };
1129
1130 subtest 'RevertWaitingStatus' => sub {
1131
1132     plan tests => 2;
1133
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(
1140         {
1141             biblionumber => $biblio->biblionumber,
1142             itype        => $itype->itemtype,
1143             library      => $library->branchcode
1144         }
1145     );
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" } );
1150
1151     # Place a hold on the title for both patrons
1152     my $priority = 1;
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 );
1157
1158     $hold_1->set_waiting;
1159     AddIssue( $patron_3->unblessed, $item_1->barcode, undef, 'revert' );
1160
1161     my $holds = $biblio->holds;
1162     is( $holds->count, 3, 'One hold has been deleted' );
1163     is_deeply(
1164         [
1165             $holds->next->priority, $holds->next->priority,
1166             $holds->next->priority
1167         ],
1168         [ 1, 2, 3 ],
1169         'priorities have been reordered'
1170     );
1171 };
1172
1173 subtest 'CheckReserves additional tests' => sub {
1174
1175     plan tests => 8;
1176
1177     my $item = $builder->build_sample_item;
1178     my $reserve1 = $builder->build_object(
1179         {
1180             class => "Koha::Holds",
1181             value => {
1182                 found            => undef,
1183                 priority         => 1,
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,
1192                 suspend          => 0,
1193                 itemtype         => undef,
1194             }
1195         }
1196     );
1197     my $reserve2 = $builder->build_object(
1198         {
1199             class => "Koha::Holds",
1200             value => {
1201                 found            => undef,
1202                 priority         => 2,
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,
1212                 suspend          => 0,
1213                 itemtype         => undef,
1214             }
1215         }
1216     );
1217
1218     my $tmp_holdsqueue = $builder->build(
1219         {
1220             source => 'TmpHoldsqueue',
1221             value  => {
1222                 borrowernumber => $reserve1->borrowernumber,
1223                 biblionumber   => $reserve1->biblionumber,
1224             }
1225         }
1226     );
1227     my $fill_target = $builder->build(
1228         {
1229             source => 'HoldFillTarget',
1230             value  => {
1231                 borrowernumber     => $reserve1->borrowernumber,
1232                 biblionumber       => $reserve1->biblionumber,
1233                 itemnumber         => $item->itemnumber,
1234                 item_level_request => 0,
1235             }
1236         }
1237     );
1238
1239     ModReserveAffect( $item->itemnumber, $reserve1->borrowernumber, 1,
1240         $reserve1->reserve_id );
1241     my ( $status, $matched_reserve, $possible_reserves ) =
1242       CheckReserves( $item );
1243
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' );
1248
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
1255     });
1256     Koha::CirculationRules->set_rules(
1257         {
1258             branchcode   => undef,
1259             categorycode => undef,
1260             itemtype     => $item_A->itype,
1261             rules        => {
1262                 reservesallowed => 25,
1263                 holds_per_record => 1,
1264             }
1265         }
1266     );
1267     Koha::CirculationRules->set_rule({
1268         branchcode => undef,
1269         itemtype   => $item_A->itype,
1270         rule_name  => 'holdallowed',
1271         rule_value => 'from_home_library'
1272     });
1273     my $reserve_id = AddReserve(
1274         {
1275             branchcode     => $patron_B->branchcode,
1276             borrowernumber => $patron_B->borrowernumber,
1277             biblionumber   => $item_A->biblionumber,
1278             priority       => 1,
1279             itemnumber     => undef,
1280         }
1281     );
1282
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'
1292     });
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");
1295
1296
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'
1306     });
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");
1309
1310 };
1311
1312 subtest 'AllowHoldOnPatronPossession test' => sub {
1313
1314     plan tests => 4;
1315
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 }});
1322
1323     C4::Circulation::AddIssue($patron->unblessed,
1324                               $item->barcode);
1325     t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 0);
1326
1327     is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1328                                        $item->biblionumber)->{status},
1329        'alreadypossession',
1330        'Patron cannot place hold on a book loaned to itself');
1331
1332     is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status},
1333        'alreadypossession',
1334        'Patron cannot place hold on an item loaned to itself');
1335
1336     t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 1);
1337
1338     is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1339                                        $item->biblionumber)->{status},
1340        'OK',
1341        'Patron can place hold on a book loaned to itself');
1342
1343     is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status},
1344        'OK',
1345        'Patron can place hold on an item loaned to itself');
1346 };
1347
1348 subtest 'MergeHolds' => sub {
1349
1350     plan tests => 1;
1351
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(
1358         {
1359             biblionumber => $biblio_1->biblionumber,
1360             itype        => $itype->itemtype,
1361             library      => $library->branchcode
1362         }
1363     );
1364     my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1365
1366     # Place a hold on $biblio_1
1367     my $priority = 1;
1368     place_item_hold( $patron_1, $item_1, $library, $priority );
1369
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' );
1373 };
1374
1375 subtest 'ModReserveAffect logging' => sub {
1376
1377     plan tests => 4;
1378
1379     my $item = $builder->build_sample_item;
1380     my $patron = $builder->build_object(
1381         {
1382             class => "Koha::Patrons",
1383             value => { branchcode => $item->homebranch }
1384         }
1385     );
1386
1387     t::lib::Mocks::mock_userenv({ patron => $patron });
1388     t::lib::Mocks::mock_preference('HoldsLog', 1);
1389
1390     my $reserve_id = AddReserve(
1391         {
1392             branchcode     => $item->homebranch,
1393             borrowernumber => $patron->borrowernumber,
1394             biblionumber   => $item->biblionumber,
1395             priority       => 1,
1396             itemnumber     => $item->itemnumber,
1397         }
1398     );
1399
1400     my $hold = Koha::Holds->find($reserve_id);
1401     my $previous_timestamp = '1970-01-01 12:34:56';
1402     $hold->timestamp($previous_timestamp)->store;
1403
1404     $hold = Koha::Holds->find($reserve_id);
1405     is( $hold->timestamp, $previous_timestamp, 'Make sure the previous timestamp has been used' );
1406
1407     # Avoid warnings
1408     my $reserve_mock = Test::MockModule->new('C4::Reserves');
1409     $reserve_mock->mock( '_koha_notify_reserve', undef );
1410
1411     # Mark it waiting
1412     ModReserveAffect( $item->itemnumber, $patron->borrowernumber );
1413
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' );
1417
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' );
1421 };
1422
1423 sub count_hold_print_messages {
1424     my $message_count = $dbh->selectall_arrayref(q{
1425         SELECT COUNT(*)
1426         FROM message_queue
1427         WHERE letter_code = 'HOLD' 
1428         AND   message_transport_type = 'print'
1429     });
1430     return $message_count->[0]->[0];
1431 }
1432
1433 sub place_item_hold {
1434     my ($patron,$item,$library,$priority) = @_;
1435
1436     my $hold_id = C4::Reserves::AddReserve(
1437         {
1438             branchcode     => $library->branchcode,
1439             borrowernumber => $patron->borrowernumber,
1440             biblionumber   => $item->biblionumber,
1441             priority       => $priority,
1442             title          => "title for fee",
1443             itemnumber     => $item->itemnumber,
1444         }
1445     );
1446
1447     my $hold = Koha::Holds->find($hold_id);
1448     return $hold;
1449 }
1450
1451 # we reached the finish
1452 $schema->storage->txn_rollback();
1453
1454 subtest 'IsAvailableForItemLevelRequest() tests' => sub {
1455
1456     plan tests => 3;
1457
1458     $schema->storage->txn_begin;
1459
1460     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1461
1462     my $item_type = undef;
1463
1464     my $item_mock = Test::MockModule->new('Koha::Item');
1465     $item_mock->mock( 'effective_itemtype', sub { return $item_type; } );
1466
1467     my $item = $builder->build_sample_item;
1468
1469     ok(
1470         !C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ),
1471         "Item not available for item-level hold because no effective item type"
1472     );
1473
1474     # Weird use case to highlight issue
1475     $item_type = '0';
1476     Koha::ItemTypes->search( { itemtype => $item_type } )->delete;
1477     my $itemtype = $builder->build_object(
1478         {
1479             class => 'Koha::ItemTypes',
1480             value => { itemtype => $item_type }
1481         }
1482     );
1483     ok(
1484         C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ),
1485         "Item not available for item-level hold because no effective item type"
1486     );
1487
1488     Koha::CirculationRules->set_rules(
1489         {
1490             categorycode => '*',
1491             itemtype     => '*',
1492             branchcode   => '*',
1493             rules        => {
1494                 onshelfholds => 0,
1495             }
1496         }
1497     );
1498     my $item_1 = $builder->build_sample_item( { notforloan => -1 } );
1499     ok(
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'"
1502     );
1503     $schema->storage->txn_rollback;
1504 };
1505
1506 subtest 'AddReserve() tests' => sub {
1507
1508     plan tests => 1;
1509
1510     $schema->storage->txn_begin;
1511
1512     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1513     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
1514     my $biblio  = $builder->build_sample_biblio;
1515
1516     my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1517     $mock->mock( 'enqueue', sub {
1518         my ( $self, $args ) = @_;
1519         is_deeply(
1520             $args->{biblio_ids},
1521             [ $biblio->id ],
1522             "AddReserve triggers a holds queue update for the related biblio"
1523         );
1524     } );
1525
1526     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1527
1528     AddReserve(
1529         {
1530             branchcode     => $library->branchcode,
1531             borrowernumber => $patron->id,
1532             biblionumber   => $biblio->id,
1533         }
1534     );
1535
1536     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1537
1538     AddReserve(
1539         {
1540             branchcode     => $library->branchcode,
1541             borrowernumber => $patron->id,
1542             biblionumber   => $biblio->id,
1543         }
1544     );
1545
1546     $schema->storage->txn_rollback;
1547 };
1548
1549 subtest 'AlterPriorty() tests' => sub {
1550
1551     plan tests => 2;
1552
1553     $schema->storage->txn_begin;
1554
1555     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1556     my $patron_1  = $builder->build_object({ class => 'Koha::Patrons' });
1557     my $patron_2  = $builder->build_object({ class => 'Koha::Patrons' });
1558     my $patron_3  = $builder->build_object({ class => 'Koha::Patrons' });
1559     my $biblio  = $builder->build_sample_biblio;
1560
1561     my $reserve_id = AddReserve(
1562         {
1563             branchcode     => $library->branchcode,
1564             borrowernumber => $patron_1->id,
1565             biblionumber   => $biblio->id,
1566         }
1567     );
1568     AddReserve(
1569         {
1570             branchcode     => $library->branchcode,
1571             borrowernumber => $patron_2->id,
1572             biblionumber   => $biblio->id,
1573         }
1574     );
1575     AddReserve(
1576         {
1577             branchcode     => $library->branchcode,
1578             borrowernumber => $patron_3->id,
1579             biblionumber   => $biblio->id,
1580         }
1581     );
1582
1583     my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1584     $mock->mock( 'enqueue', sub {
1585         my ( $self, $args ) = @_;
1586         is_deeply(
1587             $args->{biblio_ids},
1588             [ $biblio->id ],
1589             "AlterPriority triggers a holds queue update for the related biblio"
1590         );
1591     } );
1592
1593     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1594
1595     AlterPriority( "bottom", $reserve_id, 1, 2, 1, 3 );
1596
1597     my $hold = Koha::Holds->find($reserve_id);
1598
1599     is($hold->priority,3,'Successfully altered priority to bottom');
1600
1601     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1602
1603     AlterPriority( "bottom", $reserve_id, 1, 2, 1, 3 );
1604
1605     $schema->storage->txn_rollback;
1606 };
1607
1608 subtest 'CanBookBeReserved() tests' => sub {
1609
1610     plan tests => 2;
1611
1612     $schema->storage->txn_begin;
1613
1614     my $library = $builder->build_object(
1615         { class => 'Koha::Libraries', value => { pickup_location => 1 } } );
1616     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1617     my $itype  = $builder->build_object( { class => 'Koha::ItemTypes' } );
1618
1619     my $biblio = $builder->build_sample_biblio();
1620     my $item_1 = $builder->build_sample_item(
1621         { biblionumber => $biblio->id, itype => $itype->id } );
1622     my $item_2 = $builder->build_sample_item(
1623         { biblionumber => $biblio->id, itype => $itype->id } );
1624
1625     Koha::CirculationRules->delete;
1626     Koha::CirculationRules->set_rules(
1627         {
1628             branchcode   => undef,
1629             categorycode => undef,
1630             itemtype     => undef,
1631             rules        => {
1632                 holds_per_record => 100,
1633             }
1634         }
1635     );
1636     Koha::CirculationRules->set_rules(
1637         {
1638             branchcode   => undef,
1639             categorycode => undef,
1640             itemtype     => $itype->id,
1641             rules        => {
1642                 reservesallowed => 2,
1643             }
1644         }
1645     );
1646
1647     C4::Reserves::AddReserve(
1648         {
1649             branchcode     => $library->id,
1650             borrowernumber => $patron->id,
1651             biblionumber   => $biblio->id,
1652             title          => $biblio->title,
1653             itemnumber     => $item_1->id
1654         }
1655     );
1656
1657     ## Limit on item type is 2, only one hold, success tests
1658
1659     my $res = CanBookBeReserved( $patron->id, $biblio->id, $library->id,
1660         { itemtype => $itype->id } );
1661     is_deeply( $res, { status => 'OK' },
1662         'Holds on itemtype limit not reached' );
1663
1664     # Add a second hold, biblio-level and item type-constrained
1665     C4::Reserves::AddReserve(
1666         {
1667             branchcode     => $library->id,
1668             borrowernumber => $patron->id,
1669             biblionumber   => $biblio->id,
1670             title          => $biblio->title,
1671             itemtype       => $itype->id,
1672         }
1673     );
1674
1675     ## Limit on item type is 2, two holds, one of them biblio-level/item type-constrained
1676
1677     $res = CanBookBeReserved( $patron->id, $biblio->id, $library->id,
1678         { itemtype => $itype->id } );
1679     is_deeply( $res, { status => '' }, 'Holds on itemtype limit reached' );
1680
1681     $schema->storage->txn_rollback;
1682 };
1683
1684 subtest 'CanItemBeReserved() tests' => sub {
1685
1686     plan tests => 2;
1687
1688     $schema->storage->txn_begin;
1689
1690     my $library = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } );
1691     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
1692     my $itype   = $builder->build_object( { class => 'Koha::ItemTypes' } );
1693
1694     my $biblio = $builder->build_sample_biblio();
1695     my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->id, itype => $itype->id });
1696     my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->id, itype => $itype->id });
1697
1698     Koha::CirculationRules->delete;
1699     Koha::CirculationRules->set_rules(
1700         {   branchcode   => undef,
1701             categorycode => undef,
1702             itemtype     => undef,
1703             rules        => {
1704                 holds_per_record => 100,
1705             }
1706         }
1707     );
1708     Koha::CirculationRules->set_rules(
1709         {   branchcode   => undef,
1710             categorycode => undef,
1711             itemtype     => $itype->id,
1712             rules        => {
1713                 reservesallowed => 2,
1714             }
1715         }
1716     );
1717
1718     C4::Reserves::AddReserve(
1719         {
1720             branchcode     => $library->id,
1721             borrowernumber => $patron->id,
1722             biblionumber   => $biblio->id,
1723             title          => $biblio->title,
1724             itemnumber     => $item_1->id
1725         }
1726     );
1727
1728     ## Limit on item type is 2, only one hold, success tests
1729
1730     my $res = CanItemBeReserved( $patron, $item_2, $library->id );
1731     is_deeply( $res, { status => 'OK' }, 'Holds on itemtype limit not reached' );
1732
1733     # Add a second hold, biblio-level and item type-constrained
1734     C4::Reserves::AddReserve(
1735         {
1736             branchcode     => $library->id,
1737             borrowernumber => $patron->id,
1738             biblionumber   => $biblio->id,
1739             title          => $biblio->title,
1740             itemtype       => $itype->id,
1741         }
1742     );
1743
1744     ## Limit on item type is 2, two holds, one of them biblio-level/item type-constrained
1745
1746     $res = CanItemBeReserved( $patron, $item_2, $library->id );
1747     is_deeply( $res, { status => 'tooManyReserves', limit => 2 }, 'Holds on itemtype limit reached' );
1748
1749     $schema->storage->txn_rollback;
1750 };
1751
1752 subtest 'DefaultHoldExpiration tests' => sub {
1753     plan tests => 2;
1754     $schema->storage->txn_begin;
1755
1756     t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdate', 1 );
1757     t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdatePeriod', 365 );
1758     t::lib::Mocks::mock_preference( 'DefaultHoldExpirationUnitOfTime', 'days;' );
1759
1760     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
1761     my $item    = $builder->build_sample_item();
1762
1763     my $reserve_id = AddReserve({
1764         branchcode     => $item->homebranch,
1765         borrowernumber => $patron->id,
1766         biblionumber   => $item->biblionumber,
1767     });
1768
1769     my $today = dt_from_string();
1770     my $hold = Koha::Holds->find( $reserve_id );
1771
1772     is( $hold->reservedate, $today->ymd, "Hold created today" );
1773     is( $hold->expirationdate, $today->add( days => 365)->ymd, "Reserve date set 1 year from today" );
1774
1775     $schema->txn_rollback;
1776 };
1777
1778 subtest '_Findgroupreserves' => sub {
1779     plan tests => 6;
1780     $schema->storage->txn_begin;
1781
1782     my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } );
1783     my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } );
1784     my $item     = $builder->build_sample_item();
1785     my $item_2   = $builder->build_sample_item( { biblionumber => $item->biblionumber } );
1786
1787     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1788     my $reserve_id_1 = AddReserve(
1789         {
1790             branchcode     => $item->homebranch,
1791             borrowernumber => $patron_1->id,
1792             biblionumber   => $item->biblionumber,
1793         }
1794     );
1795     my $reserve_id_2 = AddReserve(
1796         {
1797             branchcode     => $item->homebranch,
1798             borrowernumber => $patron_2->id,
1799             biblionumber   => $item->biblionumber,
1800         }
1801     );
1802
1803     C4::HoldsQueue::AddToHoldTargetMap(
1804         {
1805             $item->id => {
1806                 borrowernumber => $patron_1->id,        biblionumber => $item->biblionumber,
1807                 holdingbranch  => $item->holdingbranch, item_level   => 0, reserve_id => $reserve_id_1
1808             }
1809         }
1810     );
1811
1812     # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1813     my @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item->id, 0, [] );
1814     is( scalar @reserves,           1,             "We should only get the hold that is in the map" );
1815     is( $reserves[0]->{reserve_id}, $reserve_id_1, "We got the expected reserve" );
1816
1817     C4::HoldsQueue::AddToHoldTargetMap(
1818         {
1819             $item_2->id => {
1820                 borrowernumber => $patron_2->id, biblionumber => $item->biblionumber,
1821                 holdingbranch  => $item->holdingbranch, item_level => 1, reserve_id => $reserve_id_2
1822             }
1823         }
1824     );
1825
1826     # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1827     @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item_2->id, 0, [] );
1828     is( scalar @reserves,           1,             "We should only get the item level hold that is in the map" );
1829     is( $reserves[0]->{reserve_id}, $reserve_id_2, "We got the expected reserve" );
1830
1831     C4::HoldsQueue::AddToHoldTargetMap(
1832         {
1833             $item_2->id => {
1834                 borrowernumber => $patron_2->id, biblionumber => $item->biblionumber,
1835                 holdingbranch  => $item->holdingbranch, item_level => 1, reserve_id => $reserve_id_1
1836             }
1837         }
1838     );
1839
1840     # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1841     @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item_2->id, 0, [] );
1842     is( scalar @reserves,           1,             "We should still only get the item level hold that is in the map" );
1843     is( $reserves[0]->{reserve_id}, $reserve_id_1, "We got the expected reserve which has been updated" );
1844
1845
1846
1847     $schema->txn_rollback;
1848 };