Bug 35979: (follow-up) Add check in ->enqueue
[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 my $other_item = $builder->build_sample_item({ biblionumber => $biblio->id });
696 AddReserve(
697     {
698         branchcode     => $branch_1,
699         borrowernumber => $borrowernumber,
700         biblionumber   => $bibnum,
701         priority       => 1,
702         found          => 'W',
703         itemnumber     => $other_item->id,
704     }
705 );
706 MoveReserve( $item->itemnumber, $borrowernumber );
707 ($status)=CheckReserves( $item );
708 is( $status, '', 'MoveReserve filled waiting hold');
709 #   hold from A pos 1, tomorrow, no fut holds: not filled
710 $resdate= dt_from_string();
711 $resdate->add_duration(DateTime::Duration->new(days => 1));
712 AddReserve(
713     {
714         branchcode     => $branch_1,
715         borrowernumber => $borrowernumber,
716         biblionumber   => $bibnum,
717         priority       => 1,
718         reservation_date => $resdate,
719     }
720 );
721 MoveReserve( $item->itemnumber, $borrowernumber );
722 ($status)=CheckReserves( $item, 1 );
723 is( $status, 'Reserved', 'MoveReserve did not fill future hold');
724 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
725 #   hold from A pos 1, tomorrow, fut holds=2: MoveReserve should fill it
726 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
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, undef, 2 );
738 is( $status, '', 'MoveReserve filled future hold now');
739 #   hold from A waiting, tomorrow, fut holds=2: MoveReserve should fill it
740 AddReserve(
741     {
742         branchcode     => $branch_1,
743         borrowernumber => $borrowernumber,
744         biblionumber   => $bibnum,
745         priority       => 1,
746         reservation_date => $resdate,
747     }
748 );
749 MoveReserve( $item->itemnumber, $borrowernumber );
750 ($status)=CheckReserves( $item, undef, 2 );
751 is( $status, '', 'MoveReserve filled future waiting hold now');
752 #   hold from A pos 1, today+3, fut holds=2: MoveReserve should not fill it
753 $resdate= dt_from_string();
754 $resdate->add_duration(DateTime::Duration->new(days => 3));
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, 3 );
766 is( $status, 'Reserved', 'MoveReserve did not fill future hold of 3 days');
767 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
768
769 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
770 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
771 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
772
773 subtest '_koha_notify_reserve() tests' => sub {
774
775     plan tests => 3;
776
777     my $branch = $builder->build_object({
778         class => 'Koha::Libraries',
779         value => {
780             branchemail => 'branch@e.mail',
781             branchreplyto => 'branch@reply.to',
782             pickup_location => 1
783         }
784     });
785     my $item = $builder->build_sample_item({
786         homebranch => $branch->branchcode,
787         holdingbranch => $branch->branchcode
788     });
789
790     my $wants_hold_and_email = {
791         wants_digest => '0',
792         transports => {
793             sms => 'HOLD',
794             email => 'HOLD',
795             },
796         letter_code => 'HOLD'
797     };
798
799     my $mp = Test::MockModule->new( 'C4::Members::Messaging' );
800
801     $mp->mock("GetMessagingPreferences",$wants_hold_and_email);
802
803     $dbh->do('DELETE FROM letter');
804
805     my $email_hold_notice = $builder->build({
806             source => 'Letter',
807             value => {
808                 message_transport_type => 'email',
809                 branchcode => '',
810                 code => 'HOLD',
811                 module => 'reserves',
812                 lang => 'default',
813             }
814         });
815
816     my $sms_hold_notice = $builder->build({
817             source => 'Letter',
818             value => {
819                 message_transport_type => 'sms',
820                 branchcode => '',
821                 code => 'HOLD',
822                 module => 'reserves',
823                 lang=>'default',
824             }
825         });
826
827     my $hold_borrower = $builder->build({
828             source => 'Borrower',
829             value => {
830                 smsalertnumber=>'5555555555',
831                 email=>'a@b.com',
832             }
833         })->{borrowernumber};
834
835     C4::Reserves::AddReserve(
836         {
837             branchcode     => $item->homebranch,
838             borrowernumber => $hold_borrower,
839             biblionumber   => $item->biblionumber,
840         }
841     );
842
843     ModReserveAffect($item->itemnumber, $hold_borrower, 0);
844     my $sms_message_address = $schema->resultset('MessageQueue')->search({
845             letter_code     => 'HOLD',
846             message_transport_type => 'sms',
847             borrowernumber => $hold_borrower,
848         })->next()->to_address();
849     is($sms_message_address, undef ,"We should not populate the sms message with the sms number, sending will do so");
850
851     my $email = $schema->resultset('MessageQueue')->search({
852             letter_code     => 'HOLD',
853             message_transport_type => 'email',
854             borrowernumber => $hold_borrower,
855         })->next();
856     my $email_to_address = $email->to_address();
857     is($email_to_address, undef ,"We should not populate the hold message with the email address, sending will do so");
858     my $email_from_address = $email->from_address();
859     is($email_from_address,'branch@e.mail',"Library's from address is used for sending");
860
861 };
862
863 subtest 'ReservesNeedReturns' => sub {
864     plan tests => 18;
865
866     my $library    = $builder->build_object( { class => 'Koha::Libraries' } );
867     my $item_info  = {
868         homebranch       => $library->branchcode,
869         holdingbranch    => $library->branchcode,
870     };
871     my $item = $builder->build_sample_item($item_info);
872     my $patron   = $builder->build_object(
873         {
874             class => 'Koha::Patrons',
875             value => { branchcode => $library->branchcode, }
876         }
877     );
878     my $patron_2   = $builder->build_object(
879         {
880             class => 'Koha::Patrons',
881             value => { branchcode => $library->branchcode, }
882         }
883     );
884
885     my $priority = 1;
886
887     t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Test with feature disabled
888     my $hold = place_item_hold( $patron, $item, $library, $priority );
889     is( $hold->priority, $priority, 'If ReservesNeedReturns is 1, priority must not have been set to changed' );
890     is( $hold->found, undef, 'If ReservesNeedReturns is 1, found must not have been set waiting' );
891     $hold->delete;
892
893     t::lib::Mocks::mock_preference('ReservesNeedReturns', 0); # '0' means 'Automatically mark a hold as found and waiting'
894     $hold = place_item_hold( $patron, $item, $library, $priority );
895     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
896     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
897     $hold->delete;
898
899     $item->onloan('2010-01-01')->store;
900     $hold = place_item_hold( $patron, $item, $library, $priority );
901     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item onloan priority must be set to 1' );
902     $hold->delete;
903
904     t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 0); # '0' means damaged holds not allowed
905     $item->onloan(undef)->damaged(1)->store;
906     $hold = place_item_hold( $patron, $item, $library, $priority );
907     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item damaged and not allowed holds on damaged items priority must be set to 1' );
908     $hold->delete;
909     t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 1); # '0' means damaged holds not allowed
910     $hold = place_item_hold( $patron, $item, $library, $priority );
911     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and damaged holds allowed, priority must have been set to 0' );
912     is( $hold->found,  'W', 'If ReservesNeedReturns is 0 and damaged holds allowed, found must have been set waiting' );
913     $hold->delete;
914
915     my $hold_1 = place_item_hold( $patron, $item, $library, $priority );
916     is( $hold_1->found,  'W', 'First hold on item is set to waiting with ReservesNeedReturns set to 0' );
917     is( $hold_1->priority, 0, 'First hold on item is set to waiting with ReservesNeedReturns set to 0' );
918     $hold = place_item_hold( $patron_2, $item, $library, $priority );
919     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item already on hold priority must be set to 1' );
920     $hold->delete;
921     $hold_1->delete;
922
923     my $transfer = $builder->build_object({
924         class => "Koha::Item::Transfers",
925         value => {
926           itemnumber  => $item->itemnumber,
927           datearrived => undef,
928           datecancelled => undef
929         }
930     });
931     $item->damaged(0)->store;
932     $hold = place_item_hold( $patron, $item, $library, $priority );
933     is( $hold->found, undef, 'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
934     is( $hold->priority, 1,  'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
935     $hold->delete;
936     $transfer->delete;
937
938     $hold = place_item_hold( $patron, $item, $library, $priority );
939     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
940     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
941     $hold_1 = place_item_hold( $patron, $item, $library, $priority );
942     is( $hold_1->priority, 1, 'If ReservesNeedReturns is 0 but item has a hold priority is 1' );
943     $hold_1->suspend(1)->store; # We suspend the hold
944     $hold->delete; # Delete the waiting hold
945     $hold = place_item_hold( $patron, $item, $library, $priority );
946     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and other hold(s) suspended, priority must have been set to 0' );
947     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and other  hold(s) suspended, found must have been set waiting' );
948
949
950
951
952     t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Don't affect other tests
953 };
954
955 subtest 'ChargeReserveFee tests' => sub {
956
957     plan tests => 8;
958
959     my $library = $builder->build_object({ class => 'Koha::Libraries' });
960     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
961
962     my $fee   = 20;
963     my $title = 'A title';
964
965     my $context = Test::MockModule->new('C4::Context');
966     $context->mock( userenv => { branch => $library->id } );
967
968     my $line = C4::Reserves::ChargeReserveFee( $patron->id, $fee, $title );
969
970     is( ref($line), 'Koha::Account::Line' , 'Returns a Koha::Account::Line object');
971     ok( $line->is_debit, 'Generates a debit line' );
972     is( $line->debit_type_code, 'RESERVE' , 'generates RESERVE debit_type');
973     is( $line->borrowernumber, $patron->id , 'generated line belongs to the passed patron');
974     is( $line->amount, $fee , 'amount set correctly');
975     is( $line->amountoutstanding, $fee , 'amountoutstanding set correctly');
976     is( $line->description, "$title" , 'description is title of reserved item');
977     is( $line->branchcode, $library->id , "Library id is picked from userenv and stored correctly" );
978 };
979
980 subtest 'reserves.item_level_hold' => sub {
981     plan tests => 2;
982
983     my $item   = $builder->build_sample_item;
984     my $patron = $builder->build_object(
985         {
986             class => 'Koha::Patrons',
987             value => { branchcode => $item->homebranch }
988         }
989     );
990
991     subtest 'item level hold' => sub {
992         plan tests => 5;
993         my $reserve_id = AddReserve(
994             {
995                 branchcode     => $item->homebranch,
996                 borrowernumber => $patron->borrowernumber,
997                 biblionumber   => $item->biblionumber,
998                 priority       => 1,
999                 itemnumber     => $item->itemnumber,
1000             }
1001         );
1002
1003         my $hold = Koha::Holds->find($reserve_id);
1004         is( $hold->item_level_hold, 1, 'item_level_hold should be set when AddReserve is called with a specific item' );
1005
1006         # Mark it waiting
1007         ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
1008
1009         my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1010         $mock->mock( 'enqueue', sub {
1011             my ( $self, $args ) = @_;
1012             is_deeply(
1013                 $args->{biblio_ids},
1014                 [ $hold->biblionumber ],
1015                 "AlterPriority triggers a holds queue update for the related biblio"
1016             );
1017         } );
1018
1019         t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1020         t::lib::Mocks::mock_preference( 'HoldsLog',           1 );
1021
1022         # Revert the waiting status
1023         C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1024
1025         $hold = Koha::Holds->find($reserve_id);
1026
1027         is(
1028             $hold->itemnumber, $item->itemnumber,
1029             'Itemnumber should not be removed when the waiting status is revert'
1030         );
1031
1032         my $log =
1033             Koha::ActionLogs->search( { module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id } )->next;
1034         my $expected = sprintf q{'timestamp' => '%s'}, $hold->timestamp;
1035         like( $log->info, qr{$expected}, 'Timestamp logged is the current one' );
1036         my $log_count =
1037             Koha::ActionLogs->search( { module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id } )->count;
1038
1039         t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1040         t::lib::Mocks::mock_preference( 'HoldsLog',           0 );
1041
1042         $hold->set_waiting;
1043
1044         # Revert the waiting status, RealTimeHoldsQueue => shouldn't add a test
1045         C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1046
1047         $hold->delete;    # cleanup
1048
1049         my $log_count_after =
1050             Koha::ActionLogs->search( { module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id } )->count;
1051         is( $log_count, $log_count_after, "No logging is added for RevertWaitingStatus when HoldsLog is disabled" );
1052
1053     };
1054
1055     subtest 'biblio level hold' => sub {
1056         plan tests => 3;
1057         my $reserve_id = AddReserve(
1058             {
1059                 branchcode     => $item->homebranch,
1060                 borrowernumber => $patron->borrowernumber,
1061                 biblionumber   => $item->biblionumber,
1062                 priority       => 1,
1063             }
1064         );
1065
1066         my $hold = Koha::Holds->find($reserve_id);
1067         is( $hold->item_level_hold, 0, 'item_level_hold should not be set when AddReserve is called without a specific item' );
1068
1069         # Mark it waiting
1070         ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
1071
1072         $hold = Koha::Holds->find($reserve_id);
1073         is( $hold->itemnumber, $item->itemnumber, 'Itemnumber should be set on hold confirmation' );
1074
1075         # Revert the waiting status
1076         C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1077
1078         $hold = Koha::Holds->find($reserve_id);
1079         is( $hold->itemnumber, undef, 'Itemnumber should be removed when the waiting status is revert' );
1080
1081         $hold->delete;
1082     };
1083
1084 };
1085
1086 subtest 'MoveReserve additional test' => sub {
1087
1088     plan tests => 4;
1089
1090     # Create the items and patrons we need
1091     my $biblio = $builder->build_sample_biblio();
1092     my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
1093     my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1094     my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber, notforloan => 0, itype => $itype->itemtype });
1095     my $patron_1 = $builder->build_object({ class => "Koha::Patrons" });
1096     my $patron_2 = $builder->build_object({ class => "Koha::Patrons" });
1097
1098     # Place a hold on the title for both patrons
1099     my $reserve_1 = AddReserve(
1100         {
1101             branchcode     => $item_1->homebranch,
1102             borrowernumber => $patron_1->borrowernumber,
1103             biblionumber   => $biblio->biblionumber,
1104             priority       => 1,
1105             itemnumber     => $item_1->itemnumber,
1106         }
1107     );
1108     my $reserve_2 = AddReserve(
1109         {
1110             branchcode     => $item_2->homebranch,
1111             borrowernumber => $patron_2->borrowernumber,
1112             biblionumber   => $biblio->biblionumber,
1113             priority       => 1,
1114             itemnumber     => $item_1->itemnumber,
1115         }
1116     );
1117     is($patron_1->holds->next()->reserve_id, $reserve_1, "The 1st patron has a hold");
1118     is($patron_2->holds->next()->reserve_id, $reserve_2, "The 2nd patron has a hold");
1119
1120     # Fake the holds queue
1121     $dbh->do(q{INSERT INTO hold_fill_targets VALUES (?, ?, ?, ?, ?,?)},undef,($patron_1->borrowernumber,$biblio->biblionumber,$item_1->itemnumber,$item_1->homebranch,0,$reserve_1));
1122
1123     # The 2nd hold should be filed even if the item is preselected for the first hold
1124     MoveReserve($item_1->itemnumber,$patron_2->borrowernumber);
1125     is($patron_2->holds->count, 0, "The 2nd patrons no longer has a hold");
1126     is($patron_2->old_holds->next()->reserve_id, $reserve_2, "The 2nd patrons hold was filled and moved to old holds");
1127
1128 };
1129
1130 subtest 'RevertWaitingStatus' => sub {
1131
1132     plan tests => 2;
1133
1134     # Create the items and patrons we need
1135     my $biblio  = $builder->build_sample_biblio();
1136     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1137     my $itype   = $builder->build_object(
1138         { class => "Koha::ItemTypes", value => { notforloan => 0 } } );
1139     my $item_1 = $builder->build_sample_item(
1140         {
1141             biblionumber => $biblio->biblionumber,
1142             itype        => $itype->itemtype,
1143             library      => $library->branchcode
1144         }
1145     );
1146     my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1147     my $patron_2 = $builder->build_object( { class => "Koha::Patrons" } );
1148     my $patron_3 = $builder->build_object( { class => "Koha::Patrons" } );
1149     my $patron_4 = $builder->build_object( { class => "Koha::Patrons" } );
1150
1151     # Place a hold on the title for both patrons
1152     my $priority = 1;
1153     my $hold_1 = place_item_hold( $patron_1, $item_1, $library, $priority );
1154     my $hold_2 = place_item_hold( $patron_2, $item_1, $library, $priority );
1155     my $hold_3 = place_item_hold( $patron_3, $item_1, $library, $priority );
1156     my $hold_4 = place_item_hold( $patron_4, $item_1, $library, $priority );
1157
1158     $hold_1->set_waiting;
1159     AddIssue( $patron_3, $item_1->barcode, undef, 'revert' );
1160
1161     my $holds = $biblio->holds;
1162     is( $holds->count, 3, 'One hold has been deleted' );
1163     is_deeply(
1164         [
1165             $holds->next->priority, $holds->next->priority,
1166             $holds->next->priority
1167         ],
1168         [ 1, 2, 3 ],
1169         'priorities have been reordered'
1170     );
1171 };
1172
1173 subtest 'CheckReserves additional tests' => sub {
1174
1175     plan tests => 8;
1176
1177     my $item = $builder->build_sample_item;
1178     my $reserve1 = $builder->build_object(
1179         {
1180             class => "Koha::Holds",
1181             value => {
1182                 found            => undef,
1183                 priority         => 1,
1184                 itemnumber       => undef,
1185                 biblionumber     => $item->biblionumber,
1186                 waitingdate      => undef,
1187                 cancellationdate => undef,
1188                 item_level_hold  => 0,
1189                 lowestPriority   => 0,
1190                 expirationdate   => undef,
1191                 suspend_until    => undef,
1192                 suspend          => 0,
1193                 itemtype         => undef,
1194             }
1195         }
1196     );
1197     my $reserve2 = $builder->build_object(
1198         {
1199             class => "Koha::Holds",
1200             value => {
1201                 found            => undef,
1202                 priority         => 2,
1203                 biblionumber     => $item->biblionumber,
1204                 borrowernumber   => $reserve1->borrowernumber,
1205                 itemnumber       => undef,
1206                 waitingdate      => undef,
1207                 cancellationdate => undef,
1208                 item_level_hold  => 0,
1209                 lowestPriority   => 0,
1210                 expirationdate   => undef,
1211                 suspend_until    => undef,
1212                 suspend          => 0,
1213                 itemtype         => undef,
1214             }
1215         }
1216     );
1217
1218     my $tmp_holdsqueue = $builder->build(
1219         {
1220             source => 'TmpHoldsqueue',
1221             value  => {
1222                 borrowernumber => $reserve1->borrowernumber,
1223                 biblionumber   => $reserve1->biblionumber,
1224             }
1225         }
1226     );
1227     my $fill_target = $builder->build(
1228         {
1229             source => 'HoldFillTarget',
1230             value  => {
1231                 borrowernumber     => $reserve1->borrowernumber,
1232                 biblionumber       => $reserve1->biblionumber,
1233                 itemnumber         => $item->itemnumber,
1234                 item_level_request => 0,
1235             }
1236         }
1237     );
1238
1239     ModReserveAffect( $item->itemnumber, $reserve1->borrowernumber, 1,
1240         $reserve1->reserve_id );
1241     my ( $status, $matched_reserve, $possible_reserves ) =
1242       CheckReserves( $item );
1243
1244     is( $status, 'Transferred', "We found a reserve" );
1245     is( $matched_reserve->{reserve_id},
1246         $reserve1->reserve_id, "We got the Transit reserve" );
1247     is( scalar @$possible_reserves, 2, 'We do get both reserves' );
1248
1249     my $patron_B = $builder->build_object({ class => "Koha::Patrons" });
1250     my $item_A = $builder->build_sample_item;
1251     my $item_B = $builder->build_sample_item({
1252         homebranch => $patron_B->branchcode,
1253         biblionumber => $item_A->biblionumber,
1254         itype => $item_A->itype
1255     });
1256     Koha::CirculationRules->set_rules(
1257         {
1258             branchcode   => undef,
1259             categorycode => undef,
1260             itemtype     => $item_A->itype,
1261             rules        => {
1262                 reservesallowed => 25,
1263                 holds_per_record => 1,
1264             }
1265         }
1266     );
1267     Koha::CirculationRules->set_rule({
1268         branchcode => undef,
1269         itemtype   => $item_A->itype,
1270         rule_name  => 'holdallowed',
1271         rule_value => 'from_home_library'
1272     });
1273     my $reserve_id = AddReserve(
1274         {
1275             branchcode     => $patron_B->branchcode,
1276             borrowernumber => $patron_B->borrowernumber,
1277             biblionumber   => $item_A->biblionumber,
1278             priority       => 1,
1279             itemnumber     => undef,
1280         }
1281     );
1282
1283     ok( $reserve_id, "We can place a record level hold because one item is owned by patron's home library");
1284     t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary');
1285     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1286     is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch");
1287     Koha::CirculationRules->set_rule({
1288         branchcode => $item_A->homebranch,
1289         itemtype   => $item_A->itype,
1290         rule_name  => 'holdallowed',
1291         rule_value => 'from_any_library'
1292     });
1293     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1294     is( $status, "Reserved", "We fill the hold with item A because item's branch rule says allow any");
1295
1296
1297     # Changing the control branch should change only the rule we get
1298     t::lib::Mocks::mock_preference('ReservesControlBranch', 'PatronLibrary');
1299     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1300     is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch");
1301     Koha::CirculationRules->set_rule({
1302         branchcode   => $patron_B->branchcode,
1303         itemtype   => $item_A->itype,
1304         rule_name  => 'holdallowed',
1305         rule_value => 'from_any_library'
1306     });
1307     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A );
1308     is( $status, "Reserved", "We fill the hold with item A because patron's branch rule says allow any");
1309
1310 };
1311
1312 subtest 'AllowHoldOnPatronPossession test' => sub {
1313
1314     plan tests => 4;
1315
1316     # Create the items and patrons we need
1317     my $biblio = $builder->build_sample_biblio();
1318     my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
1319     my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1320     my $patron = $builder->build_object({ class => "Koha::Patrons",
1321                                           value => { branchcode => $item->homebranch }});
1322
1323     C4::Circulation::AddIssue($patron,
1324                               $item->barcode);
1325     t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 0);
1326
1327     is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1328                                        $item->biblionumber)->{status},
1329        'alreadypossession',
1330        'Patron cannot place hold on a book loaned to itself');
1331
1332     is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status},
1333        'alreadypossession',
1334        'Patron cannot place hold on an item loaned to itself');
1335
1336     t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 1);
1337
1338     is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1339                                        $item->biblionumber)->{status},
1340        'OK',
1341        'Patron can place hold on a book loaned to itself');
1342
1343     is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status},
1344        'OK',
1345        'Patron can place hold on an item loaned to itself');
1346 };
1347
1348 subtest 'MergeHolds' => sub {
1349
1350     plan tests => 1;
1351
1352     my $biblio_1  = $builder->build_sample_biblio();
1353     my $biblio_2  = $builder->build_sample_biblio();
1354     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1355     my $itype   = $builder->build_object(
1356         { class => "Koha::ItemTypes", value => { notforloan => 0 } } );
1357     my $item_1 = $builder->build_sample_item(
1358         {
1359             biblionumber => $biblio_1->biblionumber,
1360             itype        => $itype->itemtype,
1361             library      => $library->branchcode
1362         }
1363     );
1364     my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1365
1366     # Place a hold on $biblio_1
1367     my $priority = 1;
1368     place_item_hold( $patron_1, $item_1, $library, $priority );
1369
1370     # Move and make sure hold is now on $biblio_2
1371     C4::Reserves::MergeHolds($dbh, $biblio_2->biblionumber, $biblio_1->biblionumber);
1372     is( $biblio_2->holds->count, 1, 'Hold has been transferred' );
1373 };
1374
1375 subtest 'ModReserveAffect logging' => sub {
1376
1377     plan tests => 4;
1378
1379     my $item = $builder->build_sample_item;
1380     my $patron = $builder->build_object(
1381         {
1382             class => "Koha::Patrons",
1383             value => { branchcode => $item->homebranch }
1384         }
1385     );
1386
1387     t::lib::Mocks::mock_userenv({ patron => $patron });
1388     t::lib::Mocks::mock_preference('HoldsLog', 1);
1389
1390     my $reserve_id = AddReserve(
1391         {
1392             branchcode     => $item->homebranch,
1393             borrowernumber => $patron->borrowernumber,
1394             biblionumber   => $item->biblionumber,
1395             priority       => 1,
1396             itemnumber     => $item->itemnumber,
1397         }
1398     );
1399
1400     my $hold = Koha::Holds->find($reserve_id);
1401     my $previous_timestamp = '1970-01-01 12:34:56';
1402     $hold->timestamp($previous_timestamp)->store;
1403
1404     $hold = Koha::Holds->find($reserve_id);
1405     is( $hold->timestamp, $previous_timestamp, 'Make sure the previous timestamp has been used' );
1406
1407     # Avoid warnings
1408     my $reserve_mock = Test::MockModule->new('C4::Reserves');
1409     $reserve_mock->mock( '_koha_notify_reserve', undef );
1410
1411     # Mark it waiting
1412     ModReserveAffect( $item->itemnumber, $patron->borrowernumber );
1413
1414     $hold->discard_changes;
1415     ok( $hold->is_waiting, 'Hold has been set waiting' );
1416     isnt( $hold->timestamp, $previous_timestamp, 'The timestamp has been modified' );
1417
1418     my $log = Koha::ActionLogs->search({ module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id })->next;
1419     my $expected = sprintf q{'timestamp' => '%s'}, $hold->timestamp;
1420     like( $log->info, qr{$expected}, 'Timestamp logged is the current one' );
1421 };
1422
1423 sub count_hold_print_messages {
1424     my $message_count = $dbh->selectall_arrayref(q{
1425         SELECT COUNT(*)
1426         FROM message_queue
1427         WHERE letter_code = 'HOLD' 
1428         AND   message_transport_type = 'print'
1429     });
1430     return $message_count->[0]->[0];
1431 }
1432
1433 sub place_item_hold {
1434     my ($patron,$item,$library,$priority) = @_;
1435
1436     my $hold_id = C4::Reserves::AddReserve(
1437         {
1438             branchcode     => $library->branchcode,
1439             borrowernumber => $patron->borrowernumber,
1440             biblionumber   => $item->biblionumber,
1441             priority       => $priority,
1442             title          => "title for fee",
1443             itemnumber     => $item->itemnumber,
1444         }
1445     );
1446
1447     my $hold = Koha::Holds->find($hold_id);
1448     return $hold;
1449 }
1450
1451 # we reached the finish
1452 $schema->storage->txn_rollback();
1453
1454 subtest 'IsAvailableForItemLevelRequest() tests' => sub {
1455
1456     plan tests => 3;
1457
1458     $schema->storage->txn_begin;
1459
1460     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1461
1462     my $item_type = undef;
1463
1464     my $item_mock = Test::MockModule->new('Koha::Item');
1465     $item_mock->mock( 'effective_itemtype', sub { return $item_type; } );
1466
1467     my $item = $builder->build_sample_item;
1468
1469     ok(
1470         !C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ),
1471         "Item not available for item-level hold because no effective item type"
1472     );
1473
1474     # Weird use case to highlight issue
1475     $item_type = '0';
1476     Koha::ItemTypes->search( { itemtype => $item_type } )->delete;
1477     my $itemtype = $builder->build_object(
1478         {
1479             class => 'Koha::ItemTypes',
1480             value => { itemtype => $item_type }
1481         }
1482     );
1483     ok(
1484         C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ),
1485         "Item not available for item-level hold because no effective item type"
1486     );
1487
1488     Koha::CirculationRules->set_rules(
1489         {
1490             categorycode => '*',
1491             itemtype     => '*',
1492             branchcode   => '*',
1493             rules        => {
1494                 onshelfholds => 0,
1495             }
1496         }
1497     );
1498     my $item_1 = $builder->build_sample_item( { notforloan => -1 } );
1499     ok(
1500         C4::Reserves::IsAvailableForItemLevelRequest( $item_1, $patron ),
1501         "We can placing hold on item with negative not for loan values when 'On shelf holds allowed' is set to 'If any unavailable'"
1502     );
1503     $schema->storage->txn_rollback;
1504 };
1505
1506 subtest 'AddReserve() tests' => sub {
1507
1508     plan tests => 2;
1509
1510     $schema->storage->txn_begin;
1511
1512     t::lib::Mocks::mock_preference( 'TrackLastPatronActivityTriggers', 'hold' );
1513
1514     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1515     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { lastseen => undef } } );
1516     my $biblio  = $builder->build_sample_biblio;
1517
1518     my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1519     $mock->mock( 'enqueue', sub {
1520         my ( $self, $args ) = @_;
1521         is_deeply(
1522             $args->{biblio_ids},
1523             [ $biblio->id ],
1524             "AddReserve triggers a holds queue update for the related biblio"
1525         );
1526     } );
1527
1528     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1529
1530     AddReserve(
1531         {
1532             branchcode     => $library->branchcode,
1533             borrowernumber => $patron->id,
1534             biblionumber   => $biblio->id,
1535         }
1536     );
1537
1538     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1539
1540     AddReserve(
1541         {
1542             branchcode     => $library->branchcode,
1543             borrowernumber => $patron->id,
1544             biblionumber   => $biblio->id,
1545         }
1546     );
1547
1548     $patron->discard_changes;
1549     isnt( $patron->lastseen, undef, "Patron activity tracked when hold is a valid trigger" );
1550
1551     $schema->storage->txn_rollback;
1552 };
1553
1554 subtest 'AlterPriorty() tests' => sub {
1555
1556     plan tests => 2;
1557
1558     $schema->storage->txn_begin;
1559
1560     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1561     my $patron_1  = $builder->build_object({ class => 'Koha::Patrons' });
1562     my $patron_2  = $builder->build_object({ class => 'Koha::Patrons' });
1563     my $patron_3  = $builder->build_object({ class => 'Koha::Patrons' });
1564     my $biblio  = $builder->build_sample_biblio;
1565
1566     my $reserve_id = AddReserve(
1567         {
1568             branchcode     => $library->branchcode,
1569             borrowernumber => $patron_1->id,
1570             biblionumber   => $biblio->id,
1571         }
1572     );
1573     AddReserve(
1574         {
1575             branchcode     => $library->branchcode,
1576             borrowernumber => $patron_2->id,
1577             biblionumber   => $biblio->id,
1578         }
1579     );
1580     AddReserve(
1581         {
1582             branchcode     => $library->branchcode,
1583             borrowernumber => $patron_3->id,
1584             biblionumber   => $biblio->id,
1585         }
1586     );
1587
1588     my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1589     $mock->mock( 'enqueue', sub {
1590         my ( $self, $args ) = @_;
1591         is_deeply(
1592             $args->{biblio_ids},
1593             [ $biblio->id ],
1594             "AlterPriority triggers a holds queue update for the related biblio"
1595         );
1596     } );
1597
1598     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1599
1600     AlterPriority( "bottom", $reserve_id, 1, 2, 1, 3 );
1601
1602     my $hold = Koha::Holds->find($reserve_id);
1603
1604     is($hold->priority,3,'Successfully altered priority to bottom');
1605
1606     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1607
1608     AlterPriority( "bottom", $reserve_id, 1, 2, 1, 3 );
1609
1610     $schema->storage->txn_rollback;
1611 };
1612
1613 subtest 'CanBookBeReserved() tests' => sub {
1614
1615     plan tests => 2;
1616
1617     $schema->storage->txn_begin;
1618
1619     my $library = $builder->build_object(
1620         { class => 'Koha::Libraries', value => { pickup_location => 1 } } );
1621     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1622     my $itype  = $builder->build_object( { class => 'Koha::ItemTypes' } );
1623
1624     my $biblio = $builder->build_sample_biblio();
1625     my $item_1 = $builder->build_sample_item(
1626         { biblionumber => $biblio->id, itype => $itype->id } );
1627     my $item_2 = $builder->build_sample_item(
1628         { biblionumber => $biblio->id, itype => $itype->id } );
1629
1630     Koha::CirculationRules->delete;
1631     Koha::CirculationRules->set_rules(
1632         {
1633             branchcode   => undef,
1634             categorycode => undef,
1635             itemtype     => undef,
1636             rules        => {
1637                 holds_per_record => 100,
1638             }
1639         }
1640     );
1641     Koha::CirculationRules->set_rules(
1642         {
1643             branchcode   => undef,
1644             categorycode => undef,
1645             itemtype     => $itype->id,
1646             rules        => {
1647                 reservesallowed => 2,
1648             }
1649         }
1650     );
1651
1652     C4::Reserves::AddReserve(
1653         {
1654             branchcode     => $library->id,
1655             borrowernumber => $patron->id,
1656             biblionumber   => $biblio->id,
1657             title          => $biblio->title,
1658             itemnumber     => $item_1->id
1659         }
1660     );
1661
1662     ## Limit on item type is 2, only one hold, success tests
1663
1664     my $res = CanBookBeReserved( $patron->id, $biblio->id, $library->id,
1665         { itemtype => $itype->id } );
1666     is_deeply( $res, { status => 'OK' },
1667         'Holds on itemtype limit not reached' );
1668
1669     # Add a second hold, biblio-level and item type-constrained
1670     C4::Reserves::AddReserve(
1671         {
1672             branchcode     => $library->id,
1673             borrowernumber => $patron->id,
1674             biblionumber   => $biblio->id,
1675             title          => $biblio->title,
1676             itemtype       => $itype->id,
1677         }
1678     );
1679
1680     ## Limit on item type is 2, two holds, one of them biblio-level/item type-constrained
1681
1682     $res = CanBookBeReserved( $patron->id, $biblio->id, $library->id,
1683         { itemtype => $itype->id } );
1684     is_deeply( $res, { status => '' }, 'Holds on itemtype limit reached' );
1685
1686     $schema->storage->txn_rollback;
1687 };
1688
1689 subtest 'CanItemBeReserved() tests' => sub {
1690
1691     plan tests => 2;
1692
1693     $schema->storage->txn_begin;
1694
1695     my $library = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } );
1696     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
1697     my $itype   = $builder->build_object( { class => 'Koha::ItemTypes' } );
1698
1699     my $biblio = $builder->build_sample_biblio();
1700     my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->id, itype => $itype->id });
1701     my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->id, itype => $itype->id });
1702
1703     Koha::CirculationRules->delete;
1704     Koha::CirculationRules->set_rules(
1705         {   branchcode   => undef,
1706             categorycode => undef,
1707             itemtype     => undef,
1708             rules        => {
1709                 holds_per_record => 100,
1710             }
1711         }
1712     );
1713     Koha::CirculationRules->set_rules(
1714         {   branchcode   => undef,
1715             categorycode => undef,
1716             itemtype     => $itype->id,
1717             rules        => {
1718                 reservesallowed => 2,
1719             }
1720         }
1721     );
1722
1723     C4::Reserves::AddReserve(
1724         {
1725             branchcode     => $library->id,
1726             borrowernumber => $patron->id,
1727             biblionumber   => $biblio->id,
1728             title          => $biblio->title,
1729             itemnumber     => $item_1->id
1730         }
1731     );
1732
1733     ## Limit on item type is 2, only one hold, success tests
1734
1735     my $res = CanItemBeReserved( $patron, $item_2, $library->id );
1736     is_deeply( $res, { status => 'OK' }, 'Holds on itemtype limit not reached' );
1737
1738     # Add a second hold, biblio-level and item type-constrained
1739     C4::Reserves::AddReserve(
1740         {
1741             branchcode     => $library->id,
1742             borrowernumber => $patron->id,
1743             biblionumber   => $biblio->id,
1744             title          => $biblio->title,
1745             itemtype       => $itype->id,
1746         }
1747     );
1748
1749     ## Limit on item type is 2, two holds, one of them biblio-level/item type-constrained
1750
1751     $res = CanItemBeReserved( $patron, $item_2, $library->id );
1752     is_deeply( $res, { status => 'tooManyReserves', limit => 2 }, 'Holds on itemtype limit reached' );
1753
1754     $schema->storage->txn_rollback;
1755 };
1756
1757 subtest 'DefaultHoldExpiration tests' => sub {
1758     plan tests => 2;
1759     $schema->storage->txn_begin;
1760
1761     t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdate', 1 );
1762     t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdatePeriod', 365 );
1763     t::lib::Mocks::mock_preference( 'DefaultHoldExpirationUnitOfTime', 'days;' );
1764
1765     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
1766     my $item    = $builder->build_sample_item();
1767
1768     my $reserve_id = AddReserve({
1769         branchcode     => $item->homebranch,
1770         borrowernumber => $patron->id,
1771         biblionumber   => $item->biblionumber,
1772     });
1773
1774     my $today = dt_from_string();
1775     my $hold = Koha::Holds->find( $reserve_id );
1776
1777     is( $hold->reservedate, $today->ymd, "Hold created today" );
1778     is( $hold->expirationdate, $today->add( days => 365)->ymd, "Reserve date set 1 year from today" );
1779
1780     $schema->txn_rollback;
1781 };
1782
1783 subtest '_Findgroupreserves' => sub {
1784     plan tests => 6;
1785     $schema->storage->txn_begin;
1786
1787     my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } );
1788     my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } );
1789     my $item     = $builder->build_sample_item();
1790     my $item_2   = $builder->build_sample_item( { biblionumber => $item->biblionumber } );
1791
1792     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1793     my $reserve_id_1 = AddReserve(
1794         {
1795             branchcode     => $item->homebranch,
1796             borrowernumber => $patron_1->id,
1797             biblionumber   => $item->biblionumber,
1798         }
1799     );
1800     my $reserve_id_2 = AddReserve(
1801         {
1802             branchcode     => $item->homebranch,
1803             borrowernumber => $patron_2->id,
1804             biblionumber   => $item->biblionumber,
1805         }
1806     );
1807
1808     C4::HoldsQueue::AddToHoldTargetMap(
1809         {
1810             $item->id => {
1811                 borrowernumber => $patron_1->id,        biblionumber => $item->biblionumber,
1812                 holdingbranch  => $item->holdingbranch, item_level   => 0, reserve_id => $reserve_id_1
1813             }
1814         }
1815     );
1816
1817     # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1818     my @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item->id, 0, [] );
1819     is( scalar @reserves,           1,             "We should only get the hold that is in the map" );
1820     is( $reserves[0]->{reserve_id}, $reserve_id_1, "We got the expected reserve" );
1821
1822     C4::HoldsQueue::AddToHoldTargetMap(
1823         {
1824             $item_2->id => {
1825                 borrowernumber => $patron_2->id, biblionumber => $item->biblionumber,
1826                 holdingbranch  => $item->holdingbranch, item_level => 1, reserve_id => $reserve_id_2
1827             }
1828         }
1829     );
1830
1831     # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1832     @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item_2->id, 0, [] );
1833     is( scalar @reserves,           1,             "We should only get the item level hold that is in the map" );
1834     is( $reserves[0]->{reserve_id}, $reserve_id_2, "We got the expected reserve" );
1835
1836     C4::HoldsQueue::AddToHoldTargetMap(
1837         {
1838             $item_2->id => {
1839                 borrowernumber => $patron_2->id, biblionumber => $item->biblionumber,
1840                 holdingbranch  => $item->holdingbranch, item_level => 1, reserve_id => $reserve_id_1
1841             }
1842         }
1843     );
1844
1845     # When the hold is title level and in the hold fill targets we expect this to be the only hold returned
1846     @reserves = C4::Reserves::_Findgroupreserve( $item->biblionumber, $item_2->id, 0, [] );
1847     is( scalar @reserves,           1,             "We should still only get the item level hold that is in the map" );
1848     is( $reserves[0]->{reserve_id}, $reserve_id_1, "We got the expected reserve which has been updated" );
1849
1850
1851
1852     $schema->txn_rollback;
1853 };
1854
1855 subtest 'HOLDDGST tests' => sub {
1856
1857     plan tests => 2;
1858     $schema->storage->txn_begin;
1859
1860     my $branch = $builder->build_object(
1861         {
1862             class => 'Koha::Libraries',
1863             value => {
1864                 branchemail     => 'branch@e.mail',
1865                 branchreplyto   => 'branch@reply.to',
1866                 pickup_location => 1
1867             }
1868         }
1869     );
1870     my $item = $builder->build_sample_item(
1871         {
1872             homebranch    => $branch->branchcode,
1873             holdingbranch => $branch->branchcode
1874         }
1875     );
1876     my $item2 = $builder->build_sample_item(
1877         {
1878             homebranch    => $branch->branchcode,
1879             holdingbranch => $branch->branchcode
1880         }
1881     );
1882
1883     my $wants_hold_and_email = {
1884         wants_digest => '1',
1885         transports   => {
1886             sms   => 'HOLDDGST',
1887             email => 'HOLDDGST',
1888         },
1889         letter_code => 'HOLDDGST'
1890     };
1891
1892     my $mp = Test::MockModule->new('C4::Members::Messaging');
1893
1894     $mp->mock( "GetMessagingPreferences", $wants_hold_and_email );
1895
1896     $dbh->do('DELETE FROM letter');
1897
1898     my $email_hold_notice = $builder->build(
1899         {
1900             source => 'Letter',
1901             value  => {
1902                 message_transport_type => 'email',
1903                 branchcode             => '',
1904                 code                   => 'HOLDDGST',
1905                 module                 => 'reserves',
1906                 lang                   => 'default',
1907             }
1908         }
1909     );
1910
1911     my $sms_hold_notice = $builder->build(
1912         {
1913             source => 'Letter',
1914             value  => {
1915                 message_transport_type => 'sms',
1916                 branchcode             => '',
1917                 code                   => 'HOLDDGST',
1918                 module                 => 'reserves',
1919                 lang                   => 'default',
1920             }
1921         }
1922     );
1923
1924     my $hold_borrower = $builder->build(
1925         {
1926             source => 'Borrower',
1927             value  => {
1928                 smsalertnumber => '5555555551',
1929                 email          => 'a@c.com',
1930             }
1931         }
1932     )->{borrowernumber};
1933
1934     C4::Reserves::AddReserve(
1935         {
1936             branchcode     => $item->homebranch,
1937             borrowernumber => $hold_borrower,
1938             biblionumber   => $item->biblionumber,
1939         }
1940     );
1941
1942     C4::Reserves::AddReserve(
1943         {
1944             branchcode     => $item2->homebranch,
1945             borrowernumber => $hold_borrower,
1946             biblionumber   => $item2->biblionumber,
1947         }
1948     );
1949
1950     ModReserveAffect( $item->itemnumber,  $hold_borrower, 0 );
1951     ModReserveAffect( $item2->itemnumber, $hold_borrower, 0 );
1952
1953     my $sms_count = $schema->resultset('MessageQueue')->search(
1954         {
1955             letter_code            => 'HOLDDGST',
1956             message_transport_type => 'sms',
1957             borrowernumber         => $hold_borrower,
1958         }
1959     )->count;
1960     is( $sms_count, 1, "Only one sms hold digest message created for two holds" );
1961
1962     my $email_count = $schema->resultset('MessageQueue')->search(
1963         {
1964             letter_code            => 'HOLDDGST',
1965             message_transport_type => 'email',
1966             borrowernumber         => $hold_borrower,
1967         }
1968     )->count;
1969     is( $email_count, 1, "Only one email hold digest message created for two holds" );
1970
1971     $schema->txn_rollback;
1972 };