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