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