Bug 14968 - Provides unit test
[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::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 t::lib::Mocks::mock_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 t::lib::Mocks::mock_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 t::lib::Mocks::mock_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 t::lib::Mocks::mock_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
284 # Ensure that the preference 'LocalHoldsPriority' is not set (Bug 15244):
285 t::lib::Mocks::mock_preference( 'LocalHoldsPriority', '' );
286
287 (undef, $messages, undef, undef) = AddReturn('bug10272_FPL', 'FPL');
288 is( $messages->{ResFound}->{borrowernumber},
289     $requesters{'RPL'},
290     'for generous library, its items fill first hold request in line (bug 10272)');
291
292 my $reserves = GetReservesFromBiblionumber({biblionumber => $biblionumber});
293 isa_ok($reserves, 'ARRAY');
294 is(scalar @$reserves, 1, "Only one reserves for this biblio");
295 my $reserve_id = $reserves->[0]->{reserve_id};
296
297 $reserve = GetReserve($reserve_id);
298 isa_ok($reserve, 'HASH', "GetReserve return");
299 is($reserve->{biblionumber}, $biblionumber);
300
301 $reserve = CancelReserve({reserve_id => $reserve_id});
302 isa_ok($reserve, 'HASH', "CancelReserve return");
303 is($reserve->{biblionumber}, $biblionumber);
304
305 $reserve = GetReserve($reserve_id);
306 is($reserve, undef, "GetReserve returns undef after deletion");
307
308 $reserve = CancelReserve({reserve_id => $reserve_id});
309 is($reserve, undef, "CancelReserve return undef if reserve does not exist");
310
311
312 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
313 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
314 # Test 9761a: Add a reserve without date, CheckReserve should return it
315 $resdate= undef; #defaults to today in AddReserve
316 $expdate= undef; #no expdate
317 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
318 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
319            $bibitems,  1, $resdate, $expdate, $notes,
320            $title,      $checkitem, $found);
321 ($status)=CheckReserves($itemnumber,undef,undef);
322 is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead');
323 ($status)=CheckReserves($itemnumber,undef,7);
324 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
325
326 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
327 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
328 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
329 $resdate= dt_from_string();
330 $resdate->add_duration(DateTime::Duration->new(days => 4));
331 $resdate=output_pref($resdate);
332 $expdate= undef; #no expdate
333 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
334            $bibitems,  1, $resdate, $expdate, $notes,
335            $title,      $checkitem, $found);
336 ($status)=CheckReserves($itemnumber,undef,undef);
337 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
338
339 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
340 ($status)=CheckReserves($itemnumber,undef,3);
341 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
342 ($status)=CheckReserves($itemnumber,undef,4);
343 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
344
345 # Test 9761d: Check ResFound message of AddReturn for future hold
346 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
347 # In this test we do not need an issued item; it is just a 'checkin'
348 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
349 (my $doreturn, $messages)= AddReturn('97531','CPL');
350 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
351 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 3);
352 ($doreturn, $messages)= AddReturn('97531','CPL');
353 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
354 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 7);
355 ($doreturn, $messages)= AddReturn('97531','CPL');
356 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
357
358 # End of tests for bug 9761 (ConfirmFutureHolds)
359
360 # test marking a hold as captured
361 my $hold_notice_count = count_hold_print_messages();
362 ModReserveAffect($itemnumber, $requesters{'CPL'}, 0);
363 my $new_count = count_hold_print_messages();
364 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
365
366 # test that duplicate notices aren't generated
367 ModReserveAffect($itemnumber, $requesters{'CPL'}, 0);
368 $new_count = count_hold_print_messages();
369 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
370
371 # avoiding the not_same_branch error
372 t::lib::Mocks::mock_preference('IndependentBranches', 0);
373 is(
374     DelItemCheck($dbh, $bibnum, $itemnumber),
375     'book_reserved',
376     'item that is captured to fill a hold cannot be deleted',
377 );
378
379 my $letter = ReserveSlip('CPL', $requesters{'CPL'}, $bibnum);
380 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
381
382 # Tests for bug 9788: Does GetReservesFromItemnumber return a future wait?
383 # 9788a: GetReservesFromItemnumber does not return future next available hold
384 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
385 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
386 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
387 $resdate= dt_from_string();
388 $resdate->add_duration(DateTime::Duration->new(days => 2));
389 $resdate=output_pref($resdate);
390 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
391            $bibitems,  1, $resdate, $expdate, $notes,
392            $title,      $checkitem, $found);
393 my @results= GetReservesFromItemnumber($itemnumber);
394 is(defined $results[3]?1:0, 0, 'GetReservesFromItemnumber does not return a future next available hold');
395 # 9788b: GetReservesFromItemnumber does not return future item level hold
396 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
397 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
398            $bibitems,  1, $resdate, $expdate, $notes,
399            $title,      $itemnumber, $found); #item level hold
400 @results= GetReservesFromItemnumber($itemnumber);
401 is(defined $results[3]?1:0, 0, 'GetReservesFromItemnumber does not return a future item level hold');
402 # 9788c: GetReservesFromItemnumber returns future wait (confirmed future hold)
403 ModReserveAffect( $itemnumber,  $requesters{'CPL'} , 0); #confirm hold
404 @results= GetReservesFromItemnumber($itemnumber);
405 is(defined $results[3]?1:0, 1, 'GetReservesFromItemnumber returns a future wait (confirmed future hold)');
406 # End of tests for bug 9788
407
408 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
409 # Tests for CalculatePriority (bug 8918)
410 my $p = C4::Reserves::CalculatePriority($bibnum2);
411 is($p, 4, 'CalculatePriority should now return priority 4');
412 $resdate=undef;
413 AddReserve('CPL',  $requesters{'CPL2'}, $bibnum2,
414            $bibitems,  $p, $resdate, $expdate, $notes,
415            $title,      $checkitem, $found);
416 $p = C4::Reserves::CalculatePriority($bibnum2);
417 is($p, 5, 'CalculatePriority should now return priority 5');
418 #some tests on bibnum
419 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
420 $p = C4::Reserves::CalculatePriority($bibnum);
421 is($p, 1, 'CalculatePriority should now return priority 1');
422 #add a new reserve and confirm it to waiting
423 AddReserve('CPL',  $requesters{'CPL'}, $bibnum,
424            $bibitems,  $p, $resdate, $expdate, $notes,
425            $title,      $itemnumber, $found);
426 $p = C4::Reserves::CalculatePriority($bibnum);
427 is($p, 2, 'CalculatePriority should now return priority 2');
428 ModReserveAffect( $itemnumber,  $requesters{'CPL'} , 0);
429 $p = C4::Reserves::CalculatePriority($bibnum);
430 is($p, 1, 'CalculatePriority should now return priority 1');
431 #add another biblio hold, no resdate
432 AddReserve('CPL',  $requesters{'CPL2'}, $bibnum,
433            $bibitems,  $p, $resdate, $expdate, $notes,
434            $title,      $checkitem, $found);
435 $p = C4::Reserves::CalculatePriority($bibnum);
436 is($p, 2, 'CalculatePriority should now return priority 2');
437 #add another future hold
438 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
439 $resdate= dt_from_string();
440 $resdate->add_duration(DateTime::Duration->new(days => 1));
441 AddReserve('CPL',  $requesters{'CPL3'}, $bibnum,
442            $bibitems,  $p, output_pref($resdate), $expdate, $notes,
443            $title,      $checkitem, $found);
444 $p = C4::Reserves::CalculatePriority($bibnum);
445 is($p, 2, 'CalculatePriority should now still return priority 2');
446 #calc priority with future resdate
447 $p = C4::Reserves::CalculatePriority($bibnum, $resdate);
448 is($p, 3, 'CalculatePriority should now return priority 3');
449 # End of tests for bug 8918
450
451 # Test for bug 5144
452 warning_is {
453     $reserve_id = AddReserve('CPL',  $requesters{'CPL3'}, $bibnum,
454            $bibitems,  $p, output_pref($resdate), $expdate, $notes,
455            $title,      $checkitem, $found)
456 } "AddReserve: borrower $requesters{CPL3} already has a hold for biblionumber $bibnum";
457 is( $reserve_id, undef, 'Attempt to add a second reserve on a given record for the same patron fails.' );
458
459 # Tests for cancel reserves by users from OPAC.
460 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
461 AddReserve('CPL',  $requesters{'CPL'}, $item_bibnum,
462            $bibitems,  1, undef, $expdate, $notes,
463            $title,      $checkitem, '');
464 my (undef, $canres, undef) = CheckReserves($itemnumber);
465
466 is( CanReserveBeCanceledFromOpac(), undef,
467     'CanReserveBeCanceledFromOpac should return undef if called without any parameter'
468 );
469 is(
470     CanReserveBeCanceledFromOpac( $canres->{resserve_id} ),
471     undef,
472     'CanReserveBeCanceledFromOpac should return undef if called without the reserve_id'
473 );
474 is(
475     CanReserveBeCanceledFromOpac( undef, $requesters{CPL} ),
476     undef,
477     'CanReserveBeCanceledFromOpac should return undef if called without borrowernumber'
478 );
479
480 my $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{'CPL'});
481 is($cancancel, 1, 'Can user cancel its own reserve');
482
483 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{'FPL'});
484 is($cancancel, 0, 'Other user cant cancel reserve');
485
486 ModReserveAffect($itemnumber, $requesters{'CPL'}, 1);
487 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{'CPL'});
488 is($cancancel, 0, 'Reserve in transfer status cant be canceled');
489
490 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
491 AddReserve('CPL',  $requesters{'CPL'}, $item_bibnum,
492            $bibitems,  1, undef, $expdate, $notes,
493            $title,      $checkitem, '');
494 (undef, $canres, undef) = CheckReserves($itemnumber);
495
496 ModReserveAffect($itemnumber, $requesters{'CPL'}, 0);
497 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{'CPL'});
498 is($cancancel, 0, 'Reserve in waiting status cant be canceled');
499
500 # End of tests for bug 12876
501
502        ####
503 ####### Testing Bug 13113 - Prevent juvenile/children from reserving ageRestricted material >>>
504        ####
505
506 t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' );
507
508 #Reserving an not-agerestricted Biblio by a Borrower with no dateofbirth is tested previously.
509
510 #Set the ageRestriction for the Biblio
511 my $record = GetMarcBiblio( $bibnum );
512 my ( $ageres_tagid, $ageres_subfieldid ) = GetMarcFromKohaField( "biblioitems.agerestriction" );
513 $record->append_fields(  MARC::Field->new($ageres_tagid, '', '', $ageres_subfieldid => 'PEGI 16')  );
514 C4::Biblio::ModBiblio( $record, $bibnum, '' );
515
516 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'OK', "Reserving an ageRestricted Biblio without a borrower dateofbirth succeeds" );
517
518 #Set the dateofbirth for the Borrower making him "too young".
519 my $now = DateTime->now();
520 C4::Members::SetAge( $borrower, '0015-00-00' );
521 C4::Members::ModMember( borrowernumber => $borrowernumber, dateofbirth => $borrower->{dateofbirth} );
522
523 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'ageRestricted', "Reserving a 'PEGI 16' Biblio by a 15 year old borrower fails");
524
525 #Set the dateofbirth for the Borrower making him "too old".
526 C4::Members::SetAge( $borrower, '0030-00-00' );
527 C4::Members::ModMember( borrowernumber => $borrowernumber, dateofbirth => $borrower->{dateofbirth} );
528
529 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'OK', "Reserving a 'PEGI 16' Biblio by a 30 year old borrower succeeds");
530        ####
531 ####### EO Bug 13113 <<<
532        ####
533
534 my $item = GetItem($itemnumber);
535
536 ok( C4::Reserves::IsAvailableForItemLevelRequest($item, $borrower), "Reserving a book on item level" );
537
538 my $itype = C4::Reserves::_get_itype($item);
539 my $categorycode = $borrower->{categorycode};
540 my $holdingbranch = $item->{holdingbranch};
541 my $rule = C4::Circulation::GetIssuingRule($categorycode, $itype, $holdingbranch);
542
543 $dbh->do(
544     "UPDATE issuingrules SET onshelfholds = 1 WHERE categorycode = ? AND itemtype= ? and branchcode = ?",
545     undef,
546     $rule->{categorycode}, $rule->{itemtype}, $rule->{branchcode}
547 );
548 ok( C4::Reserves::OnShelfHoldsAllowed($item, $borrower), "OnShelfHoldsAllowed() allowed" );
549 $dbh->do(
550     "UPDATE issuingrules SET onshelfholds = 0 WHERE categorycode = ? AND itemtype= ? and branchcode = ?",
551     undef,
552     $rule->{categorycode}, $rule->{itemtype}, $rule->{branchcode}
553 );
554 ok( !C4::Reserves::OnShelfHoldsAllowed($item, $borrower), "OnShelfHoldsAllowed() disallowed" );
555
556 # Tests for bug 14464
557
558 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
559 my ( undef, undef, $bz14464_fines ) = GetMemberIssuesAndFines( $borrowernumber );
560 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines at beginning' );
561
562 # First, test cancelling a reserve when there's no charge configured.
563 t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelayCharge', 0);
564
565 my $bz14464_reserve = AddReserve(
566     'CPL',
567     $borrowernumber,
568     $bibnum,
569     undef,
570     '1',
571     undef,
572     undef,
573     '',
574     $title,
575     $itemnumber,
576     'W'
577 );
578
579 ok( $bz14464_reserve, 'Bug 14464 - 1st reserve correctly created' );
580
581 CancelReserve({ reserve_id => $bz14464_reserve, charge_cancel_fee => 1 });
582
583 my $old_reserve = Koha::Database->new()->schema()->resultset('OldReserve')->find( $bz14464_reserve );
584 is($old_reserve->get_column('found'), 'W', 'Bug 14968 - Keep found column from reserve');
585
586 ( undef, undef, $bz14464_fines ) = GetMemberIssuesAndFines( $borrowernumber );
587 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines after cancelling reserve with no charge configured' );
588
589 # Then, test cancelling a reserve when there's no charge desired.
590 t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelayCharge', 42);
591
592 $bz14464_reserve = AddReserve(
593     'CPL',
594     $borrowernumber,
595     $bibnum,
596     undef,
597     '1',
598     undef,
599     undef,
600     '',
601     $title,
602     $itemnumber,
603     'W'
604 );
605
606 ok( $bz14464_reserve, 'Bug 14464 - 2nd reserve correctly created' );
607
608 CancelReserve({ reserve_id => $bz14464_reserve });
609
610 ( undef, undef, $bz14464_fines ) = GetMemberIssuesAndFines( $borrowernumber );
611 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines after cancelling reserve with no charge desired' );
612
613 # Finally, test cancelling a reserve when there's a charge desired and configured.
614 $bz14464_reserve = AddReserve(
615     'CPL',
616     $borrowernumber,
617     $bibnum,
618     undef,
619     '1',
620     undef,
621     undef,
622     '',
623     $title,
624     $itemnumber,
625     'W'
626 );
627
628 ok( $bz14464_reserve, 'Bug 14464 - 1st reserve correctly created' );
629
630 CancelReserve({ reserve_id => $bz14464_reserve, charge_cancel_fee => 1 });
631
632 ( undef, undef, $bz14464_fines ) = GetMemberIssuesAndFines( $borrowernumber );
633 is( int( $bz14464_fines ), 42, 'Bug 14464 - Fine applied after cancelling reserve with charge desired and configured' );
634
635 # tests for MoveReserve in relation to ConfirmFutureHolds (BZ 14526)
636 #   hold from A pos 1, today, no fut holds: MoveReserve should fill it
637 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
638 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
639 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
640 AddReserve('CPL',  $borrowernumber, $item_bibnum,
641     $bibitems,  1, undef, $expdate, $notes, $title, $checkitem, '');
642 MoveReserve( $itemnumber, $borrowernumber );
643 ($status)=CheckReserves( $itemnumber );
644 is( $status, '', 'MoveReserve filled hold');
645 #   hold from A waiting, today, no fut holds: MoveReserve should fill it
646 AddReserve('CPL',  $borrowernumber, $item_bibnum,
647    $bibitems,  1, undef, $expdate, $notes, $title, $checkitem, 'W');
648 MoveReserve( $itemnumber, $borrowernumber );
649 ($status)=CheckReserves( $itemnumber );
650 is( $status, '', 'MoveReserve filled waiting hold');
651 #   hold from A pos 1, tomorrow, no fut holds: not filled
652 $resdate= dt_from_string();
653 $resdate->add_duration(DateTime::Duration->new(days => 1));
654 $resdate=output_pref($resdate);
655 AddReserve('CPL',  $borrowernumber, $item_bibnum,
656     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
657 MoveReserve( $itemnumber, $borrowernumber );
658 ($status)=CheckReserves( $itemnumber, undef, 1 );
659 is( $status, 'Reserved', 'MoveReserve did not fill future hold');
660 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
661 #   hold from A pos 1, tomorrow, fut holds=2: MoveReserve should fill it
662 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
663 AddReserve('CPL',  $borrowernumber, $item_bibnum,
664     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
665 MoveReserve( $itemnumber, $borrowernumber );
666 ($status)=CheckReserves( $itemnumber, undef, 2 );
667 is( $status, '', 'MoveReserve filled future hold now');
668 #   hold from A waiting, tomorrow, fut holds=2: MoveReserve should fill it
669 AddReserve('CPL',  $borrowernumber, $item_bibnum,
670     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, 'W');
671 MoveReserve( $itemnumber, $borrowernumber );
672 ($status)=CheckReserves( $itemnumber, undef, 2 );
673 is( $status, '', 'MoveReserve filled future waiting hold now');
674 #   hold from A pos 1, today+3, fut holds=2: MoveReserve should not fill it
675 $resdate= dt_from_string();
676 $resdate->add_duration(DateTime::Duration->new(days => 3));
677 $resdate=output_pref($resdate);
678 AddReserve('CPL',  $borrowernumber, $item_bibnum,
679     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
680 MoveReserve( $itemnumber, $borrowernumber );
681 ($status)=CheckReserves( $itemnumber, undef, 3 );
682 is( $status, 'Reserved', 'MoveReserve did not fill future hold of 3 days');
683 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
684
685 # we reached the finish
686 $dbh->rollback;
687
688 sub count_hold_print_messages {
689     my $message_count = $dbh->selectall_arrayref(q{
690         SELECT COUNT(*)
691         FROM message_queue
692         WHERE letter_code = 'HOLD' 
693         AND   message_transport_type = 'print'
694     });
695     return $message_count->[0]->[0];
696 }