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