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