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