Bug 35322: Add unit tests
[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 => 5;
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         t::lib::Mocks::mock_preference( 'HoldsLog',           1 );
1036
1037         # Revert the waiting status
1038         C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1039
1040         $hold = Koha::Holds->find($reserve_id);
1041
1042         is(
1043             $hold->itemnumber, $item->itemnumber,
1044             'Itemnumber should not be removed when the waiting status is revert'
1045         );
1046
1047         my $log =
1048             Koha::ActionLogs->search( { module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id } )->next;
1049         my $expected = sprintf q{'timestamp' => '%s'}, $hold->timestamp;
1050         like( $log->info, qr{$expected}, 'Timestamp logged is the current one' );
1051         my $log_count =
1052             Koha::ActionLogs->search( { module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id } )->count;
1053
1054         t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1055         t::lib::Mocks::mock_preference( 'HoldsLog',           0 );
1056
1057         $hold->set_waiting;
1058
1059         # Revert the waiting status, RealTimeHoldsQueue => shouldn't add a test
1060         C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1061
1062         $hold->delete;    # cleanup
1063
1064         my $log_count_after =
1065             Koha::ActionLogs->search( { module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id } )->count;
1066         is( $log_count, $log_count_after, "No logging is added for RevertWaitingStatus when HoldsLog is disabled" );
1067
1068     };
1069
1070     subtest 'biblio level hold' => sub {
1071         plan tests => 3;
1072         my $reserve_id = AddReserve(
1073             {
1074                 branchcode     => $item->homebranch,
1075                 borrowernumber => $patron->borrowernumber,
1076                 biblionumber   => $item->biblionumber,
1077                 priority       => 1,
1078             }
1079         );
1080
1081         my $hold = Koha::Holds->find($reserve_id);
1082         is( $hold->item_level_hold, 0, 'item_level_hold should not be set when AddReserve is called without a specific item' );
1083
1084         # Mark it waiting
1085         ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
1086
1087         $hold = Koha::Holds->find($reserve_id);
1088         is( $hold->itemnumber, $item->itemnumber, 'Itemnumber should be set on hold confirmation' );
1089
1090         # Revert the waiting status
1091         C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1092
1093         $hold = Koha::Holds->find($reserve_id);
1094         is( $hold->itemnumber, undef, 'Itemnumber should be removed when the waiting status is revert' );
1095
1096         $hold->delete;
1097     };
1098
1099 };
1100
1101 subtest 'MoveReserve additional test' => sub {
1102
1103     plan tests => 4;
1104
1105     # Create the items and patrons we need
1106     my $biblio = $builder->build_sample_biblio();
1107     my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
1108     my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1109     my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber, notforloan => 0, itype => $itype->itemtype });
1110     my $patron_1 = $builder->build_object({ class => "Koha::Patrons" });
1111     my $patron_2 = $builder->build_object({ class => "Koha::Patrons" });
1112
1113     # Place a hold on the title for both patrons
1114     my $reserve_1 = AddReserve(
1115         {
1116             branchcode     => $item_1->homebranch,
1117             borrowernumber => $patron_1->borrowernumber,
1118             biblionumber   => $biblio->biblionumber,
1119             priority       => 1,
1120             itemnumber     => $item_1->itemnumber,
1121         }
1122     );
1123     my $reserve_2 = AddReserve(
1124         {
1125             branchcode     => $item_2->homebranch,
1126             borrowernumber => $patron_2->borrowernumber,
1127             biblionumber   => $biblio->biblionumber,
1128             priority       => 1,
1129             itemnumber     => $item_1->itemnumber,
1130         }
1131     );
1132     is($patron_1->holds->next()->reserve_id, $reserve_1, "The 1st patron has a hold");
1133     is($patron_2->holds->next()->reserve_id, $reserve_2, "The 2nd patron has a hold");
1134
1135     # Fake the holds queue
1136     $dbh->do(q{INSERT INTO hold_fill_targets VALUES (?, ?, ?, ?, ?,?)},undef,($patron_1->borrowernumber,$biblio->biblionumber,$item_1->itemnumber,$item_1->homebranch,0,$reserve_1));
1137
1138     # The 2nd hold should be filed even if the item is preselected for the first hold
1139     MoveReserve($item_1->itemnumber,$patron_2->borrowernumber);
1140     is($patron_2->holds->count, 0, "The 2nd patrons no longer has a hold");
1141     is($patron_2->old_holds->next()->reserve_id, $reserve_2, "The 2nd patrons hold was filled and moved to old holds");
1142
1143 };
1144
1145 subtest 'RevertWaitingStatus' => sub {
1146
1147     plan tests => 2;
1148
1149     # Create the items and patrons we need
1150     my $biblio  = $builder->build_sample_biblio();
1151     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1152     my $itype   = $builder->build_object(
1153         { class => "Koha::ItemTypes", value => { notforloan => 0 } } );
1154     my $item_1 = $builder->build_sample_item(
1155         {
1156             biblionumber => $biblio->biblionumber,
1157             itype        => $itype->itemtype,
1158             library      => $library->branchcode
1159         }
1160     );
1161     my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1162     my $patron_2 = $builder->build_object( { class => "Koha::Patrons" } );
1163     my $patron_3 = $builder->build_object( { class => "Koha::Patrons" } );
1164     my $patron_4 = $builder->build_object( { class => "Koha::Patrons" } );
1165
1166     # Place a hold on the title for both patrons
1167     my $priority = 1;
1168     my $hold_1 = place_item_hold( $patron_1, $item_1, $library, $priority );
1169     my $hold_2 = place_item_hold( $patron_2, $item_1, $library, $priority );
1170     my $hold_3 = place_item_hold( $patron_3, $item_1, $library, $priority );
1171     my $hold_4 = place_item_hold( $patron_4, $item_1, $library, $priority );
1172
1173     $hold_1->set_waiting;
1174     AddIssue( $patron_3->unblessed, $item_1->barcode, undef, 'revert' );
1175
1176     my $holds = $biblio->holds;
1177     is( $holds->count, 3, 'One hold has been deleted' );
1178     is_deeply(
1179         [
1180             $holds->next->priority, $holds->next->priority,
1181             $holds->next->priority
1182         ],
1183         [ 1, 2, 3 ],
1184         'priorities have been reordered'
1185     );
1186 };
1187
1188 subtest 'CheckReserves additional tests' => sub {
1189
1190     plan tests => 8;
1191
1192     my $item = $builder->build_sample_item;
1193     my $reserve1 = $builder->build_object(
1194         {
1195             class => "Koha::Holds",
1196             value => {
1197                 found            => undef,
1198                 priority         => 1,
1199                 itemnumber       => undef,
1200                 biblionumber     => $item->biblionumber,
1201                 waitingdate      => undef,
1202                 cancellationdate => undef,
1203                 item_level_hold  => 0,
1204                 lowestPriority   => 0,
1205                 expirationdate   => undef,
1206                 suspend_until    => undef,
1207                 suspend          => 0,
1208                 itemtype         => undef,
1209             }
1210         }
1211     );
1212     my $reserve2 = $builder->build_object(
1213         {
1214             class => "Koha::Holds",
1215             value => {
1216                 found            => undef,
1217                 priority         => 2,
1218                 biblionumber     => $item->biblionumber,
1219                 borrowernumber   => $reserve1->borrowernumber,
1220                 itemnumber       => undef,
1221                 waitingdate      => undef,
1222                 cancellationdate => undef,
1223                 item_level_hold  => 0,
1224                 lowestPriority   => 0,
1225                 expirationdate   => undef,
1226                 suspend_until    => undef,
1227                 suspend          => 0,
1228                 itemtype         => undef,
1229             }
1230         }
1231     );
1232
1233     my $tmp_holdsqueue = $builder->build(
1234         {
1235             source => 'TmpHoldsqueue',
1236             value  => {
1237                 borrowernumber => $reserve1->borrowernumber,
1238                 biblionumber   => $reserve1->biblionumber,
1239             }
1240         }
1241     );
1242     my $fill_target = $builder->build(
1243         {
1244             source => 'HoldFillTarget',
1245             value  => {
1246                 borrowernumber     => $reserve1->borrowernumber,
1247                 biblionumber       => $reserve1->biblionumber,
1248                 itemnumber         => $item->itemnumber,
1249                 item_level_request => 0,
1250             }
1251         }
1252     );
1253
1254     ModReserveAffect( $item->itemnumber, $reserve1->borrowernumber, 1,
1255         $reserve1->reserve_id );
1256     my ( $status, $matched_reserve, $possible_reserves ) =
1257       CheckReserves( $item );
1258
1259     is( $status, 'Transferred', "We found a reserve" );
1260     is( $matched_reserve->{reserve_id},
1261         $reserve1->reserve_id, "We got the Transit reserve" );
1262     is( scalar @$possible_reserves, 2, 'We do get both reserves' );
1263
1264     my $patron_B = $builder->build_object({ class => "Koha::Patrons" });
1265     my $item_A = $builder->build_sample_item;
1266     my $item_B = $builder->build_sample_item({
1267         homebranch => $patron_B->branchcode,
1268         biblionumber => $item_A->biblionumber,
1269         itype => $item_A->itype
1270     });
1271     Koha::CirculationRules->set_rules(
1272         {
1273             branchcode   => undef,
1274             categorycode => undef,
1275             itemtype     => $item_A->itype,
1276             rules        => {
1277                 reservesallowed => 25,
1278                 holds_per_record => 1,
1279             }
1280         }
1281     );
1282     Koha::CirculationRules->set_rule({
1283         branchcode => undef,
1284         itemtype   => $item_A->itype,
1285         rule_name  => 'holdallowed',
1286         rule_value => 'from_home_library'
1287     });
1288     my $reserve_id = AddReserve(
1289         {
1290             branchcode     => $patron_B->branchcode,
1291             borrowernumber => $patron_B->borrowernumber,
1292             biblionumber   => $item_A->biblionumber,
1293             priority       => 1,
1294             itemnumber     => undef,
1295         }
1296     );
1297
1298     ok( $reserve_id, "We can place a record level hold because one item is owned by patron's home library");
1299     t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary');
1300     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1301     is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch");
1302     Koha::CirculationRules->set_rule({
1303         branchcode => $item_A->homebranch,
1304         itemtype   => $item_A->itype,
1305         rule_name  => 'holdallowed',
1306         rule_value => 'from_any_library'
1307     });
1308     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1309     is( $status, "Reserved", "We fill the hold with item A because item's branch rule says allow any");
1310
1311
1312     # Changing the control branch should change only the rule we get
1313     t::lib::Mocks::mock_preference('ReservesControlBranch', 'PatronLibrary');
1314     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1315     is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch");
1316     Koha::CirculationRules->set_rule({
1317         branchcode   => $patron_B->branchcode,
1318         itemtype   => $item_A->itype,
1319         rule_name  => 'holdallowed',
1320         rule_value => 'from_any_library'
1321     });
1322     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1323     is( $status, "Reserved", "We fill the hold with item A because patron's branch rule says allow any");
1324
1325 };
1326
1327 subtest 'AllowHoldOnPatronPossession test' => sub {
1328
1329     plan tests => 4;
1330
1331     # Create the items and patrons we need
1332     my $biblio = $builder->build_sample_biblio();
1333     my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
1334     my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1335     my $patron = $builder->build_object({ class => "Koha::Patrons",
1336                                           value => { branchcode => $item->homebranch }});
1337
1338     C4::Circulation::AddIssue($patron->unblessed,
1339                               $item->barcode);
1340     t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 0);
1341
1342     is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1343                                        $item->biblionumber)->{status},
1344        'alreadypossession',
1345        'Patron cannot place hold on a book loaned to itself');
1346
1347     is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status},
1348        'alreadypossession',
1349        'Patron cannot place hold on an item loaned to itself');
1350
1351     t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 1);
1352
1353     is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1354                                        $item->biblionumber)->{status},
1355        'OK',
1356        'Patron can place hold on a book loaned to itself');
1357
1358     is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status},
1359        'OK',
1360        'Patron can place hold on an item loaned to itself');
1361 };
1362
1363 subtest 'MergeHolds' => sub {
1364
1365     plan tests => 1;
1366
1367     my $biblio_1  = $builder->build_sample_biblio();
1368     my $biblio_2  = $builder->build_sample_biblio();
1369     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1370     my $itype   = $builder->build_object(
1371         { class => "Koha::ItemTypes", value => { notforloan => 0 } } );
1372     my $item_1 = $builder->build_sample_item(
1373         {
1374             biblionumber => $biblio_1->biblionumber,
1375             itype        => $itype->itemtype,
1376             library      => $library->branchcode
1377         }
1378     );
1379     my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1380
1381     # Place a hold on $biblio_1
1382     my $priority = 1;
1383     place_item_hold( $patron_1, $item_1, $library, $priority );
1384
1385     # Move and make sure hold is now on $biblio_2
1386     C4::Reserves::MergeHolds($dbh, $biblio_2->biblionumber, $biblio_1->biblionumber);
1387     is( $biblio_2->holds->count, 1, 'Hold has been transferred' );
1388 };
1389
1390 subtest 'ModReserveAffect logging' => sub {
1391
1392     plan tests => 4;
1393
1394     my $item = $builder->build_sample_item;
1395     my $patron = $builder->build_object(
1396         {
1397             class => "Koha::Patrons",
1398             value => { branchcode => $item->homebranch }
1399         }
1400     );
1401
1402     t::lib::Mocks::mock_userenv({ patron => $patron });
1403     t::lib::Mocks::mock_preference('HoldsLog', 1);
1404
1405     my $reserve_id = AddReserve(
1406         {
1407             branchcode     => $item->homebranch,
1408             borrowernumber => $patron->borrowernumber,
1409             biblionumber   => $item->biblionumber,
1410             priority       => 1,
1411             itemnumber     => $item->itemnumber,
1412         }
1413     );
1414
1415     my $hold = Koha::Holds->find($reserve_id);
1416     my $previous_timestamp = '1970-01-01 12:34:56';
1417     $hold->timestamp($previous_timestamp)->store;
1418
1419     $hold = Koha::Holds->find($reserve_id);
1420     is( $hold->timestamp, $previous_timestamp, 'Make sure the previous timestamp has been used' );
1421
1422     # Avoid warnings
1423     my $reserve_mock = Test::MockModule->new('C4::Reserves');
1424     $reserve_mock->mock( '_koha_notify_reserve', undef );
1425
1426     # Mark it waiting
1427     ModReserveAffect( $item->itemnumber, $patron->borrowernumber );
1428
1429     $hold->discard_changes;
1430     ok( $hold->is_waiting, 'Hold has been set waiting' );
1431     isnt( $hold->timestamp, $previous_timestamp, 'The timestamp has been modified' );
1432
1433     my $log = Koha::ActionLogs->search({ module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id })->next;
1434     my $expected = sprintf q{'timestamp' => '%s'}, $hold->timestamp;
1435     like( $log->info, qr{$expected}, 'Timestamp logged is the current one' );
1436 };
1437
1438 sub count_hold_print_messages {
1439     my $message_count = $dbh->selectall_arrayref(q{
1440         SELECT COUNT(*)
1441         FROM message_queue
1442         WHERE letter_code = 'HOLD' 
1443         AND   message_transport_type = 'print'
1444     });
1445     return $message_count->[0]->[0];
1446 }
1447
1448 sub place_item_hold {
1449     my ($patron,$item,$library,$priority) = @_;
1450
1451     my $hold_id = C4::Reserves::AddReserve(
1452         {
1453             branchcode     => $library->branchcode,
1454             borrowernumber => $patron->borrowernumber,
1455             biblionumber   => $item->biblionumber,
1456             priority       => $priority,
1457             title          => "title for fee",
1458             itemnumber     => $item->itemnumber,
1459         }
1460     );
1461
1462     my $hold = Koha::Holds->find($hold_id);
1463     return $hold;
1464 }
1465
1466 # we reached the finish
1467 $schema->storage->txn_rollback();
1468
1469 subtest 'IsAvailableForItemLevelRequest() tests' => sub {
1470
1471     plan tests => 3;
1472
1473     $schema->storage->txn_begin;
1474
1475     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1476
1477     my $item_type = undef;
1478
1479     my $item_mock = Test::MockModule->new('Koha::Item');
1480     $item_mock->mock( 'effective_itemtype', sub { return $item_type; } );
1481
1482     my $item = $builder->build_sample_item;
1483
1484     ok(
1485         !C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ),
1486         "Item not available for item-level hold because no effective item type"
1487     );
1488
1489     # Weird use case to highlight issue
1490     $item_type = '0';
1491     Koha::ItemTypes->search( { itemtype => $item_type } )->delete;
1492     my $itemtype = $builder->build_object(
1493         {
1494             class => 'Koha::ItemTypes',
1495             value => { itemtype => $item_type }
1496         }
1497     );
1498     ok(
1499         C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ),
1500         "Item not available for item-level hold because no effective item type"
1501     );
1502
1503     Koha::CirculationRules->set_rules(
1504         {
1505             categorycode => '*',
1506             itemtype     => '*',
1507             branchcode   => '*',
1508             rules        => {
1509                 onshelfholds => 0,
1510             }
1511         }
1512     );
1513     my $item_1 = $builder->build_sample_item( { notforloan => -1 } );
1514     ok(
1515         C4::Reserves::IsAvailableForItemLevelRequest( $item_1, $patron ),
1516         "We can placing hold on item with negative not for loan values when 'On shelf holds allowed' is set to 'If any unavailable'"
1517     );
1518     $schema->storage->txn_rollback;
1519 };
1520
1521 subtest 'AddReserve() tests' => sub {
1522
1523     plan tests => 1;
1524
1525     $schema->storage->txn_begin;
1526
1527     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1528     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
1529     my $biblio  = $builder->build_sample_biblio;
1530
1531     my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1532     $mock->mock( 'enqueue', sub {
1533         my ( $self, $args ) = @_;
1534         is_deeply(
1535             $args->{biblio_ids},
1536             [ $biblio->id ],
1537             "AddReserve triggers a holds queue update for the related biblio"
1538         );
1539     } );
1540
1541     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1542
1543     AddReserve(
1544         {
1545             branchcode     => $library->branchcode,
1546             borrowernumber => $patron->id,
1547             biblionumber   => $biblio->id,
1548         }
1549     );
1550
1551     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1552
1553     AddReserve(
1554         {
1555             branchcode     => $library->branchcode,
1556             borrowernumber => $patron->id,
1557             biblionumber   => $biblio->id,
1558         }
1559     );
1560
1561     $schema->storage->txn_rollback;
1562 };
1563
1564 subtest 'AlterPriorty() tests' => sub {
1565
1566     plan tests => 2;
1567
1568     $schema->storage->txn_begin;
1569
1570     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1571     my $patron_1  = $builder->build_object({ class => 'Koha::Patrons' });
1572     my $patron_2  = $builder->build_object({ class => 'Koha::Patrons' });
1573     my $patron_3  = $builder->build_object({ class => 'Koha::Patrons' });
1574     my $biblio  = $builder->build_sample_biblio;
1575
1576     my $reserve_id = AddReserve(
1577         {
1578             branchcode     => $library->branchcode,
1579             borrowernumber => $patron_1->id,
1580             biblionumber   => $biblio->id,
1581         }
1582     );
1583     AddReserve(
1584         {
1585             branchcode     => $library->branchcode,
1586             borrowernumber => $patron_2->id,
1587             biblionumber   => $biblio->id,
1588         }
1589     );
1590     AddReserve(
1591         {
1592             branchcode     => $library->branchcode,
1593             borrowernumber => $patron_3->id,
1594             biblionumber   => $biblio->id,
1595         }
1596     );
1597
1598     my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1599     $mock->mock( 'enqueue', sub {
1600         my ( $self, $args ) = @_;
1601         is_deeply(
1602             $args->{biblio_ids},
1603             [ $biblio->id ],
1604             "AlterPriority triggers a holds queue update for the related biblio"
1605         );
1606     } );
1607
1608     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1609
1610     AlterPriority( "bottom", $reserve_id, 1, 2, 1, 3 );
1611
1612     my $hold = Koha::Holds->find($reserve_id);
1613
1614     is($hold->priority,3,'Successfully altered priority to bottom');
1615
1616     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1617
1618     AlterPriority( "bottom", $reserve_id, 1, 2, 1, 3 );
1619
1620     $schema->storage->txn_rollback;
1621 };
1622
1623 subtest 'CanBookBeReserved() tests' => sub {
1624
1625     plan tests => 2;
1626
1627     $schema->storage->txn_begin;
1628
1629     my $library = $builder->build_object(
1630         { class => 'Koha::Libraries', value => { pickup_location => 1 } } );
1631     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1632     my $itype  = $builder->build_object( { class => 'Koha::ItemTypes' } );
1633
1634     my $biblio = $builder->build_sample_biblio();
1635     my $item_1 = $builder->build_sample_item(
1636         { biblionumber => $biblio->id, itype => $itype->id } );
1637     my $item_2 = $builder->build_sample_item(
1638         { biblionumber => $biblio->id, itype => $itype->id } );
1639
1640     Koha::CirculationRules->delete;
1641     Koha::CirculationRules->set_rules(
1642         {
1643             branchcode   => undef,
1644             categorycode => undef,
1645             itemtype     => undef,
1646             rules        => {
1647                 holds_per_record => 100,
1648             }
1649         }
1650     );
1651     Koha::CirculationRules->set_rules(
1652         {
1653             branchcode   => undef,
1654             categorycode => undef,
1655             itemtype     => $itype->id,
1656             rules        => {
1657                 reservesallowed => 2,
1658             }
1659         }
1660     );
1661
1662     C4::Reserves::AddReserve(
1663         {
1664             branchcode     => $library->id,
1665             borrowernumber => $patron->id,
1666             biblionumber   => $biblio->id,
1667             title          => $biblio->title,
1668             itemnumber     => $item_1->id
1669         }
1670     );
1671
1672     ## Limit on item type is 2, only one hold, success tests
1673
1674     my $res = CanBookBeReserved( $patron->id, $biblio->id, $library->id,
1675         { itemtype => $itype->id } );
1676     is_deeply( $res, { status => 'OK' },
1677         'Holds on itemtype limit not reached' );
1678
1679     # Add a second hold, biblio-level and item type-constrained
1680     C4::Reserves::AddReserve(
1681         {
1682             branchcode     => $library->id,
1683             borrowernumber => $patron->id,
1684             biblionumber   => $biblio->id,
1685             title          => $biblio->title,
1686             itemtype       => $itype->id,
1687         }
1688     );
1689
1690     ## Limit on item type is 2, two holds, one of them biblio-level/item type-constrained
1691
1692     $res = CanBookBeReserved( $patron->id, $biblio->id, $library->id,
1693         { itemtype => $itype->id } );
1694     is_deeply( $res, { status => '' }, 'Holds on itemtype limit reached' );
1695
1696     $schema->storage->txn_rollback;
1697 };
1698
1699 subtest 'CanItemBeReserved() tests' => sub {
1700
1701     plan tests => 2;
1702
1703     $schema->storage->txn_begin;
1704
1705     my $library = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } );
1706     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
1707     my $itype   = $builder->build_object( { class => 'Koha::ItemTypes' } );
1708
1709     my $biblio = $builder->build_sample_biblio();
1710     my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->id, itype => $itype->id });
1711     my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->id, itype => $itype->id });
1712
1713     Koha::CirculationRules->delete;
1714     Koha::CirculationRules->set_rules(
1715         {   branchcode   => undef,
1716             categorycode => undef,
1717             itemtype     => undef,
1718             rules        => {
1719                 holds_per_record => 100,
1720             }
1721         }
1722     );
1723     Koha::CirculationRules->set_rules(
1724         {   branchcode   => undef,
1725             categorycode => undef,
1726             itemtype     => $itype->id,
1727             rules        => {
1728                 reservesallowed => 2,
1729             }
1730         }
1731     );
1732
1733     C4::Reserves::AddReserve(
1734         {
1735             branchcode     => $library->id,
1736             borrowernumber => $patron->id,
1737             biblionumber   => $biblio->id,
1738             title          => $biblio->title,
1739             itemnumber     => $item_1->id
1740         }
1741     );
1742
1743     ## Limit on item type is 2, only one hold, success tests
1744
1745     my $res = CanItemBeReserved( $patron, $item_2, $library->id );
1746     is_deeply( $res, { status => 'OK' }, 'Holds on itemtype limit not reached' );
1747
1748     # Add a second hold, biblio-level and item type-constrained
1749     C4::Reserves::AddReserve(
1750         {
1751             branchcode     => $library->id,
1752             borrowernumber => $patron->id,
1753             biblionumber   => $biblio->id,
1754             title          => $biblio->title,
1755             itemtype       => $itype->id,
1756         }
1757     );
1758
1759     ## Limit on item type is 2, two holds, one of them biblio-level/item type-constrained
1760
1761     $res = CanItemBeReserved( $patron, $item_2, $library->id );
1762     is_deeply( $res, { status => 'tooManyReserves', limit => 2 }, 'Holds on itemtype limit reached' );
1763
1764     $schema->storage->txn_rollback;
1765 };
1766
1767 subtest 'DefaultHoldExpiration tests' => sub {
1768     plan tests => 2;
1769     $schema->storage->txn_begin;
1770
1771     t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdate', 1 );
1772     t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdatePeriod', 365 );
1773     t::lib::Mocks::mock_preference( 'DefaultHoldExpirationUnitOfTime', 'days;' );
1774
1775     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
1776     my $item    = $builder->build_sample_item();
1777
1778     my $reserve_id = AddReserve({
1779         branchcode     => $item->homebranch,
1780         borrowernumber => $patron->id,
1781         biblionumber   => $item->biblionumber,
1782     });
1783
1784     my $today = dt_from_string();
1785     my $hold = Koha::Holds->find( $reserve_id );
1786
1787     is( $hold->reservedate, $today->ymd, "Hold created today" );
1788     is( $hold->expirationdate, $today->add( days => 365)->ymd, "Reserve date set 1 year from today" );
1789
1790     $schema->txn_rollback;
1791 };
1792
1793 subtest '_Findgroupreserves' => sub {
1794     plan tests => 6;
1795     $schema->storage->txn_begin;
1796
1797     my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } );
1798     my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } );
1799     my $item     = $builder->build_sample_item();
1800     my $item_2   = $builder->build_sample_item( { biblionumber => $item->biblionumber } );
1801
1802     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1803     my $reserve_id_1 = AddReserve(
1804         {
1805             branchcode     => $item->homebranch,
1806             borrowernumber => $patron_1->id,
1807             biblionumber   => $item->biblionumber,
1808         }
1809     );
1810     my $reserve_id_2 = AddReserve(
1811         {
1812             branchcode     => $item->homebranch,
1813             borrowernumber => $patron_2->id,
1814             biblionumber   => $item->biblionumber,
1815         }
1816     );
1817
1818     C4::HoldsQueue::AddToHoldTargetMap(
1819         {
1820             $item->id => {
1821                 borrowernumber => $patron_1->id,        biblionumber => $item->biblionumber,
1822                 holdingbranch  => $item->holdingbranch, item_level   => 0, reserve_id => $reserve_id_1
1823             }
1824         }
1825     );
1826
1827     # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1828     my @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item->id, 0, [] );
1829     is( scalar @reserves,           1,             "We should only get the hold that is in the map" );
1830     is( $reserves[0]->{reserve_id}, $reserve_id_1, "We got the expected reserve" );
1831
1832     C4::HoldsQueue::AddToHoldTargetMap(
1833         {
1834             $item_2->id => {
1835                 borrowernumber => $patron_2->id, biblionumber => $item->biblionumber,
1836                 holdingbranch  => $item->holdingbranch, item_level => 1, reserve_id => $reserve_id_2
1837             }
1838         }
1839     );
1840
1841     # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1842     @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item_2->id, 0, [] );
1843     is( scalar @reserves,           1,             "We should only get the item level hold that is in the map" );
1844     is( $reserves[0]->{reserve_id}, $reserve_id_2, "We got the expected reserve" );
1845
1846     C4::HoldsQueue::AddToHoldTargetMap(
1847         {
1848             $item_2->id => {
1849                 borrowernumber => $patron_2->id, biblionumber => $item->biblionumber,
1850                 holdingbranch  => $item->holdingbranch, item_level => 1, reserve_id => $reserve_id_1
1851             }
1852         }
1853     );
1854
1855     # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1856     @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item_2->id, 0, [] );
1857     is( scalar @reserves,           1,             "We should still only get the item level hold that is in the map" );
1858     is( $reserves[0]->{reserve_id}, $reserve_id_1, "We got the expected reserve which has been updated" );
1859
1860
1861
1862     $schema->txn_rollback;
1863 };