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