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