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