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