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