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