Bug 18432 : Follow up - Updating to use they/them
[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 => 71;
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 $biblio = Koha::Biblios->find( $bibnum2 );
272 my $holds = $biblio->holds({}, { order_by => 'reserve_id' });;
273 is($holds->next->priority, 0, 'Item is correctly waiting');
274 is($holds->next->priority, 1, 'Item is correctly priority 1');
275 is($holds->next->priority, 2, 'Item is correctly priority 2');
276
277 my @reserves = Koha::Holds->search({ borrowernumber => $requesters{$branch_3} })->waiting();
278 is( @reserves, 1, 'GetWaiting got only the waiting reserve' );
279 is( $reserves[0]->borrowernumber(), $requesters{$branch_3}, 'GetWaiting got the reserve for the correct borrower' );
280
281
282 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
283 AddReserve($branch_3,  $requesters{$branch_3}, $bibnum2,
284            $bibitems,  1, $resdate, $expdate, $notes,
285            $title,      $checkitem, $found);
286 AddReserve($branch_2,  $requesters{$branch_2}, $bibnum2,
287            $bibitems,  2, $resdate, $expdate, $notes,
288            $title,      $checkitem, $found);
289 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum2,
290            $bibitems,  3, $resdate, $expdate, $notes,
291            $title,      $checkitem, $found);
292
293 # Ensure that the item's home library controls hold policy lookup
294 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
295
296 my $messages;
297 # Return the CPL item at FPL.  The hold that should be triggered is
298 # the one placed by the CPL patron, as the other two patron's hold
299 # requests cannot be filled by that item per policy.
300 (undef, $messages, undef, undef) = AddReturn('bug10272_CPL', $branch_2);
301 is( $messages->{ResFound}->{borrowernumber},
302     $requesters{$branch_1},
303     'restrictive library\'s items only fill requests by own patrons (bug 10272)');
304
305 # Return the FPL item at FPL.  The hold that should be triggered is
306 # the one placed by the RPL patron, as that patron is first in line
307 # and RPL imposes no restrictions on whose holds its items can fill.
308
309 # Ensure that the preference 'LocalHoldsPriority' is not set (Bug 15244):
310 t::lib::Mocks::mock_preference( 'LocalHoldsPriority', '' );
311
312 (undef, $messages, undef, undef) = AddReturn('bug10272_FPL', $branch_2);
313 is( $messages->{ResFound}->{borrowernumber},
314     $requesters{$branch_3},
315     'for generous library, its items fill first hold request in line (bug 10272)');
316
317 $biblio = Koha::Biblios->find( $biblionumber );
318 $holds = $biblio->holds;
319 is($holds->count, 1, "Only one reserves for this biblio");
320 my $reserve_id = $holds->next->reserve_id;
321
322 $reserve = GetReserve($reserve_id);
323 isa_ok($reserve, 'HASH', "GetReserve return");
324 is($reserve->{biblionumber}, $biblionumber);
325
326 $reserve = CancelReserve({reserve_id => $reserve_id});
327 isa_ok($reserve, 'HASH', "CancelReserve return");
328 is($reserve->{biblionumber}, $biblionumber);
329
330 $reserve = GetReserve($reserve_id);
331 is($reserve, undef, "GetReserve returns undef after deletion");
332
333 $reserve = CancelReserve({reserve_id => $reserve_id});
334 is($reserve, undef, "CancelReserve return undef if reserve does not exist");
335
336
337 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
338 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
339 # Test 9761a: Add a reserve without date, CheckReserve should return it
340 $resdate= undef; #defaults to today in AddReserve
341 $expdate= undef; #no expdate
342 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
343 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
344            $bibitems,  1, $resdate, $expdate, $notes,
345            $title,      $checkitem, $found);
346 ($status)=CheckReserves($itemnumber,undef,undef);
347 is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead');
348 ($status)=CheckReserves($itemnumber,undef,7);
349 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
350
351 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
352 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
353 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
354 $resdate= dt_from_string();
355 $resdate->add_duration(DateTime::Duration->new(days => 4));
356 $resdate=output_pref($resdate);
357 $expdate= undef; #no expdate
358 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
359            $bibitems,  1, $resdate, $expdate, $notes,
360            $title,      $checkitem, $found);
361 ($status)=CheckReserves($itemnumber,undef,undef);
362 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
363
364 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
365 ($status)=CheckReserves($itemnumber,undef,3);
366 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
367 ($status)=CheckReserves($itemnumber,undef,4);
368 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
369
370 # Test 9761d: Check ResFound message of AddReturn for future hold
371 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
372 # In this test we do not need an issued item; it is just a 'checkin'
373 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
374 (my $doreturn, $messages)= AddReturn('97531',$branch_1);
375 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
376 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 3);
377 ($doreturn, $messages)= AddReturn('97531',$branch_1);
378 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
379 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 7);
380 ($doreturn, $messages)= AddReturn('97531',$branch_1);
381 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
382
383 # End of tests for bug 9761 (ConfirmFutureHolds)
384
385 # test marking a hold as captured
386 my $hold_notice_count = count_hold_print_messages();
387 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
388 my $new_count = count_hold_print_messages();
389 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
390
391 # test that duplicate notices aren't generated
392 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
393 $new_count = count_hold_print_messages();
394 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
395
396 # avoiding the not_same_branch error
397 t::lib::Mocks::mock_preference('IndependentBranches', 0);
398 is(
399     DelItemCheck( $bibnum, $itemnumber),
400     'book_reserved',
401     'item that is captured to fill a hold cannot be deleted',
402 );
403
404 my $letter = ReserveSlip($branch_1, $requesters{$branch_1}, $bibnum);
405 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
406
407 # Tests for bug 9788: Does Koha::Item->current_holds return a future wait?
408 # 9788a: current_holds does not return future next available hold
409 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
410 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
411 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
412 $resdate= dt_from_string();
413 $resdate->add_duration(DateTime::Duration->new(days => 2));
414 $resdate=output_pref($resdate);
415 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
416            $bibitems,  1, $resdate, $expdate, $notes,
417            $title,      $checkitem, $found);
418 my $item = Koha::Items->find( $itemnumber );
419 $holds = $item->current_holds;
420 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
421 my $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
422 is( $future_holds->count, 0, 'current_holds does not return a future next available hold');
423 # 9788b: current_holds does not return future item level hold
424 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
425 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
426            $bibitems,  1, $resdate, $expdate, $notes,
427            $title,      $itemnumber, $found); #item level hold
428 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
429 is( $future_holds->count, 0, 'current_holds does not return a future item level hold' );
430 # 9788c: current_holds returns future wait (confirmed future hold)
431 ModReserveAffect( $itemnumber,  $requesters{$branch_1} , 0); #confirm hold
432 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
433 is( $future_holds->count, 1, 'current_holds returns a future wait (confirmed future hold)' );
434 # End of tests for bug 9788
435
436 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
437 # Tests for CalculatePriority (bug 8918)
438 my $p = C4::Reserves::CalculatePriority($bibnum2);
439 is($p, 4, 'CalculatePriority should now return priority 4');
440 $resdate=undef;
441 AddReserve($branch_1,  $requesters{'CPL2'}, $bibnum2,
442            $bibitems,  $p, $resdate, $expdate, $notes,
443            $title,      $checkitem, $found);
444 $p = C4::Reserves::CalculatePriority($bibnum2);
445 is($p, 5, 'CalculatePriority should now return priority 5');
446 #some tests on bibnum
447 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
448 $p = C4::Reserves::CalculatePriority($bibnum);
449 is($p, 1, 'CalculatePriority should now return priority 1');
450 #add a new reserve and confirm it to waiting
451 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
452            $bibitems,  $p, $resdate, $expdate, $notes,
453            $title,      $itemnumber, $found);
454 $p = C4::Reserves::CalculatePriority($bibnum);
455 is($p, 2, 'CalculatePriority should now return priority 2');
456 ModReserveAffect( $itemnumber,  $requesters{$branch_1} , 0);
457 $p = C4::Reserves::CalculatePriority($bibnum);
458 is($p, 1, 'CalculatePriority should now return priority 1');
459 #add another biblio hold, no resdate
460 AddReserve($branch_1,  $requesters{'CPL2'}, $bibnum,
461            $bibitems,  $p, $resdate, $expdate, $notes,
462            $title,      $checkitem, $found);
463 $p = C4::Reserves::CalculatePriority($bibnum);
464 is($p, 2, 'CalculatePriority should now return priority 2');
465 #add another future hold
466 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
467 $resdate= dt_from_string();
468 $resdate->add_duration(DateTime::Duration->new(days => 1));
469 AddReserve($branch_1,  $requesters{'CPL3'}, $bibnum,
470            $bibitems,  $p, output_pref($resdate), $expdate, $notes,
471            $title,      $checkitem, $found);
472 $p = C4::Reserves::CalculatePriority($bibnum);
473 is($p, 2, 'CalculatePriority should now still return priority 2');
474 #calc priority with future resdate
475 $p = C4::Reserves::CalculatePriority($bibnum, $resdate);
476 is($p, 3, 'CalculatePriority should now return priority 3');
477 # End of tests for bug 8918
478
479 # Tests for cancel reserves by users from OPAC.
480 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
481 AddReserve($branch_1,  $requesters{$branch_1}, $item_bibnum,
482            $bibitems,  1, undef, $expdate, $notes,
483            $title,      $checkitem, '');
484 my (undef, $canres, undef) = CheckReserves($itemnumber);
485
486 is( CanReserveBeCanceledFromOpac(), undef,
487     'CanReserveBeCanceledFromOpac should return undef if called without any parameter'
488 );
489 is(
490     CanReserveBeCanceledFromOpac( $canres->{resserve_id} ),
491     undef,
492     'CanReserveBeCanceledFromOpac should return undef if called without the reserve_id'
493 );
494 is(
495     CanReserveBeCanceledFromOpac( undef, $requesters{CPL} ),
496     undef,
497     'CanReserveBeCanceledFromOpac should return undef if called without borrowernumber'
498 );
499
500 my $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
501 is($cancancel, 1, 'Can user cancel its own reserve');
502
503 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_2});
504 is($cancancel, 0, 'Other user cant cancel reserve');
505
506 ModReserveAffect($itemnumber, $requesters{$branch_1}, 1);
507 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
508 is($cancancel, 0, 'Reserve in transfer status cant be canceled');
509
510 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
511 AddReserve($branch_1,  $requesters{$branch_1}, $item_bibnum,
512            $bibitems,  1, undef, $expdate, $notes,
513            $title,      $checkitem, '');
514 (undef, $canres, undef) = CheckReserves($itemnumber);
515
516 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
517 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
518 is($cancancel, 0, 'Reserve in waiting status cant be canceled');
519
520 # End of tests for bug 12876
521
522        ####
523 ####### Testing Bug 13113 - Prevent juvenile/children from reserving ageRestricted material >>>
524        ####
525
526 t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' );
527
528 #Reserving an not-agerestricted Biblio by a Borrower with no dateofbirth is tested previously.
529
530 #Set the ageRestriction for the Biblio
531 my $record = GetMarcBiblio( $bibnum );
532 my ( $ageres_tagid, $ageres_subfieldid ) = GetMarcFromKohaField( "biblioitems.agerestriction" );
533 $record->append_fields(  MARC::Field->new($ageres_tagid, '', '', $ageres_subfieldid => 'PEGI 16')  );
534 C4::Biblio::ModBiblio( $record, $bibnum, $frameworkcode );
535
536 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'OK', "Reserving an ageRestricted Biblio without a borrower dateofbirth succeeds" );
537
538 #Set the dateofbirth for the Borrower making them "too young".
539 $borrower->{dateofbirth} = DateTime->now->add( years => -15 );
540 C4::Members::ModMember( borrowernumber => $borrowernumber, dateofbirth => $borrower->{dateofbirth} );
541
542 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'ageRestricted', "Reserving a 'PEGI 16' Biblio by a 15 year old borrower fails");
543
544 #Set the dateofbirth for the Borrower making them "too old".
545 $borrower->{dateofbirth} = DateTime->now->add( years => -30 );
546 C4::Members::ModMember( borrowernumber => $borrowernumber, dateofbirth => $borrower->{dateofbirth} );
547
548 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'OK', "Reserving a 'PEGI 16' Biblio by a 30 year old borrower succeeds");
549        ####
550 ####### EO Bug 13113 <<<
551        ####
552
553 $item = GetItem($itemnumber);
554
555 ok( C4::Reserves::IsAvailableForItemLevelRequest($item, $borrower), "Reserving a book on item level" );
556
557 my $itype = C4::Reserves::_get_itype($item);
558 my $categorycode = $borrower->{categorycode};
559 my $holdingbranch = $item->{holdingbranch};
560 my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule(
561     {
562         categorycode => $categorycode,
563         itemtype     => $itype,
564         branchcode   => $holdingbranch
565     }
566 );
567
568 $dbh->do(
569     "UPDATE issuingrules SET onshelfholds = 1 WHERE categorycode = ? AND itemtype= ? and branchcode = ?",
570     undef,
571     $issuing_rule->categorycode, $issuing_rule->itemtype, $issuing_rule->branchcode
572 );
573 ok( C4::Reserves::OnShelfHoldsAllowed($item, $borrower), "OnShelfHoldsAllowed() allowed" );
574 $dbh->do(
575     "UPDATE issuingrules SET onshelfholds = 0 WHERE categorycode = ? AND itemtype= ? and branchcode = ?",
576     undef,
577     $issuing_rule->categorycode, $issuing_rule->itemtype, $issuing_rule->branchcode
578 );
579 ok( !C4::Reserves::OnShelfHoldsAllowed($item, $borrower), "OnShelfHoldsAllowed() disallowed" );
580
581 # Tests for bug 14464
582
583 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
584 my $patron = Koha::Patrons->find( $borrowernumber );
585 my $bz14464_fines = $patron->account->balance;
586 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines at beginning' );
587
588 # First, test cancelling a reserve when there's no charge configured.
589 t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelayCharge', 0);
590
591 my $bz14464_reserve = AddReserve(
592     $branch_1,
593     $borrowernumber,
594     $bibnum,
595     undef,
596     '1',
597     undef,
598     undef,
599     '',
600     $title,
601     $itemnumber,
602     'W'
603 );
604
605 ok( $bz14464_reserve, 'Bug 14464 - 1st reserve correctly created' );
606
607 CancelReserve({ reserve_id => $bz14464_reserve, charge_cancel_fee => 1 });
608
609 my $old_reserve = Koha::Database->new()->schema()->resultset('OldReserve')->find( $bz14464_reserve );
610 is($old_reserve->get_column('found'), 'W', 'Bug 14968 - Keep found column from reserve');
611
612 $bz14464_fines = $patron->account->balance;
613 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines after cancelling reserve with no charge configured' );
614
615 # Then, test cancelling a reserve when there's no charge desired.
616 t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelayCharge', 42);
617
618 $bz14464_reserve = AddReserve(
619     $branch_1,
620     $borrowernumber,
621     $bibnum,
622     undef,
623     '1',
624     undef,
625     undef,
626     '',
627     $title,
628     $itemnumber,
629     'W'
630 );
631
632 ok( $bz14464_reserve, 'Bug 14464 - 2nd reserve correctly created' );
633
634 CancelReserve({ reserve_id => $bz14464_reserve });
635
636 $bz14464_fines = $patron->account->balance;
637 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines after cancelling reserve with no charge desired' );
638
639 # Finally, test cancelling a reserve when there's a charge desired and configured.
640 $bz14464_reserve = AddReserve(
641     $branch_1,
642     $borrowernumber,
643     $bibnum,
644     undef,
645     '1',
646     undef,
647     undef,
648     '',
649     $title,
650     $itemnumber,
651     'W'
652 );
653
654 ok( $bz14464_reserve, 'Bug 14464 - 1st reserve correctly created' );
655
656 CancelReserve({ reserve_id => $bz14464_reserve, charge_cancel_fee => 1 });
657
658 $bz14464_fines = $patron->account->balance;
659 is( int( $bz14464_fines ), 42, 'Bug 14464 - Fine applied after cancelling reserve with charge desired and configured' );
660
661 # tests for MoveReserve in relation to ConfirmFutureHolds (BZ 14526)
662 #   hold from A pos 1, today, no fut holds: MoveReserve should fill it
663 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
664 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
665 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
666 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
667     $bibitems,  1, undef, $expdate, $notes, $title, $checkitem, '');
668 MoveReserve( $itemnumber, $borrowernumber );
669 ($status)=CheckReserves( $itemnumber );
670 is( $status, '', 'MoveReserve filled hold');
671 #   hold from A waiting, today, no fut holds: MoveReserve should fill it
672 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
673    $bibitems,  1, undef, $expdate, $notes, $title, $checkitem, 'W');
674 MoveReserve( $itemnumber, $borrowernumber );
675 ($status)=CheckReserves( $itemnumber );
676 is( $status, '', 'MoveReserve filled waiting hold');
677 #   hold from A pos 1, tomorrow, no fut holds: not filled
678 $resdate= dt_from_string();
679 $resdate->add_duration(DateTime::Duration->new(days => 1));
680 $resdate=output_pref($resdate);
681 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
682     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
683 MoveReserve( $itemnumber, $borrowernumber );
684 ($status)=CheckReserves( $itemnumber, undef, 1 );
685 is( $status, 'Reserved', 'MoveReserve did not fill future hold');
686 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
687 #   hold from A pos 1, tomorrow, fut holds=2: MoveReserve should fill it
688 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
689 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
690     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
691 MoveReserve( $itemnumber, $borrowernumber );
692 ($status)=CheckReserves( $itemnumber, undef, 2 );
693 is( $status, '', 'MoveReserve filled future hold now');
694 #   hold from A waiting, tomorrow, fut holds=2: MoveReserve should fill it
695 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
696     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, 'W');
697 MoveReserve( $itemnumber, $borrowernumber );
698 ($status)=CheckReserves( $itemnumber, undef, 2 );
699 is( $status, '', 'MoveReserve filled future waiting hold now');
700 #   hold from A pos 1, today+3, fut holds=2: MoveReserve should not fill it
701 $resdate= dt_from_string();
702 $resdate->add_duration(DateTime::Duration->new(days => 3));
703 $resdate=output_pref($resdate);
704 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
705     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
706 MoveReserve( $itemnumber, $borrowernumber );
707 ($status)=CheckReserves( $itemnumber, undef, 3 );
708 is( $status, 'Reserved', 'MoveReserve did not fill future hold of 3 days');
709 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
710
711 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
712 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
713 $cache->clear_from_cache("default_value_for_mod_marc-$frameworkcode");
714 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
715
716 # we reached the finish
717 $schema->storage->txn_rollback();
718
719 sub count_hold_print_messages {
720     my $message_count = $dbh->selectall_arrayref(q{
721         SELECT COUNT(*)
722         FROM message_queue
723         WHERE letter_code = 'HOLD' 
724         AND   message_transport_type = 'print'
725     });
726     return $message_count->[0]->[0];
727 }