Bug 18292: Remove return 1 statements in tests
[koha.git] / t / db_dependent / Reserves.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use Test::More tests => 72;
21 use Test::MockModule;
22 use Test::Warn;
23
24 use 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 = GetReserve($reserve_id);
324 isa_ok($reserve, 'HASH', "GetReserve return");
325 is($reserve->{biblionumber}, $biblionumber);
326
327 $reserve = CancelReserve({reserve_id => $reserve_id});
328 isa_ok($reserve, 'HASH', "CancelReserve return");
329 is($reserve->{biblionumber}, $biblionumber);
330
331 $reserve = GetReserve($reserve_id);
332 is($reserve, undef, "GetReserve returns undef after deletion");
333
334 $reserve = CancelReserve({reserve_id => $reserve_id});
335 is($reserve, undef, "CancelReserve return undef if reserve does not exist");
336
337
338 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
339 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
340 # Test 9761a: Add a reserve without date, CheckReserve should return it
341 $resdate= undef; #defaults to today in AddReserve
342 $expdate= undef; #no expdate
343 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
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, 'Reserved', 'CheckReserves returns reserve without lookahead');
349 ($status)=CheckReserves($itemnumber,undef,7);
350 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
351
352 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
353 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
354 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
355 $resdate= dt_from_string();
356 $resdate->add_duration(DateTime::Duration->new(days => 4));
357 $resdate=output_pref($resdate);
358 $expdate= undef; #no expdate
359 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
360            $bibitems,  1, $resdate, $expdate, $notes,
361            $title,      $checkitem, $found);
362 ($status)=CheckReserves($itemnumber,undef,undef);
363 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
364
365 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
366 ($status)=CheckReserves($itemnumber,undef,3);
367 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
368 ($status)=CheckReserves($itemnumber,undef,4);
369 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
370
371 # Test 9761d: Check ResFound message of AddReturn for future hold
372 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
373 # In this test we do not need an issued item; it is just a 'checkin'
374 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
375 (my $doreturn, $messages)= AddReturn('97531',$branch_1);
376 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
377 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 3);
378 ($doreturn, $messages)= AddReturn('97531',$branch_1);
379 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
380 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 7);
381 ($doreturn, $messages)= AddReturn('97531',$branch_1);
382 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
383
384 # End of tests for bug 9761 (ConfirmFutureHolds)
385
386 # test marking a hold as captured
387 my $hold_notice_count = count_hold_print_messages();
388 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
389 my $new_count = count_hold_print_messages();
390 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
391
392 # test that duplicate notices aren't generated
393 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
394 $new_count = count_hold_print_messages();
395 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
396
397 # avoiding the not_same_branch error
398 t::lib::Mocks::mock_preference('IndependentBranches', 0);
399 is(
400     DelItemCheck( $bibnum, $itemnumber),
401     'book_reserved',
402     'item that is captured to fill a hold cannot be deleted',
403 );
404
405 my $letter = ReserveSlip($branch_1, $requesters{$branch_1}, $bibnum);
406 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
407
408 # Tests for bug 9788: Does Koha::Item->current_holds return a future wait?
409 # 9788a: current_holds does not return future next available hold
410 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
411 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
412 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
413 $resdate= dt_from_string();
414 $resdate->add_duration(DateTime::Duration->new(days => 2));
415 $resdate=output_pref($resdate);
416 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
417            $bibitems,  1, $resdate, $expdate, $notes,
418            $title,      $checkitem, $found);
419 my $item = Koha::Items->find( $itemnumber );
420 $holds = $item->current_holds;
421 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
422 my $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
423 is( $future_holds->count, 0, 'current_holds does not return a future next available hold');
424 # 9788b: current_holds does not return future item level hold
425 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
426 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
427            $bibitems,  1, $resdate, $expdate, $notes,
428            $title,      $itemnumber, $found); #item level hold
429 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
430 is( $future_holds->count, 0, 'current_holds does not return a future item level hold' );
431 # 9788c: current_holds returns future wait (confirmed future hold)
432 ModReserveAffect( $itemnumber,  $requesters{$branch_1} , 0); #confirm hold
433 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
434 is( $future_holds->count, 1, 'current_holds returns a future wait (confirmed future hold)' );
435 # End of tests for bug 9788
436
437 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
438 # Tests for CalculatePriority (bug 8918)
439 my $p = C4::Reserves::CalculatePriority($bibnum2);
440 is($p, 4, 'CalculatePriority should now return priority 4');
441 $resdate=undef;
442 AddReserve($branch_1,  $requesters{'CPL2'}, $bibnum2,
443            $bibitems,  $p, $resdate, $expdate, $notes,
444            $title,      $checkitem, $found);
445 $p = C4::Reserves::CalculatePriority($bibnum2);
446 is($p, 5, 'CalculatePriority should now return priority 5');
447 #some tests on bibnum
448 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
449 $p = C4::Reserves::CalculatePriority($bibnum);
450 is($p, 1, 'CalculatePriority should now return priority 1');
451 #add a new reserve and confirm it to waiting
452 AddReserve($branch_1,  $requesters{$branch_1}, $bibnum,
453            $bibitems,  $p, $resdate, $expdate, $notes,
454            $title,      $itemnumber, $found);
455 $p = C4::Reserves::CalculatePriority($bibnum);
456 is($p, 2, 'CalculatePriority should now return priority 2');
457 ModReserveAffect( $itemnumber,  $requesters{$branch_1} , 0);
458 $p = C4::Reserves::CalculatePriority($bibnum);
459 is($p, 1, 'CalculatePriority should now return priority 1');
460 #add another biblio hold, no resdate
461 AddReserve($branch_1,  $requesters{'CPL2'}, $bibnum,
462            $bibitems,  $p, $resdate, $expdate, $notes,
463            $title,      $checkitem, $found);
464 $p = C4::Reserves::CalculatePriority($bibnum);
465 is($p, 2, 'CalculatePriority should now return priority 2');
466 #add another future hold
467 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
468 $resdate= dt_from_string();
469 $resdate->add_duration(DateTime::Duration->new(days => 1));
470 AddReserve($branch_1,  $requesters{'CPL3'}, $bibnum,
471            $bibitems,  $p, output_pref($resdate), $expdate, $notes,
472            $title,      $checkitem, $found);
473 $p = C4::Reserves::CalculatePriority($bibnum);
474 is($p, 2, 'CalculatePriority should now still return priority 2');
475 #calc priority with future resdate
476 $p = C4::Reserves::CalculatePriority($bibnum, $resdate);
477 is($p, 3, 'CalculatePriority should now return priority 3');
478 # End of tests for bug 8918
479
480 # Tests for cancel reserves by users from OPAC.
481 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
482 AddReserve($branch_1,  $requesters{$branch_1}, $item_bibnum,
483            $bibitems,  1, undef, $expdate, $notes,
484            $title,      $checkitem, '');
485 my (undef, $canres, undef) = CheckReserves($itemnumber);
486
487 is( CanReserveBeCanceledFromOpac(), undef,
488     'CanReserveBeCanceledFromOpac should return undef if called without any parameter'
489 );
490 is(
491     CanReserveBeCanceledFromOpac( $canres->{resserve_id} ),
492     undef,
493     'CanReserveBeCanceledFromOpac should return undef if called without the reserve_id'
494 );
495 is(
496     CanReserveBeCanceledFromOpac( undef, $requesters{CPL} ),
497     undef,
498     'CanReserveBeCanceledFromOpac should return undef if called without borrowernumber'
499 );
500
501 my $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
502 is($cancancel, 1, 'Can user cancel its own reserve');
503
504 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_2});
505 is($cancancel, 0, 'Other user cant cancel reserve');
506
507 ModReserveAffect($itemnumber, $requesters{$branch_1}, 1);
508 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
509 is($cancancel, 0, 'Reserve in transfer status cant be canceled');
510
511 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
512 AddReserve($branch_1,  $requesters{$branch_1}, $item_bibnum,
513            $bibitems,  1, undef, $expdate, $notes,
514            $title,      $checkitem, '');
515 (undef, $canres, undef) = CheckReserves($itemnumber);
516
517 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
518 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
519 is($cancancel, 0, 'Reserve in waiting status cant be canceled');
520
521 # End of tests for bug 12876
522
523        ####
524 ####### Testing Bug 13113 - Prevent juvenile/children from reserving ageRestricted material >>>
525        ####
526
527 t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' );
528
529 #Reserving an not-agerestricted Biblio by a Borrower with no dateofbirth is tested previously.
530
531 #Set the ageRestriction for the Biblio
532 my $record = GetMarcBiblio( $bibnum );
533 my ( $ageres_tagid, $ageres_subfieldid ) = GetMarcFromKohaField( "biblioitems.agerestriction" );
534 $record->append_fields(  MARC::Field->new($ageres_tagid, '', '', $ageres_subfieldid => 'PEGI 16')  );
535 C4::Biblio::ModBiblio( $record, $bibnum, $frameworkcode );
536
537 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'OK', "Reserving an ageRestricted Biblio without a borrower dateofbirth succeeds" );
538
539 #Set the dateofbirth for the Borrower making them "too young".
540 $borrower->{dateofbirth} = DateTime->now->add( years => -15 );
541 C4::Members::ModMember( borrowernumber => $borrowernumber, dateofbirth => $borrower->{dateofbirth} );
542
543 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'ageRestricted', "Reserving a 'PEGI 16' Biblio by a 15 year old borrower fails");
544
545 #Set the dateofbirth for the Borrower making them "too old".
546 $borrower->{dateofbirth} = DateTime->now->add( years => -30 );
547 C4::Members::ModMember( borrowernumber => $borrowernumber, dateofbirth => $borrower->{dateofbirth} );
548
549 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber) , 'OK', "Reserving a 'PEGI 16' Biblio by a 30 year old borrower succeeds");
550        ####
551 ####### EO Bug 13113 <<<
552        ####
553
554 $item = GetItem($itemnumber);
555
556 ok( C4::Reserves::IsAvailableForItemLevelRequest($item, $borrower), "Reserving a book on item level" );
557
558 my $itype = C4::Reserves::_get_itype($item);
559 my $categorycode = $borrower->{categorycode};
560 my $holdingbranch = $item->{holdingbranch};
561 my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule(
562     {
563         categorycode => $categorycode,
564         itemtype     => $itype,
565         branchcode   => $holdingbranch
566     }
567 );
568
569 $dbh->do(
570     "UPDATE issuingrules SET onshelfholds = 1 WHERE categorycode = ? AND itemtype= ? and branchcode = ?",
571     undef,
572     $issuing_rule->categorycode, $issuing_rule->itemtype, $issuing_rule->branchcode
573 );
574 ok( C4::Reserves::OnShelfHoldsAllowed($item, $borrower), "OnShelfHoldsAllowed() allowed" );
575 $dbh->do(
576     "UPDATE issuingrules SET onshelfholds = 0 WHERE categorycode = ? AND itemtype= ? and branchcode = ?",
577     undef,
578     $issuing_rule->categorycode, $issuing_rule->itemtype, $issuing_rule->branchcode
579 );
580 ok( !C4::Reserves::OnShelfHoldsAllowed($item, $borrower), "OnShelfHoldsAllowed() disallowed" );
581
582 # Tests for bug 14464
583
584 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
585 my $patron = Koha::Patrons->find( $borrowernumber );
586 my $bz14464_fines = $patron->account->balance;
587 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines at beginning' );
588
589 # First, test cancelling a reserve when there's no charge configured.
590 t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelayCharge', 0);
591
592 my $bz14464_reserve = AddReserve(
593     $branch_1,
594     $borrowernumber,
595     $bibnum,
596     undef,
597     '1',
598     undef,
599     undef,
600     '',
601     $title,
602     $itemnumber,
603     'W'
604 );
605
606 ok( $bz14464_reserve, 'Bug 14464 - 1st reserve correctly created' );
607
608 CancelReserve({ reserve_id => $bz14464_reserve, charge_cancel_fee => 1 });
609
610 my $old_reserve = Koha::Database->new()->schema()->resultset('OldReserve')->find( $bz14464_reserve );
611 is($old_reserve->get_column('found'), 'W', 'Bug 14968 - Keep found column from reserve');
612
613 $bz14464_fines = $patron->account->balance;
614 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines after cancelling reserve with no charge configured' );
615
616 # Then, test cancelling a reserve when there's no charge desired.
617 t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelayCharge', 42);
618
619 $bz14464_reserve = AddReserve(
620     $branch_1,
621     $borrowernumber,
622     $bibnum,
623     undef,
624     '1',
625     undef,
626     undef,
627     '',
628     $title,
629     $itemnumber,
630     'W'
631 );
632
633 ok( $bz14464_reserve, 'Bug 14464 - 2nd reserve correctly created' );
634
635 CancelReserve({ reserve_id => $bz14464_reserve });
636
637 $bz14464_fines = $patron->account->balance;
638 is( !$bz14464_fines || $bz14464_fines==0, 1, 'Bug 14464 - No fines after cancelling reserve with no charge desired' );
639
640 # Finally, test cancelling a reserve when there's a charge desired and configured.
641 $bz14464_reserve = AddReserve(
642     $branch_1,
643     $borrowernumber,
644     $bibnum,
645     undef,
646     '1',
647     undef,
648     undef,
649     '',
650     $title,
651     $itemnumber,
652     'W'
653 );
654
655 ok( $bz14464_reserve, 'Bug 14464 - 1st reserve correctly created' );
656
657 CancelReserve({ reserve_id => $bz14464_reserve, charge_cancel_fee => 1 });
658
659 $bz14464_fines = $patron->account->balance;
660 is( int( $bz14464_fines ), 42, 'Bug 14464 - Fine applied after cancelling reserve with charge desired and configured' );
661
662 # tests for MoveReserve in relation to ConfirmFutureHolds (BZ 14526)
663 #   hold from A pos 1, today, no fut holds: MoveReserve should fill it
664 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
665 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
666 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
667 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
668     $bibitems,  1, undef, $expdate, $notes, $title, $checkitem, '');
669 MoveReserve( $itemnumber, $borrowernumber );
670 ($status)=CheckReserves( $itemnumber );
671 is( $status, '', 'MoveReserve filled hold');
672 #   hold from A waiting, today, no fut holds: MoveReserve should fill it
673 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
674    $bibitems,  1, undef, $expdate, $notes, $title, $checkitem, 'W');
675 MoveReserve( $itemnumber, $borrowernumber );
676 ($status)=CheckReserves( $itemnumber );
677 is( $status, '', 'MoveReserve filled waiting hold');
678 #   hold from A pos 1, tomorrow, no fut holds: not filled
679 $resdate= dt_from_string();
680 $resdate->add_duration(DateTime::Duration->new(days => 1));
681 $resdate=output_pref($resdate);
682 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
683     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
684 MoveReserve( $itemnumber, $borrowernumber );
685 ($status)=CheckReserves( $itemnumber, undef, 1 );
686 is( $status, 'Reserved', 'MoveReserve did not fill future hold');
687 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
688 #   hold from A pos 1, tomorrow, fut holds=2: MoveReserve should fill it
689 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
690 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
691     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
692 MoveReserve( $itemnumber, $borrowernumber );
693 ($status)=CheckReserves( $itemnumber, undef, 2 );
694 is( $status, '', 'MoveReserve filled future hold now');
695 #   hold from A waiting, tomorrow, fut holds=2: MoveReserve should fill it
696 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
697     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, 'W');
698 MoveReserve( $itemnumber, $borrowernumber );
699 ($status)=CheckReserves( $itemnumber, undef, 2 );
700 is( $status, '', 'MoveReserve filled future waiting hold now');
701 #   hold from A pos 1, today+3, fut holds=2: MoveReserve should not fill it
702 $resdate= dt_from_string();
703 $resdate->add_duration(DateTime::Duration->new(days => 3));
704 $resdate=output_pref($resdate);
705 AddReserve($branch_1,  $borrowernumber, $item_bibnum,
706     $bibitems,  1, $resdate, $expdate, $notes, $title, $checkitem, '');
707 MoveReserve( $itemnumber, $borrowernumber );
708 ($status)=CheckReserves( $itemnumber, undef, 3 );
709 is( $status, 'Reserved', 'MoveReserve did not fill future hold of 3 days');
710 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
711
712 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
713 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
714 $cache->clear_from_cache("default_value_for_mod_marc-$frameworkcode");
715 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
716
717 subtest '_koha_notify_reserve() tests' => sub {
718
719     plan tests => 2;
720
721     my $wants_hold_and_email = {
722         wants_digest => '0',
723         transports => {
724             sms => 'HOLD',
725             email => 'HOLD',
726             },
727         letter_code => 'HOLD'
728     };
729
730     my $mp = Test::MockModule->new( 'C4::Members::Messaging' );
731
732     $mp->mock("GetMessagingPreferences",$wants_hold_and_email);
733
734     $dbh->do('DELETE FROM letter');
735
736     my $email_hold_notice = $builder->build({
737             source => 'Letter',
738             value => {
739                 message_transport_type => 'email',
740                 branchcode => '',
741                 code => 'HOLD',
742                 module => 'reserves',
743                 lang => 'default',
744             }
745         });
746
747     my $sms_hold_notice = $builder->build({
748             source => 'Letter',
749             value => {
750                 message_transport_type => 'sms',
751                 branchcode => '',
752                 code => 'HOLD',
753                 module => 'reserves',
754                 lang=>'default',
755             }
756         });
757
758     my $hold_borrower = $builder->build({
759             source => 'Borrower',
760             value => {
761                 smsalertnumber=>'5555555555',
762                 email=>'a@b.com',
763             }
764         })->{borrowernumber};
765
766     my $hold = $builder->build({
767             source => 'Reserve',
768             value => {
769                borrowernumber=>$hold_borrower
770             }
771         });
772
773     ModReserveAffect($hold->{itemnumber}, $hold->{borrowernumber}, 0);
774     my $sms_message_address = $schema->resultset('MessageQueue')->search({
775             letter_code     => 'HOLD',
776             message_transport_type => 'sms',
777             borrowernumber => $hold_borrower,
778         })->next()->to_address();
779     is($sms_message_address, undef ,"We should not populate the sms message with the sms number, sending will do so");
780
781     my $email_message_address = $schema->resultset('MessageQueue')->search({
782             letter_code     => 'HOLD',
783             message_transport_type => 'email',
784             borrowernumber => $hold_borrower,
785         })->next()->to_address();
786     is($email_message_address, undef ,"We should not populate the hold message with the email address, sending will do so");
787
788 };
789
790 sub count_hold_print_messages {
791     my $message_count = $dbh->selectall_arrayref(q{
792         SELECT COUNT(*)
793         FROM message_queue
794         WHERE letter_code = 'HOLD' 
795         AND   message_transport_type = 'print'
796     });
797     return $message_count->[0]->[0];
798 }
799
800 # we reached the finish
801 $schema->storage->txn_rollback();