Bug 32121: (QA follow-up): Fix unit tests count
[koha-ffzg.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 => 3;
793
794     my $branch = $builder->build_object({
795         class => 'Koha::Libraries',
796         value => {
797             branchemail => 'branch@e.mail',
798             branchreplyto => 'branch@reply.to',
799             pickup_location => 1
800         }
801     });
802     my $item = $builder->build_sample_item({
803         homebranch => $branch->branchcode,
804         holdingbranch => $branch->branchcode
805     });
806
807     my $wants_hold_and_email = {
808         wants_digest => '0',
809         transports => {
810             sms => 'HOLD',
811             email => 'HOLD',
812             },
813         letter_code => 'HOLD'
814     };
815
816     my $mp = Test::MockModule->new( 'C4::Members::Messaging' );
817
818     $mp->mock("GetMessagingPreferences",$wants_hold_and_email);
819
820     $dbh->do('DELETE FROM letter');
821
822     my $email_hold_notice = $builder->build({
823             source => 'Letter',
824             value => {
825                 message_transport_type => 'email',
826                 branchcode => '',
827                 code => 'HOLD',
828                 module => 'reserves',
829                 lang => 'default',
830             }
831         });
832
833     my $sms_hold_notice = $builder->build({
834             source => 'Letter',
835             value => {
836                 message_transport_type => 'sms',
837                 branchcode => '',
838                 code => 'HOLD',
839                 module => 'reserves',
840                 lang=>'default',
841             }
842         });
843
844     my $hold_borrower = $builder->build({
845             source => 'Borrower',
846             value => {
847                 smsalertnumber=>'5555555555',
848                 email=>'a@b.com',
849             }
850         })->{borrowernumber};
851
852     C4::Reserves::AddReserve(
853         {
854             branchcode     => $item->homebranch,
855             borrowernumber => $hold_borrower,
856             biblionumber   => $item->biblionumber,
857         }
858     );
859
860     ModReserveAffect($item->itemnumber, $hold_borrower, 0);
861     my $sms_message_address = $schema->resultset('MessageQueue')->search({
862             letter_code     => 'HOLD',
863             message_transport_type => 'sms',
864             borrowernumber => $hold_borrower,
865         })->next()->to_address();
866     is($sms_message_address, undef ,"We should not populate the sms message with the sms number, sending will do so");
867
868     my $email = $schema->resultset('MessageQueue')->search({
869             letter_code     => 'HOLD',
870             message_transport_type => 'email',
871             borrowernumber => $hold_borrower,
872         })->next();
873     my $email_to_address = $email->to_address();
874     is($email_to_address, undef ,"We should not populate the hold message with the email address, sending will do so");
875     my $email_from_address = $email->from_address();
876     is($email_from_address,'branch@e.mail',"Library's from address is used for sending");
877
878 };
879
880 subtest 'ReservesNeedReturns' => sub {
881     plan tests => 18;
882
883     my $library    = $builder->build_object( { class => 'Koha::Libraries' } );
884     my $item_info  = {
885         homebranch       => $library->branchcode,
886         holdingbranch    => $library->branchcode,
887     };
888     my $item = $builder->build_sample_item($item_info);
889     my $patron   = $builder->build_object(
890         {
891             class => 'Koha::Patrons',
892             value => { branchcode => $library->branchcode, }
893         }
894     );
895     my $patron_2   = $builder->build_object(
896         {
897             class => 'Koha::Patrons',
898             value => { branchcode => $library->branchcode, }
899         }
900     );
901
902     my $priority = 1;
903
904     t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Test with feature disabled
905     my $hold = place_item_hold( $patron, $item, $library, $priority );
906     is( $hold->priority, $priority, 'If ReservesNeedReturns is 1, priority must not have been set to changed' );
907     is( $hold->found, undef, 'If ReservesNeedReturns is 1, found must not have been set waiting' );
908     $hold->delete;
909
910     t::lib::Mocks::mock_preference('ReservesNeedReturns', 0); # '0' means 'Automatically mark a hold as found and waiting'
911     $hold = place_item_hold( $patron, $item, $library, $priority );
912     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
913     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
914     $hold->delete;
915
916     $item->onloan('2010-01-01')->store;
917     $hold = place_item_hold( $patron, $item, $library, $priority );
918     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item onloan priority must be set to 1' );
919     $hold->delete;
920
921     t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 0); # '0' means damaged holds not allowed
922     $item->onloan(undef)->damaged(1)->store;
923     $hold = place_item_hold( $patron, $item, $library, $priority );
924     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item damaged and not allowed holds on damaged items priority must be set to 1' );
925     $hold->delete;
926     t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 1); # '0' means damaged holds not allowed
927     $hold = place_item_hold( $patron, $item, $library, $priority );
928     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and damaged holds allowed, priority must have been set to 0' );
929     is( $hold->found,  'W', 'If ReservesNeedReturns is 0 and damaged holds allowed, found must have been set waiting' );
930     $hold->delete;
931
932     my $hold_1 = place_item_hold( $patron, $item, $library, $priority );
933     is( $hold_1->found,  'W', 'First hold on item is set to waiting with ReservesNeedReturns set to 0' );
934     is( $hold_1->priority, 0, 'First hold on item is set to waiting with ReservesNeedReturns set to 0' );
935     $hold = place_item_hold( $patron_2, $item, $library, $priority );
936     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item already on hold priority must be set to 1' );
937     $hold->delete;
938     $hold_1->delete;
939
940     my $transfer = $builder->build_object({
941         class => "Koha::Item::Transfers",
942         value => {
943           itemnumber  => $item->itemnumber,
944           datearrived => undef,
945           datecancelled => undef
946         }
947     });
948     $item->damaged(0)->store;
949     $hold = place_item_hold( $patron, $item, $library, $priority );
950     is( $hold->found, undef, 'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
951     is( $hold->priority, 1,  'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
952     $hold->delete;
953     $transfer->delete;
954
955     $hold = place_item_hold( $patron, $item, $library, $priority );
956     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
957     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
958     $hold_1 = place_item_hold( $patron, $item, $library, $priority );
959     is( $hold_1->priority, 1, 'If ReservesNeedReturns is 0 but item has a hold priority is 1' );
960     $hold_1->suspend(1)->store; # We suspend the hold
961     $hold->delete; # Delete the waiting hold
962     $hold = place_item_hold( $patron, $item, $library, $priority );
963     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and other hold(s) suspended, priority must have been set to 0' );
964     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and other  hold(s) suspended, found must have been set waiting' );
965
966
967
968
969     t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Don't affect other tests
970 };
971
972 subtest 'ChargeReserveFee tests' => sub {
973
974     plan tests => 8;
975
976     my $library = $builder->build_object({ class => 'Koha::Libraries' });
977     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
978
979     my $fee   = 20;
980     my $title = 'A title';
981
982     my $context = Test::MockModule->new('C4::Context');
983     $context->mock( userenv => { branch => $library->id } );
984
985     my $line = C4::Reserves::ChargeReserveFee( $patron->id, $fee, $title );
986
987     is( ref($line), 'Koha::Account::Line' , 'Returns a Koha::Account::Line object');
988     ok( $line->is_debit, 'Generates a debit line' );
989     is( $line->debit_type_code, 'RESERVE' , 'generates RESERVE debit_type');
990     is( $line->borrowernumber, $patron->id , 'generated line belongs to the passed patron');
991     is( $line->amount, $fee , 'amount set correctly');
992     is( $line->amountoutstanding, $fee , 'amountoutstanding set correctly');
993     is( $line->description, "$title" , 'description is title of reserved item');
994     is( $line->branchcode, $library->id , "Library id is picked from userenv and stored correctly" );
995 };
996
997 subtest 'reserves.item_level_hold' => sub {
998     plan tests => 2;
999
1000     my $item   = $builder->build_sample_item;
1001     my $patron = $builder->build_object(
1002         {
1003             class => 'Koha::Patrons',
1004             value => { branchcode => $item->homebranch }
1005         }
1006     );
1007
1008     subtest 'item level hold' => sub {
1009         plan tests => 3;
1010         my $reserve_id = AddReserve(
1011             {
1012                 branchcode     => $item->homebranch,
1013                 borrowernumber => $patron->borrowernumber,
1014                 biblionumber   => $item->biblionumber,
1015                 priority       => 1,
1016                 itemnumber     => $item->itemnumber,
1017             }
1018         );
1019
1020         my $hold = Koha::Holds->find($reserve_id);
1021         is( $hold->item_level_hold, 1, 'item_level_hold should be set when AddReserve is called with a specific item' );
1022
1023         # Mark it waiting
1024         ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
1025
1026         my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1027         $mock->mock( 'enqueue', sub {
1028             my ( $self, $args ) = @_;
1029             is_deeply(
1030                 $args->{biblio_ids},
1031                 [ $hold->biblionumber ],
1032                 "AlterPriority triggers a holds queue update for the related biblio"
1033             );
1034         } );
1035
1036         t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1037
1038         # Revert the waiting status
1039         C4::Reserves::RevertWaitingStatus(
1040             { itemnumber => $item->itemnumber } );
1041
1042         $hold = Koha::Holds->find($reserve_id);
1043
1044         is( $hold->itemnumber, $item->itemnumber, 'Itemnumber should not be removed when the waiting status is revert' );
1045
1046         t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1047
1048         $hold->set_waiting;
1049
1050         # Revert the waiting status, RealTimeHoldsQueue => shouldn't add a test
1051         C4::Reserves::RevertWaitingStatus(
1052             { itemnumber => $item->itemnumber } );
1053
1054         $hold->delete;    # cleanup
1055     };
1056
1057     subtest 'biblio level hold' => sub {
1058         plan tests => 3;
1059         my $reserve_id = AddReserve(
1060             {
1061                 branchcode     => $item->homebranch,
1062                 borrowernumber => $patron->borrowernumber,
1063                 biblionumber   => $item->biblionumber,
1064                 priority       => 1,
1065             }
1066         );
1067
1068         my $hold = Koha::Holds->find($reserve_id);
1069         is( $hold->item_level_hold, 0, 'item_level_hold should not be set when AddReserve is called without a specific item' );
1070
1071         # Mark it waiting
1072         ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
1073
1074         $hold = Koha::Holds->find($reserve_id);
1075         is( $hold->itemnumber, $item->itemnumber, 'Itemnumber should be set on hold confirmation' );
1076
1077         # Revert the waiting status
1078         C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1079
1080         $hold = Koha::Holds->find($reserve_id);
1081         is( $hold->itemnumber, undef, 'Itemnumber should be removed when the waiting status is revert' );
1082
1083         $hold->delete;
1084     };
1085
1086 };
1087
1088 subtest 'MoveReserve additional test' => sub {
1089
1090     plan tests => 4;
1091
1092     # Create the items and patrons we need
1093     my $biblio = $builder->build_sample_biblio();
1094     my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
1095     my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1096     my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber, notforloan => 0, itype => $itype->itemtype });
1097     my $patron_1 = $builder->build_object({ class => "Koha::Patrons" });
1098     my $patron_2 = $builder->build_object({ class => "Koha::Patrons" });
1099
1100     # Place a hold on the title for both patrons
1101     my $reserve_1 = AddReserve(
1102         {
1103             branchcode     => $item_1->homebranch,
1104             borrowernumber => $patron_1->borrowernumber,
1105             biblionumber   => $biblio->biblionumber,
1106             priority       => 1,
1107             itemnumber     => $item_1->itemnumber,
1108         }
1109     );
1110     my $reserve_2 = AddReserve(
1111         {
1112             branchcode     => $item_2->homebranch,
1113             borrowernumber => $patron_2->borrowernumber,
1114             biblionumber   => $biblio->biblionumber,
1115             priority       => 1,
1116             itemnumber     => $item_1->itemnumber,
1117         }
1118     );
1119     is($patron_1->holds->next()->reserve_id, $reserve_1, "The 1st patron has a hold");
1120     is($patron_2->holds->next()->reserve_id, $reserve_2, "The 2nd patron has a hold");
1121
1122     # Fake the holds queue
1123     $dbh->do(q{INSERT INTO hold_fill_targets VALUES (?, ?, ?, ?, ?,?)},undef,($patron_1->borrowernumber,$biblio->biblionumber,$item_1->itemnumber,$item_1->homebranch,0,$reserve_1));
1124
1125     # The 2nd hold should be filed even if the item is preselected for the first hold
1126     MoveReserve($item_1->itemnumber,$patron_2->borrowernumber);
1127     is($patron_2->holds->count, 0, "The 2nd patrons no longer has a hold");
1128     is($patron_2->old_holds->next()->reserve_id, $reserve_2, "The 2nd patrons hold was filled and moved to old holds");
1129
1130 };
1131
1132 subtest 'RevertWaitingStatus' => sub {
1133
1134     plan tests => 2;
1135
1136     # Create the items and patrons we need
1137     my $biblio  = $builder->build_sample_biblio();
1138     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1139     my $itype   = $builder->build_object(
1140         { class => "Koha::ItemTypes", value => { notforloan => 0 } } );
1141     my $item_1 = $builder->build_sample_item(
1142         {
1143             biblionumber => $biblio->biblionumber,
1144             itype        => $itype->itemtype,
1145             library      => $library->branchcode
1146         }
1147     );
1148     my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1149     my $patron_2 = $builder->build_object( { class => "Koha::Patrons" } );
1150     my $patron_3 = $builder->build_object( { class => "Koha::Patrons" } );
1151     my $patron_4 = $builder->build_object( { class => "Koha::Patrons" } );
1152
1153     # Place a hold on the title for both patrons
1154     my $priority = 1;
1155     my $hold_1 = place_item_hold( $patron_1, $item_1, $library, $priority );
1156     my $hold_2 = place_item_hold( $patron_2, $item_1, $library, $priority );
1157     my $hold_3 = place_item_hold( $patron_3, $item_1, $library, $priority );
1158     my $hold_4 = place_item_hold( $patron_4, $item_1, $library, $priority );
1159
1160     $hold_1->set_waiting;
1161     AddIssue( $patron_3->unblessed, $item_1->barcode, undef, 'revert' );
1162
1163     my $holds = $biblio->holds;
1164     is( $holds->count, 3, 'One hold has been deleted' );
1165     is_deeply(
1166         [
1167             $holds->next->priority, $holds->next->priority,
1168             $holds->next->priority
1169         ],
1170         [ 1, 2, 3 ],
1171         'priorities have been reordered'
1172     );
1173 };
1174
1175 subtest 'CheckReserves additional tests' => sub {
1176
1177     plan tests => 8;
1178
1179     my $item = $builder->build_sample_item;
1180     my $reserve1 = $builder->build_object(
1181         {
1182             class => "Koha::Holds",
1183             value => {
1184                 found            => undef,
1185                 priority         => 1,
1186                 itemnumber       => undef,
1187                 biblionumber     => $item->biblionumber,
1188                 waitingdate      => undef,
1189                 cancellationdate => undef,
1190                 item_level_hold  => 0,
1191                 lowestPriority   => 0,
1192                 expirationdate   => undef,
1193                 suspend_until    => undef,
1194                 suspend          => 0,
1195                 itemtype         => undef,
1196             }
1197         }
1198     );
1199     my $reserve2 = $builder->build_object(
1200         {
1201             class => "Koha::Holds",
1202             value => {
1203                 found            => undef,
1204                 priority         => 2,
1205                 biblionumber     => $item->biblionumber,
1206                 borrowernumber   => $reserve1->borrowernumber,
1207                 itemnumber       => undef,
1208                 waitingdate      => undef,
1209                 cancellationdate => undef,
1210                 item_level_hold  => 0,
1211                 lowestPriority   => 0,
1212                 expirationdate   => undef,
1213                 suspend_until    => undef,
1214                 suspend          => 0,
1215                 itemtype         => undef,
1216             }
1217         }
1218     );
1219
1220     my $tmp_holdsqueue = $builder->build(
1221         {
1222             source => 'TmpHoldsqueue',
1223             value  => {
1224                 borrowernumber => $reserve1->borrowernumber,
1225                 biblionumber   => $reserve1->biblionumber,
1226             }
1227         }
1228     );
1229     my $fill_target = $builder->build(
1230         {
1231             source => 'HoldFillTarget',
1232             value  => {
1233                 borrowernumber     => $reserve1->borrowernumber,
1234                 biblionumber       => $reserve1->biblionumber,
1235                 itemnumber         => $item->itemnumber,
1236                 item_level_request => 0,
1237             }
1238         }
1239     );
1240
1241     ModReserveAffect( $item->itemnumber, $reserve1->borrowernumber, 1,
1242         $reserve1->reserve_id );
1243     my ( $status, $matched_reserve, $possible_reserves ) =
1244       CheckReserves( $item->itemnumber );
1245
1246     is( $status, 'Transferred', "We found a reserve" );
1247     is( $matched_reserve->{reserve_id},
1248         $reserve1->reserve_id, "We got the Transit reserve" );
1249     is( scalar @$possible_reserves, 2, 'We do get both reserves' );
1250
1251     my $patron_B = $builder->build_object({ class => "Koha::Patrons" });
1252     my $item_A = $builder->build_sample_item;
1253     my $item_B = $builder->build_sample_item({
1254         homebranch => $patron_B->branchcode,
1255         biblionumber => $item_A->biblionumber,
1256         itype => $item_A->itype
1257     });
1258     Koha::CirculationRules->set_rules(
1259         {
1260             branchcode   => undef,
1261             categorycode => undef,
1262             itemtype     => $item_A->itype,
1263             rules        => {
1264                 reservesallowed => 25,
1265                 holds_per_record => 1,
1266             }
1267         }
1268     );
1269     Koha::CirculationRules->set_rule({
1270         branchcode => undef,
1271         itemtype   => $item_A->itype,
1272         rule_name  => 'holdallowed',
1273         rule_value => 'from_home_library'
1274     });
1275     my $reserve_id = AddReserve(
1276         {
1277             branchcode     => $patron_B->branchcode,
1278             borrowernumber => $patron_B->borrowernumber,
1279             biblionumber   => $item_A->biblionumber,
1280             priority       => 1,
1281             itemnumber     => undef,
1282         }
1283     );
1284
1285     ok( $reserve_id, "We can place a record level hold because one item is owned by patron's home library");
1286     t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary');
1287     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A->itemnumber );
1288     is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch");
1289     Koha::CirculationRules->set_rule({
1290         branchcode => $item_A->homebranch,
1291         itemtype   => $item_A->itype,
1292         rule_name  => 'holdallowed',
1293         rule_value => 'from_any_library'
1294     });
1295     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A->itemnumber );
1296     is( $status, "Reserved", "We fill the hold with item A because item's branch rule says allow any");
1297
1298
1299     # Changing the control branch should change only the rule we get
1300     t::lib::Mocks::mock_preference('ReservesControlBranch', 'PatronLibrary');
1301     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A->itemnumber );
1302     is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch");
1303     Koha::CirculationRules->set_rule({
1304         branchcode   => $patron_B->branchcode,
1305         itemtype   => $item_A->itype,
1306         rule_name  => 'holdallowed',
1307         rule_value => 'from_any_library'
1308     });
1309     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A->itemnumber );
1310     is( $status, "Reserved", "We fill the hold with item A because patron's branch rule says allow any");
1311
1312 };
1313
1314 subtest 'AllowHoldOnPatronPossession test' => sub {
1315
1316     plan tests => 4;
1317
1318     # Create the items and patrons we need
1319     my $biblio = $builder->build_sample_biblio();
1320     my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
1321     my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1322     my $patron = $builder->build_object({ class => "Koha::Patrons",
1323                                           value => { branchcode => $item->homebranch }});
1324
1325     C4::Circulation::AddIssue($patron->unblessed,
1326                               $item->barcode);
1327     t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 0);
1328
1329     is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1330                                        $item->biblionumber)->{status},
1331        'alreadypossession',
1332        'Patron cannot place hold on a book loaned to itself');
1333
1334     is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status},
1335        'alreadypossession',
1336        'Patron cannot place hold on an item loaned to itself');
1337
1338     t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 1);
1339
1340     is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1341                                        $item->biblionumber)->{status},
1342        'OK',
1343        'Patron can place hold on a book loaned to itself');
1344
1345     is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status},
1346        'OK',
1347        'Patron can place hold on an item loaned to itself');
1348 };
1349
1350 subtest 'MergeHolds' => sub {
1351
1352     plan tests => 1;
1353
1354     my $biblio_1  = $builder->build_sample_biblio();
1355     my $biblio_2  = $builder->build_sample_biblio();
1356     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1357     my $itype   = $builder->build_object(
1358         { class => "Koha::ItemTypes", value => { notforloan => 0 } } );
1359     my $item_1 = $builder->build_sample_item(
1360         {
1361             biblionumber => $biblio_1->biblionumber,
1362             itype        => $itype->itemtype,
1363             library      => $library->branchcode
1364         }
1365     );
1366     my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1367
1368     # Place a hold on $biblio_1
1369     my $priority = 1;
1370     place_item_hold( $patron_1, $item_1, $library, $priority );
1371
1372     # Move and make sure hold is now on $biblio_2
1373     C4::Reserves::MergeHolds($dbh, $biblio_2->biblionumber, $biblio_1->biblionumber);
1374     is( $biblio_2->holds->count, 1, 'Hold has been transferred' );
1375 };
1376
1377 subtest 'ModReserveAffect logging' => sub {
1378
1379     plan tests => 4;
1380
1381     my $item = $builder->build_sample_item;
1382     my $patron = $builder->build_object(
1383         {
1384             class => "Koha::Patrons",
1385             value => { branchcode => $item->homebranch }
1386         }
1387     );
1388
1389     t::lib::Mocks::mock_userenv({ patron => $patron });
1390     t::lib::Mocks::mock_preference('HoldsLog', 1);
1391
1392     my $reserve_id = AddReserve(
1393         {
1394             branchcode     => $item->homebranch,
1395             borrowernumber => $patron->borrowernumber,
1396             biblionumber   => $item->biblionumber,
1397             priority       => 1,
1398             itemnumber     => $item->itemnumber,
1399         }
1400     );
1401
1402     my $hold = Koha::Holds->find($reserve_id);
1403     my $previous_timestamp = '1970-01-01 12:34:56';
1404     $hold->timestamp($previous_timestamp)->store;
1405
1406     $hold = Koha::Holds->find($reserve_id);
1407     is( $hold->timestamp, $previous_timestamp, 'Make sure the previous timestamp has been used' );
1408
1409     # Avoid warnings
1410     my $reserve_mock = Test::MockModule->new('C4::Reserves');
1411     $reserve_mock->mock( '_koha_notify_reserve', undef );
1412
1413     # Mark it waiting
1414     ModReserveAffect( $item->itemnumber, $patron->borrowernumber );
1415
1416     $hold->discard_changes;
1417     ok( $hold->is_waiting, 'Hold has been set waiting' );
1418     isnt( $hold->timestamp, $previous_timestamp, 'The timestamp has been modified' );
1419
1420     my $log = Koha::ActionLogs->search({ module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id })->next;
1421     my $expected = sprintf q{'timestamp' => '%s'}, $hold->timestamp;
1422     like( $log->info, qr{$expected}, 'Timestamp logged is the current one' );
1423 };
1424
1425 sub count_hold_print_messages {
1426     my $message_count = $dbh->selectall_arrayref(q{
1427         SELECT COUNT(*)
1428         FROM message_queue
1429         WHERE letter_code = 'HOLD' 
1430         AND   message_transport_type = 'print'
1431     });
1432     return $message_count->[0]->[0];
1433 }
1434
1435 sub place_item_hold {
1436     my ($patron,$item,$library,$priority) = @_;
1437
1438     my $hold_id = C4::Reserves::AddReserve(
1439         {
1440             branchcode     => $library->branchcode,
1441             borrowernumber => $patron->borrowernumber,
1442             biblionumber   => $item->biblionumber,
1443             priority       => $priority,
1444             title          => "title for fee",
1445             itemnumber     => $item->itemnumber,
1446         }
1447     );
1448
1449     my $hold = Koha::Holds->find($hold_id);
1450     return $hold;
1451 }
1452
1453 # we reached the finish
1454 $schema->storage->txn_rollback();
1455
1456 subtest 'IsAvailableForItemLevelRequest() tests' => sub {
1457
1458     plan tests => 2;
1459
1460     $schema->storage->txn_begin;
1461
1462     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1463
1464     my $item_type = undef;
1465
1466     my $item_mock = Test::MockModule->new('Koha::Item');
1467     $item_mock->mock( 'effective_itemtype', sub { return $item_type; } );
1468
1469     my $item = $builder->build_sample_item;
1470
1471     ok(
1472         !C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ),
1473         "Item not available for item-level hold because no effective item type"
1474     );
1475
1476     # Weird use case to highlight issue
1477     $item_type = '0';
1478     Koha::ItemTypes->search( { itemtype => $item_type } )->delete;
1479     my $itemtype = $builder->build_object(
1480         {
1481             class => 'Koha::ItemTypes',
1482             value => { itemtype => $item_type }
1483         }
1484     );
1485     ok(
1486         C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ),
1487         "Item not available for item-level hold because no effective item type"
1488     );
1489
1490     $schema->storage->txn_rollback;
1491 };
1492
1493 subtest 'AddReserve() tests' => sub {
1494
1495     plan tests => 1;
1496
1497     $schema->storage->txn_begin;
1498
1499     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1500     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
1501     my $biblio  = $builder->build_sample_biblio;
1502
1503     my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1504     $mock->mock( 'enqueue', sub {
1505         my ( $self, $args ) = @_;
1506         is_deeply(
1507             $args->{biblio_ids},
1508             [ $biblio->id ],
1509             "AddReserve triggers a holds queue update for the related biblio"
1510         );
1511     } );
1512
1513     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1514
1515     AddReserve(
1516         {
1517             branchcode     => $library->branchcode,
1518             borrowernumber => $patron->id,
1519             biblionumber   => $biblio->id,
1520         }
1521     );
1522
1523     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1524
1525     AddReserve(
1526         {
1527             branchcode     => $library->branchcode,
1528             borrowernumber => $patron->id,
1529             biblionumber   => $biblio->id,
1530         }
1531     );
1532
1533     $schema->storage->txn_rollback;
1534 };
1535
1536 subtest 'AlterPriorty() tests' => sub {
1537
1538     plan tests => 2;
1539
1540     $schema->storage->txn_begin;
1541
1542     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1543     my $patron_1  = $builder->build_object({ class => 'Koha::Patrons' });
1544     my $patron_2  = $builder->build_object({ class => 'Koha::Patrons' });
1545     my $patron_3  = $builder->build_object({ class => 'Koha::Patrons' });
1546     my $biblio  = $builder->build_sample_biblio;
1547
1548     my $reserve_id = AddReserve(
1549         {
1550             branchcode     => $library->branchcode,
1551             borrowernumber => $patron_1->id,
1552             biblionumber   => $biblio->id,
1553         }
1554     );
1555     AddReserve(
1556         {
1557             branchcode     => $library->branchcode,
1558             borrowernumber => $patron_2->id,
1559             biblionumber   => $biblio->id,
1560         }
1561     );
1562     AddReserve(
1563         {
1564             branchcode     => $library->branchcode,
1565             borrowernumber => $patron_3->id,
1566             biblionumber   => $biblio->id,
1567         }
1568     );
1569
1570     my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1571     $mock->mock( 'enqueue', sub {
1572         my ( $self, $args ) = @_;
1573         is_deeply(
1574             $args->{biblio_ids},
1575             [ $biblio->id ],
1576             "AlterPriority triggers a holds queue update for the related biblio"
1577         );
1578     } );
1579
1580     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1581
1582     AlterPriority( "bottom", $reserve_id, 1, 2, 1, 3 );
1583
1584     my $hold = Koha::Holds->find($reserve_id);
1585
1586     is($hold->priority,3,'Successfully altered priority to bottom');
1587
1588     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1589
1590     AlterPriority( "bottom", $reserve_id, 1, 2, 1, 3 );
1591
1592     $schema->storage->txn_rollback;
1593 };
1594
1595 subtest 'CanBookBeReserved() tests' => sub {
1596
1597     plan tests => 2;
1598
1599     $schema->storage->txn_begin;
1600
1601     my $library = $builder->build_object(
1602         { class => 'Koha::Libraries', value => { pickup_location => 1 } } );
1603     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1604     my $itype  = $builder->build_object( { class => 'Koha::ItemTypes' } );
1605
1606     my $biblio = $builder->build_sample_biblio();
1607     my $item_1 = $builder->build_sample_item(
1608         { biblionumber => $biblio->id, itype => $itype->id } );
1609     my $item_2 = $builder->build_sample_item(
1610         { biblionumber => $biblio->id, itype => $itype->id } );
1611
1612     Koha::CirculationRules->delete;
1613     Koha::CirculationRules->set_rules(
1614         {
1615             branchcode   => undef,
1616             categorycode => undef,
1617             itemtype     => undef,
1618             rules        => {
1619                 holds_per_record => 100,
1620             }
1621         }
1622     );
1623     Koha::CirculationRules->set_rules(
1624         {
1625             branchcode   => undef,
1626             categorycode => undef,
1627             itemtype     => $itype->id,
1628             rules        => {
1629                 reservesallowed => 2,
1630             }
1631         }
1632     );
1633
1634     C4::Reserves::AddReserve(
1635         {
1636             branchcode     => $library->id,
1637             borrowernumber => $patron->id,
1638             biblionumber   => $biblio->id,
1639             title          => $biblio->title,
1640             itemnumber     => $item_1->id
1641         }
1642     );
1643
1644     ## Limit on item type is 2, only one hold, success tests
1645
1646     my $res = CanBookBeReserved( $patron->id, $biblio->id, $library->id,
1647         { itemtype => $itype->id } );
1648     is_deeply( $res, { status => 'OK' },
1649         'Holds on itemtype limit not reached' );
1650
1651     # Add a second hold, biblio-level and item type-constrained
1652     C4::Reserves::AddReserve(
1653         {
1654             branchcode     => $library->id,
1655             borrowernumber => $patron->id,
1656             biblionumber   => $biblio->id,
1657             title          => $biblio->title,
1658             itemtype       => $itype->id,
1659         }
1660     );
1661
1662     ## Limit on item type is 2, two holds, one of them biblio-level/item type-constrained
1663
1664     $res = CanBookBeReserved( $patron->id, $biblio->id, $library->id,
1665         { itemtype => $itype->id } );
1666     is_deeply( $res, { status => '' }, 'Holds on itemtype limit reached' );
1667
1668     $schema->storage->txn_rollback;
1669 };
1670
1671 subtest 'CanItemBeReserved() tests' => sub {
1672
1673     plan tests => 2;
1674
1675     $schema->storage->txn_begin;
1676
1677     my $library = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } );
1678     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
1679     my $itype   = $builder->build_object( { class => 'Koha::ItemTypes' } );
1680
1681     my $biblio = $builder->build_sample_biblio();
1682     my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->id, itype => $itype->id });
1683     my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->id, itype => $itype->id });
1684
1685     Koha::CirculationRules->delete;
1686     Koha::CirculationRules->set_rules(
1687         {   branchcode   => undef,
1688             categorycode => undef,
1689             itemtype     => undef,
1690             rules        => {
1691                 holds_per_record => 100,
1692             }
1693         }
1694     );
1695     Koha::CirculationRules->set_rules(
1696         {   branchcode   => undef,
1697             categorycode => undef,
1698             itemtype     => $itype->id,
1699             rules        => {
1700                 reservesallowed => 2,
1701             }
1702         }
1703     );
1704
1705     C4::Reserves::AddReserve(
1706         {
1707             branchcode     => $library->id,
1708             borrowernumber => $patron->id,
1709             biblionumber   => $biblio->id,
1710             title          => $biblio->title,
1711             itemnumber     => $item_1->id
1712         }
1713     );
1714
1715     ## Limit on item type is 2, only one hold, success tests
1716
1717     my $res = CanItemBeReserved( $patron, $item_2, $library->id );
1718     is_deeply( $res, { status => 'OK' }, 'Holds on itemtype limit not reached' );
1719
1720     # Add a second hold, biblio-level and item type-constrained
1721     C4::Reserves::AddReserve(
1722         {
1723             branchcode     => $library->id,
1724             borrowernumber => $patron->id,
1725             biblionumber   => $biblio->id,
1726             title          => $biblio->title,
1727             itemtype       => $itype->id,
1728         }
1729     );
1730
1731     ## Limit on item type is 2, two holds, one of them biblio-level/item type-constrained
1732
1733     $res = CanItemBeReserved( $patron, $item_2, $library->id );
1734     is_deeply( $res, { status => 'tooManyReserves', limit => 2 }, 'Holds on itemtype limit reached' );
1735
1736     $schema->storage->txn_rollback;
1737 };