Bug 17539: (QA followup) Silence warnings
[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 => 72;
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::Biblio;
31 use C4::Circulation;
32 use C4::Items;
33 use C4::Members;
34 use C4::Reserves;
35 use Koha::DateUtils;
36 use Koha::Holds;
37 use Koha::Libraries;
38 use Koha::Patron::Categories;
39
40 BEGIN {
41     require_ok('C4::Reserves');
42 }
43
44 # a very minimal mack of userenv for use by the test of DelItemCheck
45 my $module = new Test::MockModule('C4::Context');
46 $module->mock('userenv', sub {
47     { }
48 });
49
50 my $dbh = C4::Context->dbh;
51
52 # Start transaction
53 my $database = Koha::Database->new();
54 my $schema = $database->schema();
55 $schema->storage->txn_begin();
56
57 my $builder = t::lib::TestBuilder->new;
58
59 # Somewhat arbitrary field chosen for age restriction unit tests. Must be added to db before the framework is cached
60 $dbh->do("update marc_subfield_structure set kohafield='biblioitems.agerestriction' where tagfield='521' and tagsubfield='a'");
61
62 ## Setup Test
63 # Add branches
64 my $branch_1 = $builder->build({ source => 'Branch' })->{ branchcode };
65 my $branch_2 = $builder->build({ source => 'Branch' })->{ branchcode };
66 my $branch_3 = $builder->build({ source => 'Branch' })->{ branchcode };
67 # Add categories
68 my $category_1 = $builder->build({ source => 'Category' })->{ categorycode };
69 my $category_2 = $builder->build({ source => 'Category' })->{ categorycode };
70 # Add an item type
71 my $itemtype = $builder->build(
72     { source => 'Itemtype', value => { notforloan => undef } } )->{itemtype};
73
74
75 # Create a helper biblio
76 my $bib = MARC::Record->new();
77 my $title = 'Silence in the library';
78 if( C4::Context->preference('marcflavour') eq 'UNIMARC' ) {
79     $bib->append_fields(
80         MARC::Field->new('600', '', '1', a => 'Moffat, Steven'),
81         MARC::Field->new('200', '', '', a => $title),
82     );
83 }
84 else {
85     $bib->append_fields(
86         MARC::Field->new('100', '', '', a => 'Moffat, Steven'),
87         MARC::Field->new('245', '', '', a => $title),
88     );
89 }
90 my ($bibnum, $bibitemnum);
91 ($bibnum, $title, $bibitemnum) = AddBiblio($bib, '');
92
93 # Create a helper item instance for testing
94 my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
95     {   homebranch    => $branch_1,
96         holdingbranch => $branch_1,
97         itype         => $itemtype
98     },
99     $bibnum
100 );
101
102
103 # Modify item; setting barcode.
104 my $testbarcode = '97531';
105 ModItem({ barcode => $testbarcode }, $bibnum, $itemnumber);
106
107 # Create a borrower
108 my %data = (
109     firstname =>  'my firstname',
110     surname => 'my surname',
111     categorycode => $category_1,
112     branchcode => $branch_1,
113 );
114 Koha::Patron::Categories->find($category_1)->set({ enrolmentfee => 0})->store;
115 my $borrowernumber = AddMember(%data);
116 my $borrower = GetMember( borrowernumber => $borrowernumber );
117 my $biblionumber   = $bibnum;
118 my $barcode        = $testbarcode;
119
120 my $bibitems       = '';
121 my $priority       = '1';
122 my $resdate        = undef;
123 my $expdate        = undef;
124 my $notes          = '';
125 my $checkitem      = undef;
126 my $found          = undef;
127
128 my $branchcode = Koha::Libraries->search->next->branchcode;
129
130 AddReserve($branchcode,    $borrowernumber, $biblionumber,
131         $bibitems,  $priority, $resdate, $expdate, $notes,
132         $title,      $checkitem, $found);
133
134 my ($status, $reserve, $all_reserves) = CheckReserves($itemnumber, $barcode);
135
136 is($status, "Reserved", "CheckReserves Test 1");
137
138 ok(exists($reserve->{reserve_id}), 'CheckReserves() include reserve_id in its response');
139
140 ($status, $reserve, $all_reserves) = CheckReserves($itemnumber);
141 is($status, "Reserved", "CheckReserves Test 2");
142
143 ($status, $reserve, $all_reserves) = CheckReserves(undef, $barcode);
144 is($status, "Reserved", "CheckReserves Test 3");
145
146 my $ReservesControlBranch = C4::Context->preference('ReservesControlBranch');
147 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
148 ok(
149     'ItemHomeLib' eq GetReservesControlBranch(
150         { homebranch => 'ItemHomeLib' },
151         { branchcode => 'PatronHomeLib' }
152     ), "GetReservesControlBranch returns item home branch when set to ItemHomeLibrary"
153 );
154 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
155 ok(
156     'PatronHomeLib' eq GetReservesControlBranch(
157         { homebranch => 'ItemHomeLib' },
158         { branchcode => 'PatronHomeLib' }
159     ), "GetReservesControlBranch returns patron home branch when set to PatronLibrary"
160 );
161 t::lib::Mocks::mock_preference( 'ReservesControlBranch', $ReservesControlBranch );
162
163 ###
164 ### Regression test for bug 10272
165 ###
166 my %requesters = ();
167 $requesters{$branch_1} = AddMember(
168     branchcode   => $branch_1,
169     categorycode => $category_2,
170     surname      => "borrower from $branch_1",
171 );
172 for my $i ( 2 .. 5 ) {
173     $requesters{"CPL$i"} = AddMember(
174         branchcode   => $branch_1,
175         categorycode => $category_2,
176         surname      => "borrower $i from $branch_1",
177     );
178 }
179 $requesters{$branch_2} = AddMember(
180     branchcode   => $branch_2,
181     categorycode => $category_2,
182     surname      => "borrower from $branch_2",
183 );
184 $requesters{$branch_3} = AddMember(
185     branchcode   => $branch_3,
186     categorycode => $category_2,
187     surname      => "borrower from $branch_3",
188 );
189
190 # Configure rules so that $branch_1 allows only $branch_1 patrons
191 # to request its items, while $branch_2 will allow its items
192 # to fill holds from anywhere.
193
194 $dbh->do('DELETE FROM issuingrules');
195 $dbh->do('DELETE FROM branch_item_rules');
196 $dbh->do('DELETE FROM branch_borrower_circ_rules');
197 $dbh->do('DELETE FROM default_borrower_circ_rules');
198 $dbh->do('DELETE FROM default_branch_item_rules');
199 $dbh->do('DELETE FROM default_branch_circ_rules');
200 $dbh->do('DELETE FROM default_circ_rules');
201 $dbh->do(
202     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed)
203       VALUES (?, ?, ?, ?)},
204     {},
205     '*', '*', '*', 25
206 );
207
208 # CPL allows only its own patrons to request its items
209 $dbh->do(
210     q{INSERT INTO default_branch_circ_rules (branchcode, maxissueqty, holdallowed, returnbranch)
211       VALUES (?, ?, ?, ?)},
212     {},
213     $branch_1, 10, 1, 'homebranch',
214 );
215
216 # ... while FPL allows anybody to request its items
217 $dbh->do(
218     q{INSERT INTO default_branch_circ_rules (branchcode, maxissueqty, holdallowed, returnbranch)
219       VALUES (?, ?, ?, ?)},
220     {},
221     $branch_2, 10, 2, 'homebranch',
222 );
223
224 # helper biblio for the bug 10272 regression test
225 my $bib2 = MARC::Record->new();
226 $bib2->append_fields(
227     MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
228     MARC::Field->new('245', ' ', ' ', a => $title),
229 );
230
231 # create one item belonging to FPL and one belonging to CPL
232 my ($bibnum2, $bibitemnum2) = AddBiblio($bib, '');
233 my ($itemnum_cpl, $itemnum_fpl);
234 ( undef, undef, $itemnum_cpl ) = AddItem(
235     {   homebranch    => $branch_1,
236         holdingbranch => $branch_1,
237         barcode       => 'bug10272_CPL',
238         itype         => $itemtype
239     },
240     $bibnum2
241 );
242 ( undef, undef, $itemnum_fpl ) = AddItem(
243     {   homebranch    => $branch_2,
244         holdingbranch => $branch_2,
245         barcode       => 'bug10272_FPL',
246         itype         => $itemtype
247     },
248     $bibnum2
249 );
250
251
252 # Ensure that priorities are numbered correcly when a hold is moved to waiting
253 # (bug 11947)
254 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
255 AddReserve($branch_3,  $requesters{$branch_3}, $bibnum2,
256            $bibitems,  1, $resdate, $expdate, $notes,
257            $title,      $checkitem, $found);
258 AddReserve($branch_2,  $requesters{$branch_2}, $bibnum2,
259            $bibitems,  2, $resdate, $expdate, $notes,
260            $title,      $checkitem, $found);
261 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum2,
262            $bibitems,  3, $resdate, $expdate, $notes,
263            $title,      $checkitem, $found);
264 ModReserveAffect($itemnum_cpl, $requesters{$branch_3}, 0);
265
266 # Now it should have different priorities.
267 my $title_reserves = GetReservesFromBiblionumber({biblionumber => $bibnum2});
268 # Sort by reserve number in case the database gives us oddly ordered results
269 my @reserves = sort { $a->{reserve_id} <=> $b->{reserve_id} } @$title_reserves;
270 is($reserves[0]{priority}, 0, 'Item is correctly waiting');
271 is($reserves[1]{priority}, 1, 'Item is correctly priority 1');
272 is($reserves[2]{priority}, 2, 'Item is correctly priority 2');
273
274 @reserves = Koha::Holds->search({ borrowernumber => $requesters{$branch_3} })->waiting();
275 is( @reserves, 1, 'GetWaiting got only the waiting reserve' );
276 is( $reserves[0]->borrowernumber(), $requesters{$branch_3}, 'GetWaiting got the reserve for the correct borrower' );
277
278
279 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
280 AddReserve($branch_3,  $requesters{$branch_3}, $bibnum2,
281            $bibitems,  1, $resdate, $expdate, $notes,
282            $title,      $checkitem, $found);
283 AddReserve($branch_2,  $requesters{$branch_2}, $bibnum2,
284            $bibitems,  2, $resdate, $expdate, $notes,
285            $title,      $checkitem, $found);
286 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum2,
287            $bibitems,  3, $resdate, $expdate, $notes,
288            $title,      $checkitem, $found);
289
290 # Ensure that the item's home library controls hold policy lookup
291 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
292
293 my $messages;
294 # Return the CPL item at FPL.  The hold that should be triggered is
295 # the one placed by the CPL patron, as the other two patron's hold
296 # requests cannot be filled by that item per policy.
297 (undef, $messages, undef, undef) = AddReturn('bug10272_CPL', $branch_2);
298 is( $messages->{ResFound}->{borrowernumber},
299     $requesters{$branch_1},
300     'restrictive library\'s items only fill requests by own patrons (bug 10272)');
301
302 # Return the FPL item at FPL.  The hold that should be triggered is
303 # the one placed by the RPL patron, as that patron is first in line
304 # and RPL imposes no restrictions on whose holds its items can fill.
305
306 # Ensure that the preference 'LocalHoldsPriority' is not set (Bug 15244):
307 t::lib::Mocks::mock_preference( 'LocalHoldsPriority', '' );
308
309 (undef, $messages, undef, undef) = AddReturn('bug10272_FPL', $branch_2);
310 is( $messages->{ResFound}->{borrowernumber},
311     $requesters{$branch_3},
312     'for generous library, its items fill first hold request in line (bug 10272)');
313
314 my $reserves = GetReservesFromBiblionumber({biblionumber => $biblionumber});
315 isa_ok($reserves, 'ARRAY');
316 is(scalar @$reserves, 1, "Only one reserves for this biblio");
317 my $reserve_id = $reserves->[0]->{reserve_id};
318
319 $reserve = GetReserve($reserve_id);
320 isa_ok($reserve, 'HASH', "GetReserve return");
321 is($reserve->{biblionumber}, $biblionumber);
322
323 $reserve = CancelReserve({reserve_id => $reserve_id});
324 isa_ok($reserve, 'HASH', "CancelReserve return");
325 is($reserve->{biblionumber}, $biblionumber);
326
327 $reserve = GetReserve($reserve_id);
328 is($reserve, undef, "GetReserve returns undef after deletion");
329
330 $reserve = CancelReserve({reserve_id => $reserve_id});
331 is($reserve, undef, "CancelReserve return undef if reserve does not exist");
332
333
334 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
335 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
336 # Test 9761a: Add a reserve without date, CheckReserve should return it
337 $resdate= undef; #defaults to today in AddReserve
338 $expdate= undef; #no expdate
339 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
340 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
341            $bibitems,  1, $resdate, $expdate, $notes,
342            $title,      $checkitem, $found);
343 ($status)=CheckReserves($itemnumber,undef,undef);
344 is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead');
345 ($status)=CheckReserves($itemnumber,undef,7);
346 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
347
348 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
349 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
350 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
351 $resdate= dt_from_string();
352 $resdate->add_duration(DateTime::Duration->new(days => 4));
353 $resdate=output_pref($resdate);
354 $expdate= undef; #no expdate
355 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
356            $bibitems,  1, $resdate, $expdate, $notes,
357            $title,      $checkitem, $found);
358 ($status)=CheckReserves($itemnumber,undef,undef);
359 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
360
361 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
362 ($status)=CheckReserves($itemnumber,undef,3);
363 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
364 ($status)=CheckReserves($itemnumber,undef,4);
365 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
366
367 # Test 9761d: Check ResFound message of AddReturn for future hold
368 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
369 # In this test we do not need an issued item; it is just a 'checkin'
370 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
371 (my $doreturn, $messages)= AddReturn('97531',$branch_1);
372 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
373 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 3);
374 ($doreturn, $messages)= AddReturn('97531',$branch_1);
375 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
376 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 7);
377 ($doreturn, $messages)= AddReturn('97531',$branch_1);
378 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
379
380 # End of tests for bug 9761 (ConfirmFutureHolds)
381
382 # test marking a hold as captured
383 my $hold_notice_count = count_hold_print_messages();
384 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
385 my $new_count = count_hold_print_messages();
386 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
387
388 # test that duplicate notices aren't generated
389 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
390 $new_count = count_hold_print_messages();
391 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
392
393 # avoiding the not_same_branch error
394 t::lib::Mocks::mock_preference('IndependentBranches', 0);
395 is(
396     DelItemCheck( $bibnum, $itemnumber),
397     'book_reserved',
398     'item that is captured to fill a hold cannot be deleted',
399 );
400
401 my $letter = ReserveSlip($branch_1, $requesters{$branch_1}, $bibnum);
402 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
403
404 # Tests for bug 9788: Does GetReservesFromItemnumber return a future wait?
405 # 9788a: GetReservesFromItemnumber does not return future next available hold
406 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
407 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
408 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
409 $resdate= dt_from_string();
410 $resdate->add_duration(DateTime::Duration->new(days => 2));
411 $resdate=output_pref($resdate);
412 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
413            $bibitems,  1, $resdate, $expdate, $notes,
414            $title,      $checkitem, $found);
415 my @results= GetReservesFromItemnumber($itemnumber);
416 is(defined $results[3]?1:0, 0, 'GetReservesFromItemnumber does not return a future next available hold');
417 # 9788b: GetReservesFromItemnumber does not return future item level hold
418 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
419 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
420            $bibitems,  1, $resdate, $expdate, $notes,
421            $title,      $itemnumber, $found); #item level hold
422 @results= GetReservesFromItemnumber($itemnumber);
423 is(defined $results[3]?1:0, 0, 'GetReservesFromItemnumber does not return a future item level hold');
424 # 9788c: GetReservesFromItemnumber returns future wait (confirmed future hold)
425 ModReserveAffect( $itemnumber,  $requesters{$branch_1} , 0); #confirm hold
426 @results= GetReservesFromItemnumber($itemnumber);
427 is(defined $results[3]?1:0, 1, 'GetReservesFromItemnumber returns a future wait (confirmed future hold)');
428 # End of tests for bug 9788
429
430 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
431 # Tests for CalculatePriority (bug 8918)
432 my $p = C4::Reserves::CalculatePriority($bibnum2);
433 is($p, 4, 'CalculatePriority should now return priority 4');
434 $resdate=undef;
435 AddReserve($branch_1,  $requesters{'CPL2'}, $bibnum2,
436            $bibitems,  $p, $resdate, $expdate, $notes,
437            $title,      $checkitem, $found);
438 $p = C4::Reserves::CalculatePriority($bibnum2);
439 is($p, 5, 'CalculatePriority should now return priority 5');
440 #some tests on bibnum
441 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
442 $p = C4::Reserves::CalculatePriority($bibnum);
443 is($p, 1, 'CalculatePriority should now return priority 1');
444 #add a new reserve and confirm it to waiting
445 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
446            $bibitems,  $p, $resdate, $expdate, $notes,
447            $title,      $itemnumber, $found);
448 $p = C4::Reserves::CalculatePriority($bibnum);
449 is($p, 2, 'CalculatePriority should now return priority 2');
450 ModReserveAffect( $itemnumber,  $requesters{$branch_1} , 0);
451 $p = C4::Reserves::CalculatePriority($bibnum);
452 is($p, 1, 'CalculatePriority should now return priority 1');
453 #add another biblio hold, no resdate
454 AddReserve($branch_1,  $requesters{'CPL2'}, $bibnum,
455            $bibitems,  $p, $resdate, $expdate, $notes,
456            $title,      $checkitem, $found);
457 $p = C4::Reserves::CalculatePriority($bibnum);
458 is($p, 2, 'CalculatePriority should now return priority 2');
459 #add another future hold
460 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
461 $resdate= dt_from_string();
462 $resdate->add_duration(DateTime::Duration->new(days => 1));
463 AddReserve($branch_1,  $requesters{'CPL3'}, $bibnum,
464            $bibitems,  $p, output_pref($resdate), $expdate, $notes,
465            $title,      $checkitem, $found);
466 $p = C4::Reserves::CalculatePriority($bibnum);
467 is($p, 2, 'CalculatePriority should now still return priority 2');
468 #calc priority with future resdate
469 $p = C4::Reserves::CalculatePriority($bibnum, $resdate);
470 is($p, 3, 'CalculatePriority should now return priority 3');
471 # End of tests for bug 8918
472
473 # Tests for cancel reserves by users from OPAC.
474 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
475 AddReserve($branch_1,  $requesters{$branch_1}, $item_bibnum,
476            $bibitems,  1, undef, $expdate, $notes,
477            $title,      $checkitem, '');
478 my (undef, $canres, undef) = CheckReserves($itemnumber);
479
480 is( CanReserveBeCanceledFromOpac(), undef,
481     'CanReserveBeCanceledFromOpac should return undef if called without any parameter'
482 );
483 is(
484     CanReserveBeCanceledFromOpac( $canres->{resserve_id} ),
485     undef,
486     'CanReserveBeCanceledFromOpac should return undef if called without the reserve_id'
487 );
488 is(
489     CanReserveBeCanceledFromOpac( undef, $requesters{CPL} ),
490     undef,
491     'CanReserveBeCanceledFromOpac should return undef if called without borrowernumber'
492 );
493
494 my $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
495 is($cancancel, 1, 'Can user cancel its own reserve');
496
497 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_2});
498 is($cancancel, 0, 'Other user cant cancel reserve');
499
500 ModReserveAffect($itemnumber, $requesters{$branch_1}, 1);
501 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
502 is($cancancel, 0, 'Reserve in transfer status cant be canceled');
503
504 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
505 AddReserve($branch_1,  $requesters{$branch_1}, $item_bibnum,
506            $bibitems,  1, undef, $expdate, $notes,
507            $title,      $checkitem, '');
508 (undef, $canres, undef) = CheckReserves($itemnumber);
509
510 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
511 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
512 is($cancancel, 0, 'Reserve in waiting status cant be canceled');
513
514 # End of tests for bug 12876
515
516        ####
517 ####### Testing Bug 13113 - Prevent juvenile/children from reserving ageRestricted material >>>
518        ####
519
520 t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' );
521
522 #Reserving an not-agerestricted Biblio by a Borrower with no dateofbirth is tested previously.
523
524 #Set the ageRestriction for the Biblio
525 my $record = GetMarcBiblio( $bibnum );
526 my ( $ageres_tagid, $ageres_subfieldid ) = GetMarcFromKohaField( "biblioitems.agerestriction" );
527 $record->append_fields(  MARC::Field->new($ageres_tagid, '', '', $ageres_subfieldid => 'PEGI 16')  );
528 C4::Biblio::ModBiblio( $record, $bibnum, '' );
529
530 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'OK', "Reserving an ageRestricted Biblio without a borrower dateofbirth succeeds" );
531
532 #Set the dateofbirth for the Borrower making him "too young".
533 my $now = DateTime->now();
534 C4::Members::SetAge( $borrower, '0015-00-00' );
535 C4::Members::ModMember( borrowernumber => $borrowernumber, dateofbirth => $borrower->{dateofbirth} );
536
537 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'ageRestricted', "Reserving a 'PEGI 16' Biblio by a 15 year old borrower fails");
538
539 #Set the dateofbirth for the Borrower making him "too old".
540 C4::Members::SetAge( $borrower, '0030-00-00' );
541 C4::Members::ModMember( borrowernumber => $borrowernumber, dateofbirth => $borrower->{dateofbirth} );
542
543 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'OK', "Reserving a 'PEGI 16' Biblio by a 30 year old borrower succeeds");
544        ####
545 ####### EO Bug 13113 <<<
546        ####
547
548 my $item = GetItem($itemnumber);
549
550 ok( C4::Reserves::IsAvailableForItemLevelRequest($item, $borrower), "Reserving a book on item level" );
551
552 my $itype = C4::Reserves::_get_itype($item);
553 my $categorycode = $borrower->{categorycode};
554 my $holdingbranch = $item->{holdingbranch};
555 my $rule = C4::Circulation::GetIssuingRule($categorycode, $itype, $holdingbranch);
556
557 $dbh->do(
558     "UPDATE issuingrules SET onshelfholds = 1 WHERE categorycode = ? AND itemtype= ? and branchcode = ?",
559     undef,
560     $rule->{categorycode}, $rule->{itemtype}, $rule->{branchcode}
561 );
562 ok( C4::Reserves::OnShelfHoldsAllowed($item, $borrower), "OnShelfHoldsAllowed() allowed" );
563 $dbh->do(
564     "UPDATE issuingrules SET onshelfholds = 0 WHERE categorycode = ? AND itemtype= ? and branchcode = ?",
565     undef,
566     $rule->{categorycode}, $rule->{itemtype}, $rule->{branchcode}
567 );
568 ok( !C4::Reserves::OnShelfHoldsAllowed($item, $borrower), "OnShelfHoldsAllowed() disallowed" );
569
570 # Tests for bug 14464
571
572 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
573 my ( undef, undef, $bz14464_fines ) = GetMemberIssuesAndFines( $borrowernumber );
574 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines at beginning' );
575
576 # First, test cancelling a reserve when there's no charge configured.
577 t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelayCharge', 0);
578
579 my $bz14464_reserve = AddReserve(
580     $branch_1,
581     $borrowernumber,
582     $bibnum,
583     undef,
584     '1',
585     undef,
586     undef,
587     '',
588     $title,
589     $itemnumber,
590     'W'
591 );
592
593 ok( $bz14464_reserve, 'Bug 14464 - 1st reserve correctly created' );
594
595 CancelReserve({ reserve_id => $bz14464_reserve, charge_cancel_fee => 1 });
596
597 my $old_reserve = Koha::Database->new()->schema()->resultset('OldReserve')->find( $bz14464_reserve );
598 is($old_reserve->get_column('found'), 'W', 'Bug 14968 - Keep found column from reserve');
599
600 ( undef, undef, $bz14464_fines ) = GetMemberIssuesAndFines( $borrowernumber );
601 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines after cancelling reserve with no charge configured' );
602
603 # Then, test cancelling a reserve when there's no charge desired.
604 t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelayCharge', 42);
605
606 $bz14464_reserve = AddReserve(
607     $branch_1,
608     $borrowernumber,
609     $bibnum,
610     undef,
611     '1',
612     undef,
613     undef,
614     '',
615     $title,
616     $itemnumber,
617     'W'
618 );
619
620 ok( $bz14464_reserve, 'Bug 14464 - 2nd reserve correctly created' );
621
622 CancelReserve({ reserve_id => $bz14464_reserve });
623
624 ( undef, undef, $bz14464_fines ) = GetMemberIssuesAndFines( $borrowernumber );
625 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines after cancelling reserve with no charge desired' );
626
627 # Finally, test cancelling a reserve when there's a charge desired and configured.
628 $bz14464_reserve = AddReserve(
629     $branch_1,
630     $borrowernumber,
631     $bibnum,
632     undef,
633     '1',
634     undef,
635     undef,
636     '',
637     $title,
638     $itemnumber,
639     'W'
640 );
641
642 ok( $bz14464_reserve, 'Bug 14464 - 1st reserve correctly created' );
643
644 CancelReserve({ reserve_id => $bz14464_reserve, charge_cancel_fee => 1 });
645
646 ( undef, undef, $bz14464_fines ) = GetMemberIssuesAndFines( $borrowernumber );
647 is( int( $bz14464_fines ), 42, 'Bug 14464 - Fine applied after cancelling reserve with charge desired and configured' );
648
649 # tests for MoveReserve in relation to ConfirmFutureHolds (BZ 14526)
650 #   hold from A pos 1, today, no fut holds: MoveReserve should fill it
651 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
652 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
653 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
654 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
655     $bibitems,  1, undef, $expdate, $notes, $title, $checkitem, '');
656 MoveReserve( $itemnumber, $borrowernumber );
657 ($status)=CheckReserves( $itemnumber );
658 is( $status, '', 'MoveReserve filled hold');
659 #   hold from A waiting, today, no fut holds: MoveReserve should fill it
660 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
661    $bibitems,  1, undef, $expdate, $notes, $title, $checkitem, 'W');
662 MoveReserve( $itemnumber, $borrowernumber );
663 ($status)=CheckReserves( $itemnumber );
664 is( $status, '', 'MoveReserve filled waiting hold');
665 #   hold from A pos 1, tomorrow, no fut holds: not filled
666 $resdate= dt_from_string();
667 $resdate->add_duration(DateTime::Duration->new(days => 1));
668 $resdate=output_pref($resdate);
669 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
670     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
671 MoveReserve( $itemnumber, $borrowernumber );
672 ($status)=CheckReserves( $itemnumber, undef, 1 );
673 is( $status, 'Reserved', 'MoveReserve did not fill future hold');
674 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
675 #   hold from A pos 1, tomorrow, fut holds=2: MoveReserve should fill it
676 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
677 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
678     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
679 MoveReserve( $itemnumber, $borrowernumber );
680 ($status)=CheckReserves( $itemnumber, undef, 2 );
681 is( $status, '', 'MoveReserve filled future hold now');
682 #   hold from A waiting, tomorrow, fut holds=2: MoveReserve should fill it
683 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
684     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, 'W');
685 MoveReserve( $itemnumber, $borrowernumber );
686 ($status)=CheckReserves( $itemnumber, undef, 2 );
687 is( $status, '', 'MoveReserve filled future waiting hold now');
688 #   hold from A pos 1, today+3, fut holds=2: MoveReserve should not fill it
689 $resdate= dt_from_string();
690 $resdate->add_duration(DateTime::Duration->new(days => 3));
691 $resdate=output_pref($resdate);
692 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
693     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
694 MoveReserve( $itemnumber, $borrowernumber );
695 ($status)=CheckReserves( $itemnumber, undef, 3 );
696 is( $status, 'Reserved', 'MoveReserve did not fill future hold of 3 days');
697 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
698
699 # we reached the finish
700 $schema->storage->txn_rollback();
701
702 sub count_hold_print_messages {
703     my $message_count = $dbh->selectall_arrayref(q{
704         SELECT COUNT(*)
705         FROM message_queue
706         WHERE letter_code = 'HOLD' 
707         AND   message_transport_type = 'print'
708     });
709     return $message_count->[0]->[0];
710 }