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