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