Bug 19301: Remove C4::Reserves::OnShelfHoldsAllowed
[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 => 56;
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-");
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 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
324 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
325 # Test 9761a: Add a reserve without date, CheckReserve should return it
326 $resdate= undef; #defaults to today in AddReserve
327 $expdate= undef; #no expdate
328 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
329 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
330            $bibitems,  1, $resdate, $expdate, $notes,
331            $title,      $checkitem, $found);
332 ($status)=CheckReserves($itemnumber,undef,undef);
333 is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead');
334 ($status)=CheckReserves($itemnumber,undef,7);
335 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
336
337 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
338 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
339 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
340 $resdate= dt_from_string();
341 $resdate->add_duration(DateTime::Duration->new(days => 4));
342 $resdate=output_pref($resdate);
343 $expdate= undef; #no expdate
344 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
345            $bibitems,  1, $resdate, $expdate, $notes,
346            $title,      $checkitem, $found);
347 ($status)=CheckReserves($itemnumber,undef,undef);
348 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
349
350 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
351 ($status)=CheckReserves($itemnumber,undef,3);
352 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
353 ($status)=CheckReserves($itemnumber,undef,4);
354 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
355
356 # Test 9761d: Check ResFound message of AddReturn for future hold
357 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
358 # In this test we do not need an issued item; it is just a 'checkin'
359 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
360 (my $doreturn, $messages)= AddReturn('97531',$branch_1);
361 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
362 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 3);
363 ($doreturn, $messages)= AddReturn('97531',$branch_1);
364 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
365 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 7);
366 ($doreturn, $messages)= AddReturn('97531',$branch_1);
367 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
368
369 # End of tests for bug 9761 (ConfirmFutureHolds)
370
371 # test marking a hold as captured
372 my $hold_notice_count = count_hold_print_messages();
373 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
374 my $new_count = count_hold_print_messages();
375 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
376
377 # test that duplicate notices aren't generated
378 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
379 $new_count = count_hold_print_messages();
380 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
381
382 # avoiding the not_same_branch error
383 t::lib::Mocks::mock_preference('IndependentBranches', 0);
384 is(
385     DelItemCheck( $bibnum, $itemnumber),
386     'book_reserved',
387     'item that is captured to fill a hold cannot be deleted',
388 );
389
390 my $letter = ReserveSlip($branch_1, $requesters{$branch_1}, $bibnum);
391 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
392
393 # Tests for bug 9788: Does Koha::Item->current_holds return a future wait?
394 # 9788a: current_holds does not return future next available hold
395 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
396 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
397 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
398 $resdate= dt_from_string();
399 $resdate->add_duration(DateTime::Duration->new(days => 2));
400 $resdate=output_pref($resdate);
401 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
402            $bibitems,  1, $resdate, $expdate, $notes,
403            $title,      $checkitem, $found);
404 my $item = Koha::Items->find( $itemnumber );
405 $holds = $item->current_holds;
406 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
407 my $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
408 is( $future_holds->count, 0, 'current_holds does not return a future next available hold');
409 # 9788b: current_holds does not return future item level hold
410 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
411 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
412            $bibitems,  1, $resdate, $expdate, $notes,
413            $title,      $itemnumber, $found); #item level hold
414 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
415 is( $future_holds->count, 0, 'current_holds does not return a future item level hold' );
416 # 9788c: current_holds returns future wait (confirmed future hold)
417 ModReserveAffect( $itemnumber,  $requesters{$branch_1} , 0); #confirm hold
418 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
419 is( $future_holds->count, 1, 'current_holds returns a future wait (confirmed future hold)' );
420 # End of tests for bug 9788
421
422 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
423 # Tests for CalculatePriority (bug 8918)
424 my $p = C4::Reserves::CalculatePriority($bibnum2);
425 is($p, 4, 'CalculatePriority should now return priority 4');
426 $resdate=undef;
427 AddReserve($branch_1,  $requesters{'CPL2'}, $bibnum2,
428            $bibitems,  $p, $resdate, $expdate, $notes,
429            $title,      $checkitem, $found);
430 $p = C4::Reserves::CalculatePriority($bibnum2);
431 is($p, 5, 'CalculatePriority should now return priority 5');
432 #some tests on bibnum
433 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
434 $p = C4::Reserves::CalculatePriority($bibnum);
435 is($p, 1, 'CalculatePriority should now return priority 1');
436 #add a new reserve and confirm it to waiting
437 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
438            $bibitems,  $p, $resdate, $expdate, $notes,
439            $title,      $itemnumber, $found);
440 $p = C4::Reserves::CalculatePriority($bibnum);
441 is($p, 2, 'CalculatePriority should now return priority 2');
442 ModReserveAffect( $itemnumber,  $requesters{$branch_1} , 0);
443 $p = C4::Reserves::CalculatePriority($bibnum);
444 is($p, 1, 'CalculatePriority should now return priority 1');
445 #add another biblio hold, no resdate
446 AddReserve($branch_1,  $requesters{'CPL2'}, $bibnum,
447            $bibitems,  $p, $resdate, $expdate, $notes,
448            $title,      $checkitem, $found);
449 $p = C4::Reserves::CalculatePriority($bibnum);
450 is($p, 2, 'CalculatePriority should now return priority 2');
451 #add another future hold
452 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
453 $resdate= dt_from_string();
454 $resdate->add_duration(DateTime::Duration->new(days => 1));
455 AddReserve($branch_1,  $requesters{'CPL3'}, $bibnum,
456            $bibitems,  $p, output_pref($resdate), $expdate, $notes,
457            $title,      $checkitem, $found);
458 $p = C4::Reserves::CalculatePriority($bibnum);
459 is($p, 2, 'CalculatePriority should now still return priority 2');
460 #calc priority with future resdate
461 $p = C4::Reserves::CalculatePriority($bibnum, $resdate);
462 is($p, 3, 'CalculatePriority should now return priority 3');
463 # End of tests for bug 8918
464
465 # Tests for cancel reserves by users from OPAC.
466 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
467 AddReserve($branch_1,  $requesters{$branch_1}, $item_bibnum,
468            $bibitems,  1, undef, $expdate, $notes,
469            $title,      $checkitem, '');
470 my (undef, $canres, undef) = CheckReserves($itemnumber);
471
472 is( CanReserveBeCanceledFromOpac(), undef,
473     'CanReserveBeCanceledFromOpac should return undef if called without any parameter'
474 );
475 is(
476     CanReserveBeCanceledFromOpac( $canres->{resserve_id} ),
477     undef,
478     'CanReserveBeCanceledFromOpac should return undef if called without the reserve_id'
479 );
480 is(
481     CanReserveBeCanceledFromOpac( undef, $requesters{CPL} ),
482     undef,
483     'CanReserveBeCanceledFromOpac should return undef if called without borrowernumber'
484 );
485
486 my $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
487 is($cancancel, 1, 'Can user cancel its own reserve');
488
489 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_2});
490 is($cancancel, 0, 'Other user cant cancel reserve');
491
492 ModReserveAffect($itemnumber, $requesters{$branch_1}, 1);
493 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
494 is($cancancel, 0, 'Reserve in transfer status cant be canceled');
495
496 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
497 AddReserve($branch_1,  $requesters{$branch_1}, $item_bibnum,
498            $bibitems,  1, undef, $expdate, $notes,
499            $title,      $checkitem, '');
500 (undef, $canres, undef) = CheckReserves($itemnumber);
501
502 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
503 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
504 is($cancancel, 0, 'Reserve in waiting status cant be canceled');
505
506 # End of tests for bug 12876
507
508        ####
509 ####### Testing Bug 13113 - Prevent juvenile/children from reserving ageRestricted material >>>
510        ####
511
512 t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' );
513
514 #Reserving an not-agerestricted Biblio by a Borrower with no dateofbirth is tested previously.
515
516 #Set the ageRestriction for the Biblio
517 my $record = GetMarcBiblio({ biblionumber =>  $bibnum });
518 my ( $ageres_tagid, $ageres_subfieldid ) = GetMarcFromKohaField( "biblioitems.agerestriction" );
519 $record->append_fields(  MARC::Field->new($ageres_tagid, '', '', $ageres_subfieldid => 'PEGI 16')  );
520 C4::Biblio::ModBiblio( $record, $bibnum, $frameworkcode );
521
522 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'OK', "Reserving an ageRestricted Biblio without a borrower dateofbirth succeeds" );
523
524 #Set the dateofbirth for the Borrower making them "too young".
525 $borrower->{dateofbirth} = DateTime->now->add( years => -15 );
526 C4::Members::ModMember( borrowernumber => $borrowernumber, dateofbirth => $borrower->{dateofbirth} );
527
528 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'ageRestricted', "Reserving a 'PEGI 16' Biblio by a 15 year old borrower fails");
529
530 #Set the dateofbirth for the Borrower making them "too old".
531 $borrower->{dateofbirth} = DateTime->now->add( years => -30 );
532 C4::Members::ModMember( borrowernumber => $borrowernumber, dateofbirth => $borrower->{dateofbirth} );
533
534 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'OK', "Reserving a 'PEGI 16' Biblio by a 30 year old borrower succeeds");
535        ####
536 ####### EO Bug 13113 <<<
537        ####
538
539 $item = GetItem($itemnumber);
540
541 ok( C4::Reserves::IsAvailableForItemLevelRequest($item, $borrower), "Reserving a book on item level" );
542
543 # tests for MoveReserve in relation to ConfirmFutureHolds (BZ 14526)
544 #   hold from A pos 1, today, no fut holds: MoveReserve should fill it
545 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
546 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
547 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
548 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
549     $bibitems,  1, undef, $expdate, $notes, $title, $checkitem, '');
550 MoveReserve( $itemnumber, $borrowernumber );
551 ($status)=CheckReserves( $itemnumber );
552 is( $status, '', 'MoveReserve filled hold');
553 #   hold from A waiting, today, no fut holds: MoveReserve should fill it
554 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
555    $bibitems,  1, undef, $expdate, $notes, $title, $checkitem, 'W');
556 MoveReserve( $itemnumber, $borrowernumber );
557 ($status)=CheckReserves( $itemnumber );
558 is( $status, '', 'MoveReserve filled waiting hold');
559 #   hold from A pos 1, tomorrow, no fut holds: not filled
560 $resdate= dt_from_string();
561 $resdate->add_duration(DateTime::Duration->new(days => 1));
562 $resdate=output_pref($resdate);
563 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
564     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
565 MoveReserve( $itemnumber, $borrowernumber );
566 ($status)=CheckReserves( $itemnumber, undef, 1 );
567 is( $status, 'Reserved', 'MoveReserve did not fill future hold');
568 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
569 #   hold from A pos 1, tomorrow, fut holds=2: MoveReserve should fill it
570 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
571 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
572     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
573 MoveReserve( $itemnumber, $borrowernumber );
574 ($status)=CheckReserves( $itemnumber, undef, 2 );
575 is( $status, '', 'MoveReserve filled future hold now');
576 #   hold from A waiting, tomorrow, fut holds=2: MoveReserve should fill it
577 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
578     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, 'W');
579 MoveReserve( $itemnumber, $borrowernumber );
580 ($status)=CheckReserves( $itemnumber, undef, 2 );
581 is( $status, '', 'MoveReserve filled future waiting hold now');
582 #   hold from A pos 1, today+3, fut holds=2: MoveReserve should not fill it
583 $resdate= dt_from_string();
584 $resdate->add_duration(DateTime::Duration->new(days => 3));
585 $resdate=output_pref($resdate);
586 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
587     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
588 MoveReserve( $itemnumber, $borrowernumber );
589 ($status)=CheckReserves( $itemnumber, undef, 3 );
590 is( $status, 'Reserved', 'MoveReserve did not fill future hold of 3 days');
591 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
592
593 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
594 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
595 $cache->clear_from_cache("default_value_for_mod_marc-");
596 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
597
598 subtest '_koha_notify_reserve() tests' => sub {
599
600     plan tests => 2;
601
602     my $wants_hold_and_email = {
603         wants_digest => '0',
604         transports => {
605             sms => 'HOLD',
606             email => 'HOLD',
607             },
608         letter_code => 'HOLD'
609     };
610
611     my $mp = Test::MockModule->new( 'C4::Members::Messaging' );
612
613     $mp->mock("GetMessagingPreferences",$wants_hold_and_email);
614
615     $dbh->do('DELETE FROM letter');
616
617     my $email_hold_notice = $builder->build({
618             source => 'Letter',
619             value => {
620                 message_transport_type => 'email',
621                 branchcode => '',
622                 code => 'HOLD',
623                 module => 'reserves',
624                 lang => 'default',
625             }
626         });
627
628     my $sms_hold_notice = $builder->build({
629             source => 'Letter',
630             value => {
631                 message_transport_type => 'sms',
632                 branchcode => '',
633                 code => 'HOLD',
634                 module => 'reserves',
635                 lang=>'default',
636             }
637         });
638
639     my $hold_borrower = $builder->build({
640             source => 'Borrower',
641             value => {
642                 smsalertnumber=>'5555555555',
643                 email=>'a@b.com',
644             }
645         })->{borrowernumber};
646
647     my $hold = $builder->build({
648             source => 'Reserve',
649             value => {
650                borrowernumber=>$hold_borrower
651             }
652         });
653
654     ModReserveAffect($hold->{itemnumber}, $hold->{borrowernumber}, 0);
655     my $sms_message_address = $schema->resultset('MessageQueue')->search({
656             letter_code     => 'HOLD',
657             message_transport_type => 'sms',
658             borrowernumber => $hold_borrower,
659         })->next()->to_address();
660     is($sms_message_address, undef ,"We should not populate the sms message with the sms number, sending will do so");
661
662     my $email_message_address = $schema->resultset('MessageQueue')->search({
663             letter_code     => 'HOLD',
664             message_transport_type => 'email',
665             borrowernumber => $hold_borrower,
666         })->next()->to_address();
667     is($email_message_address, undef ,"We should not populate the hold message with the email address, sending will do so");
668
669 };
670
671 sub count_hold_print_messages {
672     my $message_count = $dbh->selectall_arrayref(q{
673         SELECT COUNT(*)
674         FROM message_queue
675         WHERE letter_code = 'HOLD' 
676         AND   message_transport_type = 'print'
677     });
678     return $message_count->[0]->[0];
679 }
680
681 # we reached the finish
682 $schema->storage->txn_rollback();