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