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