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