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