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