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