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