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