Bug 14711: Change prototype for AddReserve - pass a hashref
[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 => 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 $branchcode = Koha::Libraries->search->next->branchcode;
120
121 AddReserve(
122     {
123         branchcode     => $branchcode,
124         borrowernumber => $borrowernumber,
125         biblionumber   => $biblionumber,
126         priority       => 1,
127     }
128 );
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 circulation_rules');
191 Koha::CirculationRules->set_rules(
192     {
193         branchcode   => undef,
194         categorycode => undef,
195         itemtype     => undef,
196         rules        => {
197             reservesallowed => 25,
198             holds_per_record => 1,
199         }
200     }
201 );
202
203 # CPL allows only its own patrons to request its items
204 Koha::CirculationRules->set_rules(
205     {
206         branchcode   => $branch_1,
207         itemtype     => undef,
208         rules        => {
209             holdallowed  => 1,
210             returnbranch => 'homebranch',
211         }
212     }
213 );
214
215 # ... while FPL allows anybody to request its items
216 Koha::CirculationRules->set_rules(
217     {
218         branchcode   => $branch_2,
219         itemtype     => undef,
220         rules        => {
221             holdallowed  => 2,
222             returnbranch => 'homebranch',
223         }
224     }
225 );
226
227 my $bibnum2 = $builder->build_sample_biblio({frameworkcode => $frameworkcode})->biblionumber;
228
229 my ($itemnum_cpl, $itemnum_fpl);
230 ( undef, undef, $itemnum_cpl ) = AddItem(
231     {   homebranch    => $branch_1,
232         holdingbranch => $branch_1,
233         barcode       => 'bug10272_CPL',
234         itype         => $itemtype
235     },
236     $bibnum2
237 );
238 ( undef, undef, $itemnum_fpl ) = AddItem(
239     {   homebranch    => $branch_2,
240         holdingbranch => $branch_2,
241         barcode       => 'bug10272_FPL',
242         itype         => $itemtype
243     },
244     $bibnum2
245 );
246
247
248 # Ensure that priorities are numbered correcly when a hold is moved to waiting
249 # (bug 11947)
250 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
251 AddReserve(
252     {
253         branchcode     => $branch_3,
254         borrowernumber => $requesters{$branch_3},
255         biblionumber   => $bibnum2,
256         priority       => 1,
257     }
258 );
259 AddReserve(
260     {
261         branchcode     => $branch_2,
262         borrowernumber => $requesters{$branch_2},
263         biblionumber   => $bibnum2,
264         priority       => 2,
265     }
266 );
267 AddReserve(
268     {
269         branchcode     => $branch_1,
270         borrowernumber => $requesters{$branch_1},
271         biblionumber   => $bibnum2,
272         priority       => 3,
273     }
274 );
275 ModReserveAffect($itemnum_cpl, $requesters{$branch_3}, 0);
276
277 # Now it should have different priorities.
278 my $biblio = Koha::Biblios->find( $bibnum2 );
279 my $holds = $biblio->holds({}, { order_by => 'reserve_id' });;
280 is($holds->next->priority, 0, 'Item is correctly waiting');
281 is($holds->next->priority, 1, 'Item is correctly priority 1');
282 is($holds->next->priority, 2, 'Item is correctly priority 2');
283
284 my @reserves = Koha::Holds->search({ borrowernumber => $requesters{$branch_3} })->waiting();
285 is( @reserves, 1, 'GetWaiting got only the waiting reserve' );
286 is( $reserves[0]->borrowernumber(), $requesters{$branch_3}, 'GetWaiting got the reserve for the correct borrower' );
287
288
289 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
290 AddReserve(
291     {
292         branchcode     => $branch_3,
293         borrowernumber => $requesters{$branch_3},
294         biblionumber   => $bibnum2,
295         priority       => 1,
296     }
297 );
298 AddReserve(
299     {
300         branchcode     => $branch_2,
301         borrowernumber => $requesters{$branch_2},
302         biblionumber   => $bibnum2,
303         priority       => 2,
304     }
305 );
306
307 AddReserve(
308     {
309         branchcode     => $branch_1,
310         borrowernumber => $requesters{$branch_1},
311         biblionumber   => $bibnum2,
312         priority       => 3,
313     }
314 );
315
316 # Ensure that the item's home library controls hold policy lookup
317 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
318
319 my $messages;
320 # Return the CPL item at FPL.  The hold that should be triggered is
321 # the one placed by the CPL patron, as the other two patron's hold
322 # requests cannot be filled by that item per policy.
323 (undef, $messages, undef, undef) = AddReturn('bug10272_CPL', $branch_2);
324 is( $messages->{ResFound}->{borrowernumber},
325     $requesters{$branch_1},
326     'restrictive library\'s items only fill requests by own patrons (bug 10272)');
327
328 # Return the FPL item at FPL.  The hold that should be triggered is
329 # the one placed by the RPL patron, as that patron is first in line
330 # and RPL imposes no restrictions on whose holds its items can fill.
331
332 # Ensure that the preference 'LocalHoldsPriority' is not set (Bug 15244):
333 t::lib::Mocks::mock_preference( 'LocalHoldsPriority', '' );
334
335 (undef, $messages, undef, undef) = AddReturn('bug10272_FPL', $branch_2);
336 is( $messages->{ResFound}->{borrowernumber},
337     $requesters{$branch_3},
338     'for generous library, its items fill first hold request in line (bug 10272)');
339
340 $biblio = Koha::Biblios->find( $biblionumber );
341 $holds = $biblio->holds;
342 is($holds->count, 1, "Only one reserves for this biblio");
343 my $reserve_id = $holds->next->reserve_id;
344
345 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
346 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
347 # Test 9761a: Add a reserve without date, CheckReserve should return it
348 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
349 AddReserve(
350     {
351         branchcode     => $branch_1,
352         borrowernumber => $requesters{$branch_1},
353         biblionumber   => $bibnum,
354         priority       => 1,
355     }
356 );
357 ($status)=CheckReserves($itemnumber,undef,undef);
358 is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead');
359 ($status)=CheckReserves($itemnumber,undef,7);
360 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
361
362 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
363 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
364 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
365 my $resdate= dt_from_string();
366 $resdate->add_duration(DateTime::Duration->new(days => 4));
367 $resdate=output_pref($resdate);
368 AddReserve(
369     {
370         branchcode       => $branch_1,
371         borrowernumber   => $requesters{$branch_1},
372         biblionumber     => $bibnum,
373         priority         => 1,
374         reservation_date => $resdate,
375     }
376 );
377 ($status)=CheckReserves($itemnumber,undef,undef);
378 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
379
380 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
381 ($status)=CheckReserves($itemnumber,undef,3);
382 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
383 ($status)=CheckReserves($itemnumber,undef,4);
384 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
385
386 # Test 9761d: Check ResFound message of AddReturn for future hold
387 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
388 # In this test we do not need an issued item; it is just a 'checkin'
389 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
390 (my $doreturn, $messages)= AddReturn('97531',$branch_1);
391 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
392 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 3);
393 ($doreturn, $messages)= AddReturn('97531',$branch_1);
394 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
395 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 7);
396 ($doreturn, $messages)= AddReturn('97531',$branch_1);
397 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
398
399 # End of tests for bug 9761 (ConfirmFutureHolds)
400
401 # test marking a hold as captured
402 my $hold_notice_count = count_hold_print_messages();
403 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
404 my $new_count = count_hold_print_messages();
405 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
406
407 # test that duplicate notices aren't generated
408 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
409 $new_count = count_hold_print_messages();
410 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
411
412 # avoiding the not_same_branch error
413 t::lib::Mocks::mock_preference('IndependentBranches', 0);
414 is(
415     DelItemCheck( $bibnum, $itemnumber),
416     'book_reserved',
417     'item that is captured to fill a hold cannot be deleted',
418 );
419
420 my $letter = ReserveSlip( { branchcode => $branch_1, borrowernumber => $requesters{$branch_1}, biblionumber => $bibnum } );
421 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
422
423 # Tests for bug 9788: Does Koha::Item->current_holds return a future wait?
424 # 9788a: current_holds does not return future next available hold
425 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
426 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
427 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
428 $resdate= dt_from_string();
429 $resdate->add_duration(DateTime::Duration->new(days => 2));
430 $resdate=output_pref($resdate);
431 AddReserve(
432     {
433         branchcode       => $branch_1,
434         borrowernumber   => $requesters{$branch_1},
435         biblionumber     => $bibnum,
436         priority         => 1,
437         reservation_date => $resdate,
438     }
439 );
440
441 my $item = Koha::Items->find( $itemnumber );
442 $holds = $item->current_holds;
443 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
444 my $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
445 is( $future_holds->count, 0, 'current_holds does not return a future next available hold');
446 # 9788b: current_holds does not return future item level hold
447 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
448 AddReserve(
449     {
450         branchcode       => $branch_1,
451         borrowernumber   => $requesters{$branch_1},
452         biblionumber     => $bibnum,
453         priority         => 1,
454         reservation_date => $resdate,
455         itemnumber       => $itemnumber,
456     }
457 ); #item level hold
458 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
459 is( $future_holds->count, 0, 'current_holds does not return a future item level hold' );
460 # 9788c: current_holds returns future wait (confirmed future hold)
461 ModReserveAffect( $itemnumber,  $requesters{$branch_1} , 0); #confirm hold
462 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
463 is( $future_holds->count, 1, 'current_holds returns a future wait (confirmed future hold)' );
464 # End of tests for bug 9788
465
466 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
467 # Tests for CalculatePriority (bug 8918)
468 my $p = C4::Reserves::CalculatePriority($bibnum2);
469 is($p, 4, 'CalculatePriority should now return priority 4');
470 AddReserve(
471     {
472         branchcode     => $branch_1,
473         borrowernumber => $requesters{'CPL2'},
474         biblionumber   => $bibnum2,
475         priority       => $p,
476     }
477 );
478 $p = C4::Reserves::CalculatePriority($bibnum2);
479 is($p, 5, 'CalculatePriority should now return priority 5');
480 #some tests on bibnum
481 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
482 $p = C4::Reserves::CalculatePriority($bibnum);
483 is($p, 1, 'CalculatePriority should now return priority 1');
484 #add a new reserve and confirm it to waiting
485 AddReserve(
486     {
487         branchcode     => $branch_1,
488         borrowernumber => $requesters{$branch_1},
489         biblionumber   => $bibnum,
490         priority       => $p,
491         itemnumber     => $itemnumber,
492     }
493 );
494 $p = C4::Reserves::CalculatePriority($bibnum);
495 is($p, 2, 'CalculatePriority should now return priority 2');
496 ModReserveAffect( $itemnumber,  $requesters{$branch_1} , 0);
497 $p = C4::Reserves::CalculatePriority($bibnum);
498 is($p, 1, 'CalculatePriority should now return priority 1');
499 #add another biblio hold, no resdate
500 AddReserve(
501     {
502         branchcode     => $branch_1,
503         borrowernumber => $requesters{'CPL2'},
504         biblionumber   => $bibnum,
505         priority       => $p,
506     }
507 );
508 $p = C4::Reserves::CalculatePriority($bibnum);
509 is($p, 2, 'CalculatePriority should now return priority 2');
510 #add another future hold
511 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
512 $resdate= dt_from_string();
513 $resdate->add_duration(DateTime::Duration->new(days => 1));
514 AddReserve(
515     {
516         branchcode     => $branch_1,
517         borrowernumber => $requesters{'CPL2'},
518         biblionumber   => $bibnum,
519         priority       => $p,
520         reservation_date => output_pref($resdate),
521     }
522 );
523 $p = C4::Reserves::CalculatePriority($bibnum);
524 is($p, 2, 'CalculatePriority should now still return priority 2');
525 #calc priority with future resdate
526 $p = C4::Reserves::CalculatePriority($bibnum, $resdate);
527 is($p, 3, 'CalculatePriority should now return priority 3');
528 # End of tests for bug 8918
529
530 # Tests for cancel reserves by users from OPAC.
531 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
532 AddReserve(
533     {
534         branchcode     => $branch_1,
535         borrowernumber => $requesters{$branch_1},
536         biblionumber   => $item_bibnum,
537         priority       => 1,
538     }
539 );
540 my (undef, $canres, undef) = CheckReserves($itemnumber);
541
542 is( CanReserveBeCanceledFromOpac(), undef,
543     'CanReserveBeCanceledFromOpac should return undef if called without any parameter'
544 );
545 is(
546     CanReserveBeCanceledFromOpac( $canres->{resserve_id} ),
547     undef,
548     'CanReserveBeCanceledFromOpac should return undef if called without the reserve_id'
549 );
550 is(
551     CanReserveBeCanceledFromOpac( undef, $requesters{CPL} ),
552     undef,
553     'CanReserveBeCanceledFromOpac should return undef if called without borrowernumber'
554 );
555
556 my $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
557 is($cancancel, 1, 'Can user cancel its own reserve');
558
559 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_2});
560 is($cancancel, 0, 'Other user cant cancel reserve');
561
562 ModReserveAffect($itemnumber, $requesters{$branch_1}, 1);
563 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
564 is($cancancel, 0, 'Reserve in transfer status cant be canceled');
565
566 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
567 AddReserve(
568     {
569         branchcode     => $branch_1,
570         borrowernumber => $requesters{$branch_1},
571         biblionumber   => $item_bibnum,
572         priority       => 1,
573     }
574 );
575 (undef, $canres, undef) = CheckReserves($itemnumber);
576
577 ModReserveAffect($itemnumber, $requesters{$branch_1}, 0);
578 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
579 is($cancancel, 0, 'Reserve in waiting status cant be canceled');
580
581 # End of tests for bug 12876
582
583        ####
584 ####### Testing Bug 13113 - Prevent juvenile/children from reserving ageRestricted material >>>
585        ####
586
587 t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' );
588
589 #Reserving an not-agerestricted Biblio by a Borrower with no dateofbirth is tested previously.
590
591 #Set the ageRestriction for the Biblio
592 my $record = GetMarcBiblio({ biblionumber =>  $bibnum });
593 my ( $ageres_tagid, $ageres_subfieldid ) = GetMarcFromKohaField( "biblioitems.agerestriction" );
594 $record->append_fields(  MARC::Field->new($ageres_tagid, '', '', $ageres_subfieldid => 'PEGI 16')  );
595 C4::Biblio::ModBiblio( $record, $bibnum, $frameworkcode );
596
597 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'OK', "Reserving an ageRestricted Biblio without a borrower dateofbirth succeeds" );
598
599 #Set the dateofbirth for the Borrower making them "too young".
600 $borrower->{dateofbirth} = DateTime->now->add( years => -15 );
601 Koha::Patrons->find( $borrowernumber )->set({ dateofbirth => $borrower->{dateofbirth} })->store;
602
603 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'ageRestricted', "Reserving a 'PEGI 16' Biblio by a 15 year old borrower fails");
604
605 #Set the dateofbirth for the Borrower making them "too old".
606 $borrower->{dateofbirth} = DateTime->now->add( years => -30 );
607 Koha::Patrons->find( $borrowernumber )->set({ dateofbirth => $borrower->{dateofbirth} })->store;
608
609 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'OK', "Reserving a 'PEGI 16' Biblio by a 30 year old borrower succeeds");
610
611 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblio_with_no_item->{biblionumber})->{status} , '', "Biblio with no item. Status is empty");
612        ####
613 ####### EO Bug 13113 <<<
614        ####
615
616 $item = Koha::Items->find($itemnumber);
617
618 ok( C4::Reserves::IsAvailableForItemLevelRequest($item, $patron), "Reserving a book on item level" );
619
620 my $pickup_branch = $builder->build({ source => 'Branch' })->{ branchcode };
621 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits',  '1' );
622 t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' );
623 my $limit = Koha::Item::Transfer::Limit->new(
624     {
625         toBranch   => $pickup_branch,
626         fromBranch => $item->holdingbranch,
627         itemtype   => $item->effective_itemtype,
628     }
629 )->store();
630 is( C4::Reserves::IsAvailableForItemLevelRequest($item, $patron, $pickup_branch), 0, "Item level request not available due to transfer limit" );
631 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits',  '0' );
632
633 my $itype = C4::Reserves::_get_itype($item);
634 my $categorycode = $borrower->{categorycode};
635 my $holdingbranch = $item->{holdingbranch};
636 Koha::CirculationRules->set_rules(
637     {
638         categorycode => $categorycode,
639         itemtype     => $itype,
640         branchcode   => $holdingbranch,
641         rules => {
642             onshelfholds => 1,
643         }
644     }
645 );
646
647 # tests for MoveReserve in relation to ConfirmFutureHolds (BZ 14526)
648 #   hold from A pos 1, today, no fut holds: MoveReserve should fill it
649 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
650 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
651 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
652 AddReserve(
653     {
654         branchcode     => $branch_1,
655         borrowernumber => $borrowernumber,
656         biblionumber   => $item_bibnum,
657         priority       => 1,
658     }
659 );
660 MoveReserve( $itemnumber, $borrowernumber );
661 ($status)=CheckReserves( $itemnumber );
662 is( $status, '', 'MoveReserve filled hold');
663 #   hold from A waiting, today, no fut holds: MoveReserve should fill it
664 AddReserve(
665     {
666         branchcode     => $branch_1,
667         borrowernumber => $borrowernumber,
668         biblionumber   => $item_bibnum,
669         priority       => 1,
670         found          => 'W',
671     }
672 );
673 MoveReserve( $itemnumber, $borrowernumber );
674 ($status)=CheckReserves( $itemnumber );
675 is( $status, '', 'MoveReserve filled waiting hold');
676 #   hold from A pos 1, tomorrow, no fut holds: not filled
677 $resdate= dt_from_string();
678 $resdate->add_duration(DateTime::Duration->new(days => 1));
679 $resdate=output_pref($resdate);
680 AddReserve(
681     {
682         branchcode     => $branch_1,
683         borrowernumber => $borrowernumber,
684         biblionumber   => $item_bibnum,
685         priority       => 1,
686         reservation_date => $resdate,
687     }
688 );
689 MoveReserve( $itemnumber, $borrowernumber );
690 ($status)=CheckReserves( $itemnumber, undef, 1 );
691 is( $status, 'Reserved', 'MoveReserve did not fill future hold');
692 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
693 #   hold from A pos 1, tomorrow, fut holds=2: MoveReserve should fill it
694 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
695 AddReserve(
696     {
697         branchcode     => $branch_1,
698         borrowernumber => $borrowernumber,
699         biblionumber   => $item_bibnum,
700         priority       => 1,
701         reservation_date => $resdate,
702     }
703 );
704 MoveReserve( $itemnumber, $borrowernumber );
705 ($status)=CheckReserves( $itemnumber, undef, 2 );
706 is( $status, '', 'MoveReserve filled future hold now');
707 #   hold from A waiting, tomorrow, fut holds=2: MoveReserve should fill it
708 AddReserve(
709     {
710         branchcode     => $branch_1,
711         borrowernumber => $borrowernumber,
712         biblionumber   => $item_bibnum,
713         priority       => 1,
714         reservation_date => $resdate,
715     }
716 );
717 MoveReserve( $itemnumber, $borrowernumber );
718 ($status)=CheckReserves( $itemnumber, undef, 2 );
719 is( $status, '', 'MoveReserve filled future waiting hold now');
720 #   hold from A pos 1, today+3, fut holds=2: MoveReserve should not fill it
721 $resdate= dt_from_string();
722 $resdate->add_duration(DateTime::Duration->new(days => 3));
723 $resdate=output_pref($resdate);
724 AddReserve(
725     {
726         branchcode     => $branch_1,
727         borrowernumber => $borrowernumber,
728         biblionumber   => $item_bibnum,
729         priority       => 1,
730         reservation_date => $resdate,
731     }
732 );
733 MoveReserve( $itemnumber, $borrowernumber );
734 ($status)=CheckReserves( $itemnumber, undef, 3 );
735 is( $status, 'Reserved', 'MoveReserve did not fill future hold of 3 days');
736 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
737
738 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
739 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
740 $cache->clear_from_cache("default_value_for_mod_marc-");
741 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
742
743 subtest '_koha_notify_reserve() tests' => sub {
744
745     plan tests => 2;
746
747     my $wants_hold_and_email = {
748         wants_digest => '0',
749         transports => {
750             sms => 'HOLD',
751             email => 'HOLD',
752             },
753         letter_code => 'HOLD'
754     };
755
756     my $mp = Test::MockModule->new( 'C4::Members::Messaging' );
757
758     $mp->mock("GetMessagingPreferences",$wants_hold_and_email);
759
760     $dbh->do('DELETE FROM letter');
761
762     my $email_hold_notice = $builder->build({
763             source => 'Letter',
764             value => {
765                 message_transport_type => 'email',
766                 branchcode => '',
767                 code => 'HOLD',
768                 module => 'reserves',
769                 lang => 'default',
770             }
771         });
772
773     my $sms_hold_notice = $builder->build({
774             source => 'Letter',
775             value => {
776                 message_transport_type => 'sms',
777                 branchcode => '',
778                 code => 'HOLD',
779                 module => 'reserves',
780                 lang=>'default',
781             }
782         });
783
784     my $hold_borrower = $builder->build({
785             source => 'Borrower',
786             value => {
787                 smsalertnumber=>'5555555555',
788                 email=>'a@b.com',
789             }
790         })->{borrowernumber};
791
792     C4::Reserves::AddReserve(
793         {
794             branchcode     => $item->homebranch,
795             borrowernumber => $hold_borrower,
796             biblionumber   => $item->biblionumber,
797         }
798     );
799
800     ModReserveAffect($item->itemnumber, $hold_borrower, 0);
801     my $sms_message_address = $schema->resultset('MessageQueue')->search({
802             letter_code     => 'HOLD',
803             message_transport_type => 'sms',
804             borrowernumber => $hold_borrower,
805         })->next()->to_address();
806     is($sms_message_address, undef ,"We should not populate the sms message with the sms number, sending will do so");
807
808     my $email_message_address = $schema->resultset('MessageQueue')->search({
809             letter_code     => 'HOLD',
810             message_transport_type => 'email',
811             borrowernumber => $hold_borrower,
812         })->next()->to_address();
813     is($email_message_address, undef ,"We should not populate the hold message with the email address, sending will do so");
814
815 };
816
817 subtest 'ReservesNeedReturns' => sub {
818     plan tests => 18;
819
820     my $library    = $builder->build_object( { class => 'Koha::Libraries' } );
821     my $item_info  = {
822         homebranch       => $library->branchcode,
823         holdingbranch    => $library->branchcode,
824     };
825     my $item = $builder->build_sample_item($item_info);
826     my $patron   = $builder->build_object(
827         {
828             class => 'Koha::Patrons',
829             value => { branchcode => $library->branchcode, }
830         }
831     );
832     my $patron_2   = $builder->build_object(
833         {
834             class => 'Koha::Patrons',
835             value => { branchcode => $library->branchcode, }
836         }
837     );
838
839     my $priority = 1;
840
841     t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Test with feature disabled
842     my $hold = place_item_hold( $patron, $item, $library, $priority );
843     is( $hold->priority, $priority, 'If ReservesNeedReturns is 1, priority must not have been set to changed' );
844     is( $hold->found, undef, 'If ReservesNeedReturns is 1, found must not have been set waiting' );
845     $hold->delete;
846
847     t::lib::Mocks::mock_preference('ReservesNeedReturns', 0); # '0' means 'Automatically mark a hold as found and waiting'
848     $hold = place_item_hold( $patron, $item, $library, $priority );
849     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
850     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
851     $hold->delete;
852
853     $item->onloan('2010-01-01')->store;
854     $hold = place_item_hold( $patron, $item, $library, $priority );
855     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item onloan priority must be set to 1' );
856     $hold->delete;
857
858     t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 0); # '0' means damaged holds not allowed
859     $item->onloan(undef)->damaged(1)->store;
860     $hold = place_item_hold( $patron, $item, $library, $priority );
861     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item damaged and not allowed holds on damaged items priority must be set to 1' );
862     $hold->delete;
863     t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 1); # '0' means damaged holds not allowed
864     $hold = place_item_hold( $patron, $item, $library, $priority );
865     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and damaged holds allowed, priority must have been set to 0' );
866     is( $hold->found,  'W', 'If ReservesNeedReturns is 0 and damaged holds allowed, found must have been set waiting' );
867     $hold->delete;
868
869     my $hold_1 = place_item_hold( $patron, $item, $library, $priority );
870     is( $hold_1->found,  'W', 'First hold on item is set to waiting with ReservesNeedReturns set to 0' );
871     is( $hold_1->priority, 0, 'First hold on item is set to waiting with ReservesNeedReturns set to 0' );
872     $hold = place_item_hold( $patron_2, $item, $library, $priority );
873     is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item already on hold priority must be set to 1' );
874     $hold->delete;
875     $hold_1->delete;
876
877     my $transfer = $builder->build_object({
878         class => "Koha::Item::Transfers",
879         value => {
880           itemnumber  => $item->itemnumber,
881           datearrived => undef,
882         }
883     });
884     $item->damaged(0)->store;
885     $hold = place_item_hold( $patron, $item, $library, $priority );
886     is( $hold->found, undef, 'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
887     is( $hold->priority, 1,  'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
888     $hold->delete;
889     $transfer->delete;
890
891     $hold = place_item_hold( $patron, $item, $library, $priority );
892     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
893     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
894     $hold_1 = place_item_hold( $patron, $item, $library, $priority );
895     is( $hold_1->priority, 1, 'If ReservesNeedReturns is 0 but item has a hold priority is 1' );
896     $hold_1->suspend(1)->store; # We suspend the hold
897     $hold->delete; # Delete the waiting hold
898     $hold = place_item_hold( $patron, $item, $library, $priority );
899     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and other hold(s) suspended, priority must have been set to 0' );
900     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and other  hold(s) suspended, found must have been set waiting' );
901
902
903
904
905     t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Don't affect other tests
906 };
907
908 subtest 'ChargeReserveFee tests' => sub {
909
910     plan tests => 8;
911
912     my $library = $builder->build_object({ class => 'Koha::Libraries' });
913     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
914
915     my $fee   = 20;
916     my $title = 'A title';
917
918     my $context = Test::MockModule->new('C4::Context');
919     $context->mock( userenv => { branch => $library->id } );
920
921     my $line = C4::Reserves::ChargeReserveFee( $patron->id, $fee, $title );
922
923     is( ref($line), 'Koha::Account::Line' , 'Returns a Koha::Account::Line object');
924     ok( $line->is_debit, 'Generates a debit line' );
925     is( $line->debit_type_code, 'RESERVE' , 'generates RESERVE debit_type');
926     is( $line->borrowernumber, $patron->id , 'generated line belongs to the passed patron');
927     is( $line->amount, $fee , 'amount set correctly');
928     is( $line->amountoutstanding, $fee , 'amountoutstanding set correctly');
929     is( $line->description, "$title" , 'description is title of reserved item');
930     is( $line->branchcode, $library->id , "Library id is picked from userenv and stored correctly" );
931 };
932
933 subtest 'reserves.item_level_hold' => sub {
934     plan tests => 2;
935
936     my $item   = $builder->build_sample_item;
937     my $patron = $builder->build_object(
938         {
939             class => 'Koha::Patrons',
940             value => { branchcode => $item->homebranch }
941         }
942     );
943
944     subtest 'item level hold' => sub {
945         plan tests => 2;
946         my $reserve_id = AddReserve(
947             {
948                 branchcode     => $item->homebranch,
949                 borrowernumber => $patron->borrowernumber,
950                 biblionumber   => $item->biblionumber,
951                 priority       => 1,
952                 itemnumber     => $item->itemnumber,
953             }
954         );
955
956         my $hold = Koha::Holds->find($reserve_id);
957         is( $hold->item_level_hold, 1, 'item_level_hold should be set when AddReserve is called with a specific item' );
958
959         # Mark it waiting
960         ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
961
962         # Revert the waiting status
963         C4::Reserves::RevertWaitingStatus(
964             { itemnumber => $item->itemnumber } );
965
966         $hold = Koha::Holds->find($reserve_id);
967
968         is( $hold->itemnumber, $item->itemnumber, 'Itemnumber should not be removed when the waiting status is revert' );
969
970         $hold->delete;    # cleanup
971     };
972
973     subtest 'biblio level hold' => sub {
974         plan tests => 3;
975         my $reserve_id = AddReserve(
976             {
977                 branchcode     => $item->homebranch,
978                 borrowernumber => $patron->borrowernumber,
979                 biblionumber   => $item->biblionumber,
980                 priority       => 1,
981             }
982         );
983
984         my $hold = Koha::Holds->find($reserve_id);
985         is( $hold->item_level_hold, 0, 'item_level_hold should not be set when AddReserve is called without a specific item' );
986
987         # Mark it waiting
988         ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
989
990         $hold = Koha::Holds->find($reserve_id);
991         is( $hold->itemnumber, $item->itemnumber, 'Itemnumber should be set on hold confirmation' );
992
993         # Revert the waiting status
994         C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
995
996         $hold = Koha::Holds->find($reserve_id);
997         is( $hold->itemnumber, undef, 'Itemnumber should be removed when the waiting status is revert' );
998
999         $hold->delete;
1000     };
1001
1002 };
1003
1004 subtest 'MoveReserve additional test' => sub {
1005
1006     plan tests => 4;
1007
1008     # Create the items and patrons we need
1009     my $biblio = $builder->build_sample_biblio();
1010     my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
1011     my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1012     my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber, notforloan => 0, itype => $itype->itemtype });
1013     my $patron_1 = $builder->build_object({ class => "Koha::Patrons" });
1014     my $patron_2 = $builder->build_object({ class => "Koha::Patrons" });
1015
1016     # Place a hold on the title for both patrons
1017     my $reserve_1 = AddReserve(
1018         {
1019             branchcode     => $item_1->homebranch,
1020             borrowernumber => $patron_1->borrowernumber,
1021             biblionumber   => $biblio->biblionumber,
1022             priority       => 1,
1023             itemnumber     => $item_1->itemnumber,
1024         }
1025     );
1026     my $reserve_2 = AddReserve(
1027         {
1028             branchcode     => $item_2->homebranch,
1029             borrowernumber => $patron_2->borrowernumber,
1030             biblionumber   => $biblio->biblionumber,
1031             priority       => 1,
1032             itemnumber     => $item_1->itemnumber,
1033         }
1034     );
1035     is($patron_1->holds->next()->reserve_id, $reserve_1, "The 1st patron has a hold");
1036     is($patron_2->holds->next()->reserve_id, $reserve_2, "The 2nd patron has a hold");
1037
1038     # Fake the holds queue
1039     $dbh->do(q{INSERT INTO hold_fill_targets VALUES (?, ?, ?, ?, ?)},undef,($patron_1->borrowernumber,$biblio->biblionumber,$item_1->itemnumber,$item_1->homebranch,0));
1040
1041     # The 2nd hold should be filed even if the item is preselected for the first hold
1042     MoveReserve($item_1->itemnumber,$patron_2->borrowernumber);
1043     is($patron_2->holds->count, 0, "The 2nd patrons no longer has a hold");
1044     is($patron_2->old_holds->next()->reserve_id, $reserve_2, "The 2nd patrons hold was filled and moved to old holds");
1045
1046 };
1047
1048 sub count_hold_print_messages {
1049     my $message_count = $dbh->selectall_arrayref(q{
1050         SELECT COUNT(*)
1051         FROM message_queue
1052         WHERE letter_code = 'HOLD' 
1053         AND   message_transport_type = 'print'
1054     });
1055     return $message_count->[0]->[0];
1056 }
1057
1058 sub place_item_hold {
1059     my ($patron,$item,$library,$priority) = @_;
1060
1061     my $hold_id = C4::Reserves::AddReserve(
1062         {
1063             branchcode     => $library->branchcode,
1064             borrowernumber => $patron->borrowernumber,
1065             biblionumber   => $item->biblionumber,
1066             priority       => $priority,
1067             title          => "title for fee",
1068             itemnumber     => $item->itemnumber,
1069         }
1070     );
1071
1072     my $hold = Koha::Holds->find($hold_id);
1073     return $hold;
1074 }
1075
1076 # we reached the finish
1077 $schema->storage->txn_rollback();