]> git.koha-community.org Git - koha.git/blob - t/db_dependent/Reserves.t
Bug 30728: Add unit tests
[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 => 71;
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 qw( AddReturn AddIssue );
31 use C4::Items;
32 use C4::Biblio qw( GetMarcBiblio GetMarcFromKohaField ModBiblio );
33 use C4::Members;
34 use C4::Reserves qw( AddReserve AlterPriority CheckReserves GetReservesControlBranch ModReserve ModReserveAffect ReserveSlip CalculatePriority CanReserveBeCanceledFromOpac CanBookBeReserved IsAvailableForItemLevelRequest MoveReserve ChargeReserveFee RevertWaitingStatus CanItemBeReserved MergeHolds );
35 use Koha::ActionLogs;
36 use Koha::Caches;
37 use Koha::DateUtils qw( dt_from_string output_pref );
38 use Koha::Holds;
39 use Koha::Items;
40 use Koha::Libraries;
41 use Koha::Notice::Templates;
42 use Koha::Patrons;
43 use Koha::Patron::Categories;
44 use Koha::CirculationRules;
45
46 BEGIN {
47     require_ok('C4::Reserves');
48 }
49
50 # Start transaction
51 my $database = Koha::Database->new();
52 my $schema = $database->schema();
53 $schema->storage->txn_begin();
54 my $dbh = C4::Context->dbh;
55 $dbh->do('DELETE FROM circulation_rules');
56
57 my $builder = t::lib::TestBuilder->new;
58
59 my $frameworkcode = q//;
60
61
62 t::lib::Mocks::mock_preference('ReservesNeedReturns', 1);
63
64 # Somewhat arbitrary field chosen for age restriction unit tests. Must be added to db before the framework is cached
65 $dbh->do("update marc_subfield_structure set kohafield='biblioitems.agerestriction' where tagfield='521' and tagsubfield='a' and frameworkcode=?", undef, $frameworkcode);
66 my $cache = Koha::Caches->get_instance;
67 $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
68 $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
69 $cache->clear_from_cache("default_value_for_mod_marc-");
70 $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
71
72 ## Setup Test
73 # Add branches
74 my $branch_1 = $builder->build({ source => 'Branch' })->{ branchcode };
75 my $branch_2 = $builder->build({ source => 'Branch' })->{ branchcode };
76 my $branch_3 = $builder->build({ source => 'Branch' })->{ branchcode };
77 # Add categories
78 my $category_1 = $builder->build({ source => 'Category' })->{ categorycode };
79 my $category_2 = $builder->build({ source => 'Category' })->{ categorycode };
80 # Add an item type
81 my $itemtype = $builder->build(
82     { source => 'Itemtype', value => { notforloan => undef } } )->{itemtype};
83
84 t::lib::Mocks::mock_userenv({ branchcode => $branch_1 });
85
86 my $bibnum = $builder->build_sample_biblio({frameworkcode => $frameworkcode})->biblionumber;
87
88 # Create a helper item instance for testing
89 my $item = $builder->build_sample_item({ biblionumber => $bibnum, library => $branch_1, itype => $itemtype });
90
91 my $biblio_with_no_item = $builder->build_sample_biblio;
92
93 # Modify item; setting barcode.
94 my $testbarcode = '97531';
95 $item->barcode($testbarcode)->store; # FIXME We should not hardcode a barcode! Also, what's the purpose of this?
96
97 # Create a borrower
98 my %data = (
99     firstname =>  'my firstname',
100     surname => 'my surname',
101     categorycode => $category_1,
102     branchcode => $branch_1,
103 );
104 Koha::Patron::Categories->find($category_1)->set({ enrolmentfee => 0})->store;
105 my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
106 my $patron = Koha::Patrons->find( $borrowernumber );
107 my $borrower = $patron->unblessed;
108 my $biblionumber   = $bibnum;
109 my $barcode        = $testbarcode;
110
111 my $branchcode = Koha::Libraries->search->next->branchcode;
112
113 AddReserve(
114     {
115         branchcode     => $branchcode,
116         borrowernumber => $borrowernumber,
117         biblionumber   => $biblionumber,
118         priority       => 1,
119     }
120 );
121
122 my ($status, $reserve, $all_reserves) = CheckReserves($item->itemnumber, $barcode);
123
124 is($status, "Reserved", "CheckReserves Test 1");
125
126 ok(exists($reserve->{reserve_id}), 'CheckReserves() include reserve_id in its response');
127
128 ($status, $reserve, $all_reserves) = CheckReserves($item->itemnumber);
129 is($status, "Reserved", "CheckReserves Test 2");
130
131 ($status, $reserve, $all_reserves) = CheckReserves(undef, $barcode);
132 is($status, "Reserved", "CheckReserves Test 3");
133
134 my $ReservesControlBranch = C4::Context->preference('ReservesControlBranch');
135 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
136 ok(
137     'ItemHomeLib' eq GetReservesControlBranch(
138         { homebranch => 'ItemHomeLib' },
139         { branchcode => 'PatronHomeLib' }
140     ), "GetReservesControlBranch returns item home branch when set to ItemHomeLibrary"
141 );
142 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
143 ok(
144     'PatronHomeLib' eq GetReservesControlBranch(
145         { homebranch => 'ItemHomeLib' },
146         { branchcode => 'PatronHomeLib' }
147     ), "GetReservesControlBranch returns patron home branch when set to PatronLibrary"
148 );
149 t::lib::Mocks::mock_preference( 'ReservesControlBranch', $ReservesControlBranch );
150
151 ###
152 ### Regression test for bug 10272
153 ###
154 my %requesters = ();
155 $requesters{$branch_1} = Koha::Patron->new({
156     branchcode   => $branch_1,
157     categorycode => $category_2,
158     surname      => "borrower from $branch_1",
159 })->store->borrowernumber;
160 for my $i ( 2 .. 5 ) {
161     $requesters{"CPL$i"} = Koha::Patron->new({
162         branchcode   => $branch_1,
163         categorycode => $category_2,
164         surname      => "borrower $i from $branch_1",
165     })->store->borrowernumber;
166 }
167 $requesters{$branch_2} = Koha::Patron->new({
168     branchcode   => $branch_2,
169     categorycode => $category_2,
170     surname      => "borrower from $branch_2",
171 })->store->borrowernumber;
172 $requesters{$branch_3} = Koha::Patron->new({
173     branchcode   => $branch_3,
174     categorycode => $category_2,
175     surname      => "borrower from $branch_3",
176 })->store->borrowernumber;
177
178 # Configure rules so that $branch_1 allows only $branch_1 patrons
179 # to request its items, while $branch_2 will allow its items
180 # to fill holds from anywhere.
181
182 $dbh->do('DELETE FROM circulation_rules');
183 Koha::CirculationRules->set_rules(
184     {
185         branchcode   => undef,
186         categorycode => undef,
187         itemtype     => undef,
188         rules        => {
189             reservesallowed => 25,
190             holds_per_record => 1,
191         }
192     }
193 );
194
195 # CPL allows only its own patrons to request its items
196 Koha::CirculationRules->set_rules(
197     {
198         branchcode   => $branch_1,
199         itemtype     => undef,
200         rules        => {
201             holdallowed  => 'from_home_library',
202             returnbranch => 'homebranch',
203         }
204     }
205 );
206
207 # ... while FPL allows anybody to request its items
208 Koha::CirculationRules->set_rules(
209     {
210         branchcode   => $branch_2,
211         itemtype     => undef,
212         rules        => {
213             holdallowed  => 'from_any_library',
214             returnbranch => 'homebranch',
215         }
216     }
217 );
218
219 my $bibnum2 = $builder->build_sample_biblio({frameworkcode => $frameworkcode})->biblionumber;
220
221 my ($itemnum_cpl, $itemnum_fpl);
222 $itemnum_cpl = $builder->build_sample_item(
223     {
224         biblionumber => $bibnum2,
225         library      => $branch_1,
226         barcode      => 'bug10272_CPL',
227         itype        => $itemtype
228     }
229 )->itemnumber;
230 $itemnum_fpl = $builder->build_sample_item(
231     {
232         biblionumber => $bibnum2,
233         library      => $branch_2,
234         barcode      => 'bug10272_FPL',
235         itype        => $itemtype
236     }
237 )->itemnumber;
238
239 # Ensure that priorities are numbered correcly when a hold is moved to waiting
240 # (bug 11947)
241 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
242 AddReserve(
243     {
244         branchcode     => $branch_3,
245         borrowernumber => $requesters{$branch_3},
246         biblionumber   => $bibnum2,
247         priority       => 1,
248     }
249 );
250 AddReserve(
251     {
252         branchcode     => $branch_2,
253         borrowernumber => $requesters{$branch_2},
254         biblionumber   => $bibnum2,
255         priority       => 2,
256     }
257 );
258 AddReserve(
259     {
260         branchcode     => $branch_1,
261         borrowernumber => $requesters{$branch_1},
262         biblionumber   => $bibnum2,
263         priority       => 3,
264     }
265 );
266 ModReserveAffect($itemnum_cpl, $requesters{$branch_3}, 0);
267
268 # Now it should have different priorities.
269 my $biblio = Koha::Biblios->find( $bibnum2 );
270 my $holds = $biblio->holds({}, { order_by => 'reserve_id' });;
271 is($holds->next->priority, 0, 'Item is correctly waiting');
272 is($holds->next->priority, 1, 'Item is correctly priority 1');
273 is($holds->next->priority, 2, 'Item is correctly priority 2');
274
275 my @reserves = Koha::Holds->search({ borrowernumber => $requesters{$branch_3} })->waiting->as_list;
276 is( @reserves, 1, 'GetWaiting got only the waiting reserve' );
277 is( $reserves[0]->borrowernumber(), $requesters{$branch_3}, 'GetWaiting got the reserve for the correct borrower' );
278
279
280 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2));
281 AddReserve(
282     {
283         branchcode     => $branch_3,
284         borrowernumber => $requesters{$branch_3},
285         biblionumber   => $bibnum2,
286         priority       => 1,
287     }
288 );
289 AddReserve(
290     {
291         branchcode     => $branch_2,
292         borrowernumber => $requesters{$branch_2},
293         biblionumber   => $bibnum2,
294         priority       => 2,
295     }
296 );
297
298 AddReserve(
299     {
300         branchcode     => $branch_1,
301         borrowernumber => $requesters{$branch_1},
302         biblionumber   => $bibnum2,
303         priority       => 3,
304     }
305 );
306
307 # Ensure that the item's home library controls hold policy lookup
308 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
309
310 my $messages;
311 # Return the CPL item at FPL.  The hold that should be triggered is
312 # the one placed by the CPL patron, as the other two patron's hold
313 # requests cannot be filled by that item per policy.
314 (undef, $messages, undef, undef) = AddReturn('bug10272_CPL', $branch_2);
315 is( $messages->{ResFound}->{borrowernumber},
316     $requesters{$branch_1},
317     'restrictive library\'s items only fill requests by own patrons (bug 10272)');
318
319 # Return the FPL item at FPL.  The hold that should be triggered is
320 # the one placed by the RPL patron, as that patron is first in line
321 # and RPL imposes no restrictions on whose holds its items can fill.
322
323 # Ensure that the preference 'LocalHoldsPriority' is not set (Bug 15244):
324 t::lib::Mocks::mock_preference( 'LocalHoldsPriority', '' );
325
326 (undef, $messages, undef, undef) = AddReturn('bug10272_FPL', $branch_2);
327 is( $messages->{ResFound}->{borrowernumber},
328     $requesters{$branch_3},
329     'for generous library, its items fill first hold request in line (bug 10272)');
330
331 $biblio = Koha::Biblios->find( $biblionumber );
332 $holds = $biblio->holds;
333 is($holds->count, 1, "Only one reserves for this biblio");
334 $holds->next->reserve_id;
335
336 # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn
337 # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does)
338 # Test 9761a: Add a reserve without date, CheckReserve should return it
339 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
340 AddReserve(
341     {
342         branchcode     => $branch_1,
343         borrowernumber => $requesters{$branch_1},
344         biblionumber   => $bibnum,
345         priority       => 1,
346     }
347 );
348 ($status)=CheckReserves($item->itemnumber,undef,undef);
349 is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead');
350 ($status)=CheckReserves($item->itemnumber,undef,7);
351 is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead');
352
353 # Test 9761b: Add a reserve with future date, CheckReserve should not return it
354 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
355 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
356 my $resdate= dt_from_string();
357 $resdate->add_duration(DateTime::Duration->new(days => 4));
358 $resdate=output_pref($resdate);
359 my $reserve_id = AddReserve(
360     {
361         branchcode       => $branch_1,
362         borrowernumber   => $requesters{$branch_1},
363         biblionumber     => $bibnum,
364         priority         => 1,
365         reservation_date => $resdate,
366     }
367 );
368 ($status)=CheckReserves($item->itemnumber,undef,undef);
369 is( $status, '', 'CheckReserves returns no future reserve without lookahead');
370
371 # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough
372 ($status)=CheckReserves($item->itemnumber,undef,3);
373 is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead');
374 ($status)=CheckReserves($item->itemnumber,undef,4);
375 is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead');
376
377 # Test 9761d: Check ResFound message of AddReturn for future hold
378 # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves
379 # In this test we do not need an issued item; it is just a 'checkin'
380 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0);
381 (my $doreturn, $messages)= AddReturn('97531',$branch_1);
382 is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off');
383 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 3);
384 ($doreturn, $messages)= AddReturn('97531',$branch_1);
385 is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days');
386 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 7);
387 ($doreturn, $messages)= AddReturn('97531',$branch_1);
388 is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days');
389
390 # End of tests for bug 9761 (ConfirmFutureHolds)
391
392 # test marking a hold as captured
393 my $hold_notice_count = count_hold_print_messages();
394 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
395 my $new_count = count_hold_print_messages();
396 is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting');
397
398 # test that duplicate notices aren't generated
399 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
400 $new_count = count_hold_print_messages();
401 is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)');
402
403 # avoiding the not_same_branch error
404 t::lib::Mocks::mock_preference('IndependentBranches', 0);
405 $item = Koha::Items->find($item->itemnumber);
406 is(
407     @{$item->safe_delete->messages}[0]->message,
408     'book_reserved',
409     'item that is captured to fill a hold cannot be deleted',
410 );
411
412 my $letter = ReserveSlip( { branchcode => $branch_1, reserve_id => $reserve_id } );
413 ok(defined($letter), 'can successfully generate hold slip (bug 10949)');
414
415 # Tests for bug 9788: Does Koha::Item->current_holds return a future wait?
416 # 9788a: current_holds does not return future next available hold
417 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
418 t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2);
419 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
420 $resdate= dt_from_string();
421 $resdate->add_duration(DateTime::Duration->new(days => 2));
422 $resdate=output_pref($resdate);
423 AddReserve(
424     {
425         branchcode       => $branch_1,
426         borrowernumber   => $requesters{$branch_1},
427         biblionumber     => $bibnum,
428         priority         => 1,
429         reservation_date => $resdate,
430     }
431 );
432
433 $holds = $item->current_holds;
434 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
435 my $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
436 is( $future_holds->count, 0, 'current_holds does not return a future next available hold');
437 # 9788b: current_holds does not return future item level hold
438 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
439 AddReserve(
440     {
441         branchcode       => $branch_1,
442         borrowernumber   => $requesters{$branch_1},
443         biblionumber     => $bibnum,
444         priority         => 1,
445         reservation_date => $resdate,
446         itemnumber       => $item->itemnumber,
447     }
448 ); #item level hold
449 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
450 is( $future_holds->count, 0, 'current_holds does not return a future item level hold' );
451 # 9788c: current_holds returns future wait (confirmed future hold)
452 ModReserveAffect( $item->itemnumber,  $requesters{$branch_1} , 0); #confirm hold
453 $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } );
454 is( $future_holds->count, 1, 'current_holds returns a future wait (confirmed future hold)' );
455 # End of tests for bug 9788
456
457 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
458 # Tests for CalculatePriority (bug 8918)
459 my $p = C4::Reserves::CalculatePriority($bibnum2);
460 is($p, 4, 'CalculatePriority should now return priority 4');
461 AddReserve(
462     {
463         branchcode     => $branch_1,
464         borrowernumber => $requesters{'CPL2'},
465         biblionumber   => $bibnum2,
466         priority       => $p,
467     }
468 );
469 $p = C4::Reserves::CalculatePriority($bibnum2);
470 is($p, 5, 'CalculatePriority should now return priority 5');
471 #some tests on bibnum
472 $dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum));
473 $p = C4::Reserves::CalculatePriority($bibnum);
474 is($p, 1, 'CalculatePriority should now return priority 1');
475 #add a new reserve and confirm it to waiting
476 AddReserve(
477     {
478         branchcode     => $branch_1,
479         borrowernumber => $requesters{$branch_1},
480         biblionumber   => $bibnum,
481         priority       => $p,
482         itemnumber     => $item->itemnumber,
483     }
484 );
485 $p = C4::Reserves::CalculatePriority($bibnum);
486 is($p, 2, 'CalculatePriority should now return priority 2');
487 ModReserveAffect( $item->itemnumber,  $requesters{$branch_1} , 0);
488 $p = C4::Reserves::CalculatePriority($bibnum);
489 is($p, 1, 'CalculatePriority should now return priority 1');
490 #add another biblio hold, no resdate
491 AddReserve(
492     {
493         branchcode     => $branch_1,
494         borrowernumber => $requesters{'CPL2'},
495         biblionumber   => $bibnum,
496         priority       => $p,
497     }
498 );
499 $p = C4::Reserves::CalculatePriority($bibnum);
500 is($p, 2, 'CalculatePriority should now return priority 2');
501 #add another future hold
502 t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1);
503 $resdate= dt_from_string();
504 $resdate->add_duration(DateTime::Duration->new(days => 1));
505 AddReserve(
506     {
507         branchcode     => $branch_1,
508         borrowernumber => $requesters{'CPL2'},
509         biblionumber   => $bibnum,
510         priority       => $p,
511         reservation_date => output_pref($resdate),
512     }
513 );
514 $p = C4::Reserves::CalculatePriority($bibnum);
515 is($p, 2, 'CalculatePriority should now still return priority 2');
516 #calc priority with future resdate
517 $p = C4::Reserves::CalculatePriority($bibnum, $resdate);
518 is($p, 3, 'CalculatePriority should now return priority 3');
519 # End of tests for bug 8918
520
521 # Tests for cancel reserves by users from OPAC.
522 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
523 AddReserve(
524     {
525         branchcode     => $branch_1,
526         borrowernumber => $requesters{$branch_1},
527         biblionumber   => $bibnum,
528         priority       => 1,
529     }
530 );
531 my (undef, $canres, undef) = CheckReserves($item->itemnumber);
532
533 is( CanReserveBeCanceledFromOpac(), undef,
534     'CanReserveBeCanceledFromOpac should return undef if called without any parameter'
535 );
536 is(
537     CanReserveBeCanceledFromOpac( $canres->{resserve_id} ),
538     undef,
539     'CanReserveBeCanceledFromOpac should return undef if called without the reserve_id'
540 );
541 is(
542     CanReserveBeCanceledFromOpac( undef, $requesters{CPL} ),
543     undef,
544     'CanReserveBeCanceledFromOpac should return undef if called without borrowernumber'
545 );
546
547 my $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
548 is($cancancel, 1, 'Can user cancel its own reserve');
549
550 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_2});
551 is($cancancel, 0, 'Other user cant cancel reserve');
552
553 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 1);
554 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
555 is($cancancel, 0, 'Reserve in transfer status cant be canceled');
556
557 $dbh->do('DELETE FROM reserves', undef, ($bibnum));
558 is( CanReserveBeCanceledFromOpac($canres->{resserve_id}, $requesters{$branch_1}), undef,
559     'Cannot cancel a deleted hold' );
560
561 AddReserve(
562     {
563         branchcode     => $branch_1,
564         borrowernumber => $requesters{$branch_1},
565         biblionumber   => $bibnum,
566         priority       => 1,
567     }
568 );
569 (undef, $canres, undef) = CheckReserves($item->itemnumber);
570
571 ModReserveAffect($item->itemnumber, $requesters{$branch_1}, 0);
572 $cancancel = CanReserveBeCanceledFromOpac($canres->{reserve_id}, $requesters{$branch_1});
573 is($cancancel, 0, 'Reserve in waiting status cant be canceled');
574
575 # End of tests for bug 12876
576
577        ####
578 ####### Testing Bug 13113 - Prevent juvenile/children from reserving ageRestricted material >>>
579        ####
580
581 t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' );
582
583 #Reserving an not-agerestricted Biblio by a Borrower with no dateofbirth is tested previously.
584
585 #Set the ageRestriction for the Biblio
586 my $record = GetMarcBiblio({ biblionumber =>  $bibnum });
587 my ( $ageres_tagid, $ageres_subfieldid ) = GetMarcFromKohaField( "biblioitems.agerestriction" );
588 $record->append_fields(  MARC::Field->new($ageres_tagid, '', '', $ageres_subfieldid => 'PEGI 16')  );
589 C4::Biblio::ModBiblio( $record, $bibnum, $frameworkcode );
590
591 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'OK', "Reserving an ageRestricted Biblio without a borrower dateofbirth succeeds" );
592
593 #Set the dateofbirth for the Borrower making them "too young".
594 $borrower->{dateofbirth} = DateTime->now->add( years => -15 );
595 Koha::Patrons->find( $borrowernumber )->set({ dateofbirth => $borrower->{dateofbirth} })->store;
596
597 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'ageRestricted', "Reserving a 'PEGI 16' Biblio by a 15 year old borrower fails");
598
599 #Set the dateofbirth for the Borrower making them "too old".
600 $borrower->{dateofbirth} = DateTime->now->add( years => -30 );
601 Koha::Patrons->find( $borrowernumber )->set({ dateofbirth => $borrower->{dateofbirth} })->store;
602
603 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'OK', "Reserving a 'PEGI 16' Biblio by a 30 year old borrower succeeds");
604
605 is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblio_with_no_item->biblionumber)->{status} , '', "Biblio with no item. Status is empty");
606        ####
607 ####### EO Bug 13113 <<<
608        ####
609
610 ok( C4::Reserves::IsAvailableForItemLevelRequest($item, $patron), "Reserving a book on item level" );
611
612 my $pickup_branch = $builder->build({ source => 'Branch' })->{ branchcode };
613 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits',  '1' );
614 t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' );
615 my $limit = Koha::Item::Transfer::Limit->new(
616     {
617         toBranch   => $pickup_branch,
618         fromBranch => $item->holdingbranch,
619         itemtype   => $item->effective_itemtype,
620     }
621 )->store();
622 is( C4::Reserves::IsAvailableForItemLevelRequest($item, $patron, $pickup_branch), 0, "Item level request not available due to transfer limit" );
623 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits',  '0' );
624
625 my $categorycode = $borrower->{categorycode};
626 my $holdingbranch = $item->{holdingbranch};
627 Koha::CirculationRules->set_rules(
628     {
629         categorycode => $categorycode,
630         itemtype     => $item->effective_itemtype,
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           datecancelled => undef
874         }
875     });
876     $item->damaged(0)->store;
877     $hold = place_item_hold( $patron, $item, $library, $priority );
878     is( $hold->found, undef, 'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
879     is( $hold->priority, 1,  'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' );
880     $hold->delete;
881     $transfer->delete;
882
883     $hold = place_item_hold( $patron, $item, $library, $priority );
884     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' );
885     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' );
886     $hold_1 = place_item_hold( $patron, $item, $library, $priority );
887     is( $hold_1->priority, 1, 'If ReservesNeedReturns is 0 but item has a hold priority is 1' );
888     $hold_1->suspend(1)->store; # We suspend the hold
889     $hold->delete; # Delete the waiting hold
890     $hold = place_item_hold( $patron, $item, $library, $priority );
891     is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and other hold(s) suspended, priority must have been set to 0' );
892     is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and other  hold(s) suspended, found must have been set waiting' );
893
894
895
896
897     t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Don't affect other tests
898 };
899
900 subtest 'ChargeReserveFee tests' => sub {
901
902     plan tests => 8;
903
904     my $library = $builder->build_object({ class => 'Koha::Libraries' });
905     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
906
907     my $fee   = 20;
908     my $title = 'A title';
909
910     my $context = Test::MockModule->new('C4::Context');
911     $context->mock( userenv => { branch => $library->id } );
912
913     my $line = C4::Reserves::ChargeReserveFee( $patron->id, $fee, $title );
914
915     is( ref($line), 'Koha::Account::Line' , 'Returns a Koha::Account::Line object');
916     ok( $line->is_debit, 'Generates a debit line' );
917     is( $line->debit_type_code, 'RESERVE' , 'generates RESERVE debit_type');
918     is( $line->borrowernumber, $patron->id , 'generated line belongs to the passed patron');
919     is( $line->amount, $fee , 'amount set correctly');
920     is( $line->amountoutstanding, $fee , 'amountoutstanding set correctly');
921     is( $line->description, "$title" , 'description is title of reserved item');
922     is( $line->branchcode, $library->id , "Library id is picked from userenv and stored correctly" );
923 };
924
925 subtest 'reserves.item_level_hold' => sub {
926     plan tests => 2;
927
928     my $item   = $builder->build_sample_item;
929     my $patron = $builder->build_object(
930         {
931             class => 'Koha::Patrons',
932             value => { branchcode => $item->homebranch }
933         }
934     );
935
936     subtest 'item level hold' => sub {
937         plan tests => 3;
938         my $reserve_id = AddReserve(
939             {
940                 branchcode     => $item->homebranch,
941                 borrowernumber => $patron->borrowernumber,
942                 biblionumber   => $item->biblionumber,
943                 priority       => 1,
944                 itemnumber     => $item->itemnumber,
945             }
946         );
947
948         my $hold = Koha::Holds->find($reserve_id);
949         is( $hold->item_level_hold, 1, 'item_level_hold should be set when AddReserve is called with a specific item' );
950
951         # Mark it waiting
952         ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
953
954         my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
955         $mock->mock( 'enqueue', sub {
956             my ( $self, $args ) = @_;
957             is_deeply(
958                 $args->{biblio_ids},
959                 [ $hold->biblionumber ],
960                 "AlterPriority triggers a holds queue update for the related biblio"
961             );
962         } );
963
964         t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
965
966         # Revert the waiting status
967         C4::Reserves::RevertWaitingStatus(
968             { itemnumber => $item->itemnumber } );
969
970         $hold = Koha::Holds->find($reserve_id);
971
972         is( $hold->itemnumber, $item->itemnumber, 'Itemnumber should not be removed when the waiting status is revert' );
973
974         t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
975
976         $hold->set_waiting;
977
978         # Revert the waiting status, RealTimeHoldsQueue => shouldn't add a test
979         C4::Reserves::RevertWaitingStatus(
980             { itemnumber => $item->itemnumber } );
981
982         $hold->delete;    # cleanup
983     };
984
985     subtest 'biblio level hold' => sub {
986         plan tests => 3;
987         my $reserve_id = AddReserve(
988             {
989                 branchcode     => $item->homebranch,
990                 borrowernumber => $patron->borrowernumber,
991                 biblionumber   => $item->biblionumber,
992                 priority       => 1,
993             }
994         );
995
996         my $hold = Koha::Holds->find($reserve_id);
997         is( $hold->item_level_hold, 0, 'item_level_hold should not be set when AddReserve is called without a specific item' );
998
999         # Mark it waiting
1000         ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 );
1001
1002         $hold = Koha::Holds->find($reserve_id);
1003         is( $hold->itemnumber, $item->itemnumber, 'Itemnumber should be set on hold confirmation' );
1004
1005         # Revert the waiting status
1006         C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } );
1007
1008         $hold = Koha::Holds->find($reserve_id);
1009         is( $hold->itemnumber, undef, 'Itemnumber should be removed when the waiting status is revert' );
1010
1011         $hold->delete;
1012     };
1013
1014 };
1015
1016 subtest 'MoveReserve additional test' => sub {
1017
1018     plan tests => 4;
1019
1020     # Create the items and patrons we need
1021     my $biblio = $builder->build_sample_biblio();
1022     my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
1023     my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1024     my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber, notforloan => 0, itype => $itype->itemtype });
1025     my $patron_1 = $builder->build_object({ class => "Koha::Patrons" });
1026     my $patron_2 = $builder->build_object({ class => "Koha::Patrons" });
1027
1028     # Place a hold on the title for both patrons
1029     my $reserve_1 = AddReserve(
1030         {
1031             branchcode     => $item_1->homebranch,
1032             borrowernumber => $patron_1->borrowernumber,
1033             biblionumber   => $biblio->biblionumber,
1034             priority       => 1,
1035             itemnumber     => $item_1->itemnumber,
1036         }
1037     );
1038     my $reserve_2 = AddReserve(
1039         {
1040             branchcode     => $item_2->homebranch,
1041             borrowernumber => $patron_2->borrowernumber,
1042             biblionumber   => $biblio->biblionumber,
1043             priority       => 1,
1044             itemnumber     => $item_1->itemnumber,
1045         }
1046     );
1047     is($patron_1->holds->next()->reserve_id, $reserve_1, "The 1st patron has a hold");
1048     is($patron_2->holds->next()->reserve_id, $reserve_2, "The 2nd patron has a hold");
1049
1050     # Fake the holds queue
1051     $dbh->do(q{INSERT INTO hold_fill_targets VALUES (?, ?, ?, ?, ?,?)},undef,($patron_1->borrowernumber,$biblio->biblionumber,$item_1->itemnumber,$item_1->homebranch,0,$reserve_1));
1052
1053     # The 2nd hold should be filed even if the item is preselected for the first hold
1054     MoveReserve($item_1->itemnumber,$patron_2->borrowernumber);
1055     is($patron_2->holds->count, 0, "The 2nd patrons no longer has a hold");
1056     is($patron_2->old_holds->next()->reserve_id, $reserve_2, "The 2nd patrons hold was filled and moved to old holds");
1057
1058 };
1059
1060 subtest 'RevertWaitingStatus' => sub {
1061
1062     plan tests => 2;
1063
1064     # Create the items and patrons we need
1065     my $biblio  = $builder->build_sample_biblio();
1066     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1067     my $itype   = $builder->build_object(
1068         { class => "Koha::ItemTypes", value => { notforloan => 0 } } );
1069     my $item_1 = $builder->build_sample_item(
1070         {
1071             biblionumber => $biblio->biblionumber,
1072             itype        => $itype->itemtype,
1073             library      => $library->branchcode
1074         }
1075     );
1076     my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1077     my $patron_2 = $builder->build_object( { class => "Koha::Patrons" } );
1078     my $patron_3 = $builder->build_object( { class => "Koha::Patrons" } );
1079     my $patron_4 = $builder->build_object( { class => "Koha::Patrons" } );
1080
1081     # Place a hold on the title for both patrons
1082     my $priority = 1;
1083     my $hold_1 = place_item_hold( $patron_1, $item_1, $library, $priority );
1084     my $hold_2 = place_item_hold( $patron_2, $item_1, $library, $priority );
1085     my $hold_3 = place_item_hold( $patron_3, $item_1, $library, $priority );
1086     my $hold_4 = place_item_hold( $patron_4, $item_1, $library, $priority );
1087
1088     $hold_1->set_waiting;
1089     AddIssue( $patron_3->unblessed, $item_1->barcode, undef, 'revert' );
1090
1091     my $holds = $biblio->holds;
1092     is( $holds->count, 3, 'One hold has been deleted' );
1093     is_deeply(
1094         [
1095             $holds->next->priority, $holds->next->priority,
1096             $holds->next->priority
1097         ],
1098         [ 1, 2, 3 ],
1099         'priorities have been reordered'
1100     );
1101 };
1102
1103 subtest 'CheckReserves additional tests' => sub {
1104
1105     plan tests => 8;
1106
1107     my $item = $builder->build_sample_item;
1108     my $reserve1 = $builder->build_object(
1109         {
1110             class => "Koha::Holds",
1111             value => {
1112                 found            => undef,
1113                 priority         => 1,
1114                 itemnumber       => undef,
1115                 biblionumber     => $item->biblionumber,
1116                 waitingdate      => undef,
1117                 cancellationdate => undef,
1118                 item_level_hold  => 0,
1119                 lowestPriority   => 0,
1120                 expirationdate   => undef,
1121                 suspend_until    => undef,
1122                 suspend          => 0,
1123                 itemtype         => undef,
1124             }
1125         }
1126     );
1127     my $reserve2 = $builder->build_object(
1128         {
1129             class => "Koha::Holds",
1130             value => {
1131                 found            => undef,
1132                 priority         => 2,
1133                 biblionumber     => $item->biblionumber,
1134                 borrowernumber   => $reserve1->borrowernumber,
1135                 itemnumber       => undef,
1136                 waitingdate      => undef,
1137                 cancellationdate => undef,
1138                 item_level_hold  => 0,
1139                 lowestPriority   => 0,
1140                 expirationdate   => undef,
1141                 suspend_until    => undef,
1142                 suspend          => 0,
1143                 itemtype         => undef,
1144             }
1145         }
1146     );
1147
1148     my $tmp_holdsqueue = $builder->build(
1149         {
1150             source => 'TmpHoldsqueue',
1151             value  => {
1152                 borrowernumber => $reserve1->borrowernumber,
1153                 biblionumber   => $reserve1->biblionumber,
1154             }
1155         }
1156     );
1157     my $fill_target = $builder->build(
1158         {
1159             source => 'HoldFillTarget',
1160             value  => {
1161                 borrowernumber     => $reserve1->borrowernumber,
1162                 biblionumber       => $reserve1->biblionumber,
1163                 itemnumber         => $item->itemnumber,
1164                 item_level_request => 0,
1165             }
1166         }
1167     );
1168
1169     ModReserveAffect( $item->itemnumber, $reserve1->borrowernumber, 1,
1170         $reserve1->reserve_id );
1171     my ( $status, $matched_reserve, $possible_reserves ) =
1172       CheckReserves( $item->itemnumber );
1173
1174     is( $status, 'Transferred', "We found a reserve" );
1175     is( $matched_reserve->{reserve_id},
1176         $reserve1->reserve_id, "We got the Transit reserve" );
1177     is( scalar @$possible_reserves, 2, 'We do get both reserves' );
1178
1179     my $patron_B = $builder->build_object({ class => "Koha::Patrons" });
1180     my $item_A = $builder->build_sample_item;
1181     my $item_B = $builder->build_sample_item({
1182         homebranch => $patron_B->branchcode,
1183         biblionumber => $item_A->biblionumber,
1184         itype => $item_A->itype
1185     });
1186     Koha::CirculationRules->set_rules(
1187         {
1188             branchcode   => undef,
1189             categorycode => undef,
1190             itemtype     => $item_A->itype,
1191             rules        => {
1192                 reservesallowed => 25,
1193                 holds_per_record => 1,
1194             }
1195         }
1196     );
1197     Koha::CirculationRules->set_rule({
1198         branchcode => undef,
1199         itemtype   => $item_A->itype,
1200         rule_name  => 'holdallowed',
1201         rule_value => 'from_home_library'
1202     });
1203     my $reserve_id = AddReserve(
1204         {
1205             branchcode     => $patron_B->branchcode,
1206             borrowernumber => $patron_B->borrowernumber,
1207             biblionumber   => $item_A->biblionumber,
1208             priority       => 1,
1209             itemnumber     => undef,
1210         }
1211     );
1212
1213     ok( $reserve_id, "We can place a record level hold because one item is owned by patron's home library");
1214     t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary');
1215     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A->itemnumber );
1216     is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch");
1217     Koha::CirculationRules->set_rule({
1218         branchcode => $item_A->homebranch,
1219         itemtype   => $item_A->itype,
1220         rule_name  => 'holdallowed',
1221         rule_value => 'from_any_library'
1222     });
1223     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A->itemnumber );
1224     is( $status, "Reserved", "We fill the hold with item A because item's branch rule says allow any");
1225
1226
1227     # Changing the control branch should change only the rule we get
1228     t::lib::Mocks::mock_preference('ReservesControlBranch', 'PatronLibrary');
1229     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A->itemnumber );
1230     is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch");
1231     Koha::CirculationRules->set_rule({
1232         branchcode   => $patron_B->branchcode,
1233         itemtype   => $item_A->itype,
1234         rule_name  => 'holdallowed',
1235         rule_value => 'from_any_library'
1236     });
1237     ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A->itemnumber );
1238     is( $status, "Reserved", "We fill the hold with item A because patron's branch rule says allow any");
1239
1240 };
1241
1242 subtest 'AllowHoldOnPatronPossession test' => sub {
1243
1244     plan tests => 4;
1245
1246     # Create the items and patrons we need
1247     my $biblio = $builder->build_sample_biblio();
1248     my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } });
1249     my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype });
1250     my $patron = $builder->build_object({ class => "Koha::Patrons",
1251                                           value => { branchcode => $item->homebranch }});
1252
1253     C4::Circulation::AddIssue($patron->unblessed,
1254                               $item->barcode);
1255     t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 0);
1256
1257     is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1258                                        $item->biblionumber)->{status},
1259        'alreadypossession',
1260        'Patron cannot place hold on a book loaned to itself');
1261
1262     is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status},
1263        'alreadypossession',
1264        'Patron cannot place hold on an item loaned to itself');
1265
1266     t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 1);
1267
1268     is(C4::Reserves::CanBookBeReserved($patron->borrowernumber,
1269                                        $item->biblionumber)->{status},
1270        'OK',
1271        'Patron can place hold on a book loaned to itself');
1272
1273     is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status},
1274        'OK',
1275        'Patron can place hold on an item loaned to itself');
1276 };
1277
1278 subtest 'MergeHolds' => sub {
1279
1280     plan tests => 1;
1281
1282     my $biblio_1  = $builder->build_sample_biblio();
1283     my $biblio_2  = $builder->build_sample_biblio();
1284     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1285     my $itype   = $builder->build_object(
1286         { class => "Koha::ItemTypes", value => { notforloan => 0 } } );
1287     my $item_1 = $builder->build_sample_item(
1288         {
1289             biblionumber => $biblio_1->biblionumber,
1290             itype        => $itype->itemtype,
1291             library      => $library->branchcode
1292         }
1293     );
1294     my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } );
1295
1296     # Place a hold on $biblio_1
1297     my $priority = 1;
1298     place_item_hold( $patron_1, $item_1, $library, $priority );
1299
1300     # Move and make sure hold is now on $biblio_2
1301     C4::Reserves::MergeHolds($dbh, $biblio_2->biblionumber, $biblio_1->biblionumber);
1302     is( $biblio_2->holds->count, 1, 'Hold has been transferred' );
1303 };
1304
1305 subtest 'ModReserveAffect logging' => sub {
1306
1307     plan tests => 4;
1308
1309     my $item = $builder->build_sample_item;
1310     my $patron = $builder->build_object(
1311         {
1312             class => "Koha::Patrons",
1313             value => { branchcode => $item->homebranch }
1314         }
1315     );
1316
1317     t::lib::Mocks::mock_userenv({ patron => $patron });
1318     t::lib::Mocks::mock_preference('HoldsLog', 1);
1319
1320     my $reserve_id = AddReserve(
1321         {
1322             branchcode     => $item->homebranch,
1323             borrowernumber => $patron->borrowernumber,
1324             biblionumber   => $item->biblionumber,
1325             priority       => 1,
1326             itemnumber     => $item->itemnumber,
1327         }
1328     );
1329
1330     my $hold = Koha::Holds->find($reserve_id);
1331     my $previous_timestamp = '1970-01-01 12:34:56';
1332     $hold->timestamp($previous_timestamp)->store;
1333
1334     $hold = Koha::Holds->find($reserve_id);
1335     is( $hold->timestamp, $previous_timestamp, 'Make sure the previous timestamp has been used' );
1336
1337     # Avoid warnings
1338     my $reserve_mock = Test::MockModule->new('C4::Reserves');
1339     $reserve_mock->mock( '_koha_notify_reserve', undef );
1340
1341     # Mark it waiting
1342     ModReserveAffect( $item->itemnumber, $patron->borrowernumber );
1343
1344     $hold->discard_changes;
1345     ok( $hold->is_waiting, 'Hold has been set waiting' );
1346     isnt( $hold->timestamp, $previous_timestamp, 'The timestamp has been modified' );
1347
1348     my $log = Koha::ActionLogs->search({ module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id })->next;
1349     my $expected = sprintf q{'timestamp' => '%s'}, $hold->timestamp;
1350     like( $log->info, qr{$expected}, 'Timestamp logged is the current one' );
1351 };
1352
1353 sub count_hold_print_messages {
1354     my $message_count = $dbh->selectall_arrayref(q{
1355         SELECT COUNT(*)
1356         FROM message_queue
1357         WHERE letter_code = 'HOLD' 
1358         AND   message_transport_type = 'print'
1359     });
1360     return $message_count->[0]->[0];
1361 }
1362
1363 sub place_item_hold {
1364     my ($patron,$item,$library,$priority) = @_;
1365
1366     my $hold_id = C4::Reserves::AddReserve(
1367         {
1368             branchcode     => $library->branchcode,
1369             borrowernumber => $patron->borrowernumber,
1370             biblionumber   => $item->biblionumber,
1371             priority       => $priority,
1372             title          => "title for fee",
1373             itemnumber     => $item->itemnumber,
1374         }
1375     );
1376
1377     my $hold = Koha::Holds->find($hold_id);
1378     return $hold;
1379 }
1380
1381 # we reached the finish
1382 $schema->storage->txn_rollback();
1383
1384 subtest 'IsAvailableForItemLevelRequest() tests' => sub {
1385
1386     plan tests => 2;
1387
1388     $schema->storage->txn_begin;
1389
1390     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1391
1392     my $item_type = undef;
1393
1394     my $item_mock = Test::MockModule->new('Koha::Item');
1395     $item_mock->mock( 'effective_itemtype', sub { return $item_type; } );
1396
1397     my $item = $builder->build_sample_item;
1398
1399     ok(
1400         !C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ),
1401         "Item not available for item-level hold because no effective item type"
1402     );
1403
1404     # Weird use case to highlight issue
1405     $item_type = '0';
1406     Koha::ItemTypes->search( { itemtype => $item_type } )->delete;
1407     my $itemtype = $builder->build_object(
1408         {
1409             class => 'Koha::ItemTypes',
1410             value => { itemtype => $item_type, notloan => 0 }
1411         }
1412     );
1413     ok(
1414         C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ),
1415         "Item not available for item-level hold because no effective item type"
1416     );
1417
1418     $schema->storage->txn_rollback;
1419 };
1420
1421 subtest 'AddReserve() tests' => sub {
1422
1423     plan tests => 1;
1424
1425     $schema->storage->txn_begin;
1426
1427     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1428     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
1429     my $biblio  = $builder->build_sample_biblio;
1430
1431     my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1432     $mock->mock( 'enqueue', sub {
1433         my ( $self, $args ) = @_;
1434         is_deeply(
1435             $args->{biblio_ids},
1436             [ $biblio->id ],
1437             "AddReserve triggers a holds queue update for the related biblio"
1438         );
1439     } );
1440
1441     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1442
1443     AddReserve(
1444         {
1445             branchcode     => $library->branchcode,
1446             borrowernumber => $patron->id,
1447             biblionumber   => $biblio->id,
1448         }
1449     );
1450
1451     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1452
1453     AddReserve(
1454         {
1455             branchcode     => $library->branchcode,
1456             borrowernumber => $patron->id,
1457             biblionumber   => $biblio->id,
1458         }
1459     );
1460
1461     $schema->storage->txn_rollback;
1462 };
1463
1464 subtest 'AlterPriorty() tests' => sub {
1465
1466     plan tests => 2;
1467
1468     $schema->storage->txn_begin;
1469
1470     my $library = $builder->build_object({ class => 'Koha::Libraries' });
1471     my $patron_1  = $builder->build_object({ class => 'Koha::Patrons' });
1472     my $patron_2  = $builder->build_object({ class => 'Koha::Patrons' });
1473     my $patron_3  = $builder->build_object({ class => 'Koha::Patrons' });
1474     my $biblio  = $builder->build_sample_biblio;
1475
1476     my $reserve_id = AddReserve(
1477         {
1478             branchcode     => $library->branchcode,
1479             borrowernumber => $patron_1->id,
1480             biblionumber   => $biblio->id,
1481         }
1482     );
1483     AddReserve(
1484         {
1485             branchcode     => $library->branchcode,
1486             borrowernumber => $patron_2->id,
1487             biblionumber   => $biblio->id,
1488         }
1489     );
1490     AddReserve(
1491         {
1492             branchcode     => $library->branchcode,
1493             borrowernumber => $patron_3->id,
1494             biblionumber   => $biblio->id,
1495         }
1496     );
1497
1498     my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue');
1499     $mock->mock( 'enqueue', sub {
1500         my ( $self, $args ) = @_;
1501         is_deeply(
1502             $args->{biblio_ids},
1503             [ $biblio->id ],
1504             "AlterPriority triggers a holds queue update for the related biblio"
1505         );
1506     } );
1507
1508     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 );
1509
1510     AlterPriority( "bottom", $reserve_id, 1, 2, 1, 3 );
1511
1512     my $hold = Koha::Holds->find($reserve_id);
1513
1514     is($hold->priority,3,'Successfully altered priority to bottom');
1515
1516     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
1517
1518     AlterPriority( "bottom", $reserve_id, 1, 2, 1, 3 );
1519
1520     $schema->storage->txn_rollback;
1521 };