Bug 28320: Add DB connection check to the SIP SC status message
[koha.git] / t / db_dependent / Holds.t
1 #!/usr/bin/perl
2
3 use Modern::Perl;
4
5 use t::lib::Mocks;
6 use t::lib::TestBuilder;
7
8 use C4::Context;
9
10 use Test::More tests => 72;
11 use MARC::Record;
12
13 use C4::Biblio;
14 use C4::Calendar;
15 use C4::Items;
16 use C4::Reserves;
17 use C4::Circulation;
18
19 use Koha::Biblios;
20 use Koha::CirculationRules;
21 use Koha::Database;
22 use Koha::DateUtils qw( dt_from_string output_pref );
23 use Koha::Holds;
24 use Koha::Checkout;
25 use Koha::Item::Transfer::Limits;
26 use Koha::Items;
27 use Koha::Libraries;
28 use Koha::Library::Groups;
29 use Koha::Patrons;
30
31 BEGIN {
32     use FindBin;
33     use lib $FindBin::Bin;
34 }
35
36 my $schema  = Koha::Database->new->schema;
37 $schema->storage->txn_begin;
38
39 my $builder = t::lib::TestBuilder->new();
40 my $dbh     = C4::Context->dbh;
41
42 # Create two random branches
43 my $branch_1 = $builder->build({ source => 'Branch' })->{ branchcode };
44 my $branch_2 = $builder->build({ source => 'Branch' })->{ branchcode };
45
46 my $category = $builder->build({ source => 'Category' });
47
48 my $borrowers_count = 5;
49
50 $dbh->do('DELETE FROM itemtypes');
51 $dbh->do('DELETE FROM reserves');
52 $dbh->do('DELETE FROM circulation_rules');
53 my $insert_sth = $dbh->prepare('INSERT INTO itemtypes (itemtype) VALUES (?)');
54 $insert_sth->execute('CAN');
55 $insert_sth->execute('CANNOT');
56 $insert_sth->execute('DUMMY');
57 $insert_sth->execute('ONLY1');
58
59 # Setup Test------------------------
60 my $biblio = $builder->build_sample_biblio({ itemtype => 'DUMMY' });
61
62 # Create item instance for testing.
63 my $itemnumber = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber })->itemnumber;
64
65 # Create some borrowers
66 my @borrowernumbers;
67 foreach (1..$borrowers_count) {
68     my $borrowernumber = Koha::Patron->new({
69         firstname =>  'my firstname',
70         surname => 'my surname ' . $_,
71         categorycode => $category->{categorycode},
72         branchcode => $branch_1,
73     })->store->borrowernumber;
74     push @borrowernumbers, $borrowernumber;
75 }
76
77 # Create five item level holds
78 foreach my $borrowernumber ( @borrowernumbers ) {
79     AddReserve(
80         {
81             branchcode     => $branch_1,
82             borrowernumber => $borrowernumber,
83             biblionumber   => $biblio->biblionumber,
84             priority       => C4::Reserves::CalculatePriority( $biblio->biblionumber ),
85             itemnumber     => $itemnumber,
86         }
87     );
88 }
89
90 my $holds = $biblio->holds;
91 is( $holds->count, $borrowers_count, 'Test GetReserves()' );
92 is( $holds->next->priority, 1, "Reserve 1 has a priority of 1" );
93 is( $holds->next->priority, 2, "Reserve 2 has a priority of 2" );
94 is( $holds->next->priority, 3, "Reserve 3 has a priority of 3" );
95 is( $holds->next->priority, 4, "Reserve 4 has a priority of 4" );
96 is( $holds->next->priority, 5, "Reserve 5 has a priority of 5" );
97
98 my $item = Koha::Items->find( $itemnumber );
99 $holds = $item->current_holds;
100 my $first_hold = $holds->next;
101 my $reservedate = $first_hold->reservedate;
102 my $borrowernumber = $first_hold->borrowernumber;
103 my $branch_1code = $first_hold->branchcode;
104 my $reserve_id = $first_hold->reserve_id;
105 is( $reservedate, output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }), "holds_placed_today should return a valid reserve date");
106 is( $borrowernumber, $borrowernumbers[0], "holds_placed_today should return a valid borrowernumber");
107 is( $branch_1code, $branch_1, "holds_placed_today should return a valid branchcode");
108 ok($reserve_id, "Test holds_placed_today()");
109
110 my $hold = Koha::Holds->find( $reserve_id );
111 ok( $hold, "Koha::Holds found the hold" );
112 my $hold_biblio = $hold->biblio();
113 ok( $hold_biblio, "Got biblio using biblio() method" );
114 ok( $hold_biblio == $hold->biblio(), "biblio method returns stashed biblio" );
115 my $hold_item = $hold->item();
116 ok( $hold_item, "Got item using item() method" );
117 ok( $hold_item == $hold->item(), "item method returns stashed item" );
118 my $hold_branch = $hold->branch();
119 ok( $hold_branch, "Got branch using branch() method" );
120 ok( $hold_branch == $hold->branch(), "branch method returns stashed branch" );
121 my $hold_found = $hold->found();
122 $hold->set({ found => 'W'})->store();
123 is( Koha::Holds->waiting()->count(), 1, "Koha::Holds->waiting returns waiting holds" );
124 is( Koha::Holds->unfilled()->count(), 4, "Koha::Holds->unfilled returns unfilled holds" );
125
126 my $patron = Koha::Patrons->find( $borrowernumbers[0] );
127 $holds = $patron->holds;
128 is( $holds->next->borrowernumber, $borrowernumbers[0], "Test Koha::Patron->holds");
129
130
131 $holds = $item->current_holds;
132 $first_hold = $holds->next;
133 $borrowernumber = $first_hold->borrowernumber;
134 $branch_1code = $first_hold->branchcode;
135 $reserve_id = $first_hold->reserve_id;
136
137 ModReserve({
138     reserve_id    => $reserve_id,
139     rank          => '4',
140     branchcode    => $branch_1,
141     itemnumber    => $itemnumber,
142     suspend_until => output_pref( { dt => dt_from_string( "2013-01-01", "iso" ), dateonly => 1 } ),
143 });
144
145 $hold = Koha::Holds->find( $reserve_id );
146 ok( $hold->priority eq '4', "Test ModReserve, priority changed correctly" );
147 ok( $hold->suspend, "Test ModReserve, suspend hold" );
148 is( $hold->suspend_until, '2013-01-01 00:00:00', "Test ModReserve, suspend until date" );
149
150 ModReserve({ # call without reserve_id
151     rank          => '3',
152     biblionumber  => $biblio->biblionumber,
153     itemnumber    => $itemnumber,
154     borrowernumber => $borrowernumber,
155 });
156 $hold = Koha::Holds->find( $reserve_id );
157 ok( $hold->priority eq '3', "Test ModReserve, priority changed correctly" );
158
159 ToggleSuspend( $reserve_id );
160 $hold = Koha::Holds->find( $reserve_id );
161 ok( ! $hold->suspend, "Test ToggleSuspend(), no date" );
162
163 ToggleSuspend( $reserve_id, '2012-01-01' );
164 $hold = Koha::Holds->find( $reserve_id );
165 is( $hold->suspend_until, '2012-01-01 00:00:00', "Test ToggleSuspend(), with date" );
166
167 AutoUnsuspendReserves();
168 $hold = Koha::Holds->find( $reserve_id );
169 ok( ! $hold->suspend, "Test AutoUnsuspendReserves()" );
170
171 SuspendAll(
172     borrowernumber => $borrowernumber,
173     biblionumber   => $biblio->biblionumber,
174     suspend => 1,
175     suspend_until => '2012-01-01',
176 );
177 $hold = Koha::Holds->find( $reserve_id );
178 is( $hold->suspend, 1, "Test SuspendAll()" );
179 is( $hold->suspend_until, '2012-01-01 00:00:00', "Test SuspendAll(), with date" );
180
181 SuspendAll(
182     borrowernumber => $borrowernumber,
183     biblionumber   => $biblio->biblionumber,
184     suspend => 0,
185 );
186 $hold = Koha::Holds->find( $reserve_id );
187 is( $hold->suspend, 0, "Test resuming with SuspendAll()" );
188 is( $hold->suspend_until, undef, "Test resuming with SuspendAll(), should have no suspend until date" );
189
190 # Add a new hold for the borrower whose hold we canceled earlier, this time at the bib level
191     AddReserve(
192         {
193             branchcode     => $branch_1,
194             borrowernumber => $borrowernumbers[0],
195             biblionumber   => $biblio->biblionumber,
196         }
197     );
198
199 $patron = Koha::Patrons->find( $borrowernumber );
200 $holds = $patron->holds;
201 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $borrowernumbers[0] })->next->reserve_id;
202 ModReserveMinusPriority( $itemnumber, $reserveid );
203 $holds = $patron->holds;
204 is( $holds->search({ itemnumber => $itemnumber })->count, 1, "Test ModReserveMinusPriority()" );
205
206 $holds = $biblio->holds;
207 $hold = $holds->next;
208 AlterPriority( 'top', $hold->reserve_id, undef, 2, 1, 6 );
209 $hold = Koha::Holds->find( $reserveid );
210 is( $hold->priority, '1', "Test AlterPriority(), move to top" );
211
212 AlterPriority( 'down', $hold->reserve_id, undef, 2, 1, 6 );
213 $hold = Koha::Holds->find( $reserveid );
214 is( $hold->priority, '2', "Test AlterPriority(), move down" );
215
216 AlterPriority( 'up', $hold->reserve_id, 1, 3, 1, 6 );
217 $hold = Koha::Holds->find( $reserveid );
218 is( $hold->priority, '1', "Test AlterPriority(), move up" );
219
220 AlterPriority( 'bottom', $hold->reserve_id, undef, 2, 1, 6 );
221 $hold = Koha::Holds->find( $reserveid );
222 is( $hold->priority, '6', "Test AlterPriority(), move to bottom" );
223
224 # Regression test for bug 2394
225 #
226 # If IndependentBranches is ON and canreservefromotherbranches is OFF,
227 # a patron is not permittedo to request an item whose homebranch (i.e.,
228 # owner of the item) is different from the patron's own library.
229 # However, if canreservefromotherbranches is turned ON, the patron can
230 # create such hold requests.
231 #
232 # Note that canreservefromotherbranches has no effect if
233 # IndependentBranches is OFF.
234
235 my $foreign_biblio = $builder->build_sample_biblio({ itemtype => 'DUMMY' });
236 my $foreign_itemnumber = $builder->build_sample_item({ library => $branch_2, biblionumber => $foreign_biblio->biblionumber })->itemnumber;
237 Koha::CirculationRules->set_rules(
238     {
239         categorycode => undef,
240         branchcode   => undef,
241         itemtype     => undef,
242         rules        => {
243             reservesallowed  => 25,
244             holds_per_record => 99,
245         }
246     }
247 );
248 Koha::CirculationRules->set_rules(
249     {
250         categorycode => undef,
251         branchcode   => undef,
252         itemtype     => 'CANNOT',
253         rules        => {
254             reservesallowed  => 0,
255             holds_per_record => 99,
256         }
257     }
258 );
259
260 # make sure some basic sysprefs are set
261 t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary');
262 t::lib::Mocks::mock_preference('item-level_itypes', 1);
263
264 # if IndependentBranches is OFF, a $branch_1 patron can reserve an $branch_2 item
265 t::lib::Mocks::mock_preference('IndependentBranches', 0);
266
267 is(
268     CanItemBeReserved($borrowernumbers[0], $foreign_itemnumber)->{status}, 'OK',
269     '$branch_1 patron allowed to reserve $branch_2 item with IndependentBranches OFF (bug 2394)'
270 );
271
272 # if IndependentBranches is OFF, a $branch_1 patron cannot reserve an $branch_2 item
273 t::lib::Mocks::mock_preference('IndependentBranches', 1);
274 t::lib::Mocks::mock_preference('canreservefromotherbranches', 0);
275 ok(
276     CanItemBeReserved($borrowernumbers[0], $foreign_itemnumber)->{status} eq 'cannotReserveFromOtherBranches',
277     '$branch_1 patron NOT allowed to reserve $branch_2 item with IndependentBranches ON ... (bug 2394)'
278 );
279
280 # ... unless canreservefromotherbranches is ON
281 t::lib::Mocks::mock_preference('canreservefromotherbranches', 1);
282 ok(
283     CanItemBeReserved($borrowernumbers[0], $foreign_itemnumber)->{status} eq 'OK',
284     '... unless canreservefromotherbranches is ON (bug 2394)'
285 );
286
287 {
288     # Regression test for bug 11336 # Test if ModReserve correctly recalculate the priorities
289     $biblio = $builder->build_sample_biblio({ itemtype => 'DUMMY' });
290     $itemnumber = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber })->itemnumber;
291     my $reserveid1 = AddReserve(
292         {
293             branchcode     => $branch_1,
294             borrowernumber => $borrowernumbers[0],
295             biblionumber   => $biblio->biblionumber,
296             priority       => 1
297         }
298     );
299
300     $itemnumber = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber })->itemnumber;
301     my $reserveid2 = AddReserve(
302         {
303             branchcode     => $branch_1,
304             borrowernumber => $borrowernumbers[1],
305             biblionumber   => $biblio->biblionumber,
306             priority       => 2
307         }
308     );
309
310     $itemnumber = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber })->itemnumber;
311     my $reserveid3 = AddReserve(
312         {
313             branchcode     => $branch_1,
314             borrowernumber => $borrowernumbers[2],
315             biblionumber   => $biblio->biblionumber,
316             priority       => 3
317         }
318     );
319
320     my $hhh = Koha::Holds->search({ biblionumber => $biblio->biblionumber });
321     my $hold3 = Koha::Holds->find( $reserveid3 );
322     is( $hold3->priority, 3, "The 3rd hold should have a priority set to 3" );
323     ModReserve({ reserve_id => $reserveid1, rank => 'del' });
324     ModReserve({ reserve_id => $reserveid2, rank => 'del' });
325     is( $hold3->discard_changes->priority, 1, "After ModReserve, the 3rd reserve becomes the first on the waiting list" );
326 }
327
328 Koha::Items->find($itemnumber)->damaged(1)->store; # FIXME The $itemnumber is a bit confusing here
329 t::lib::Mocks::mock_preference( 'AllowHoldsOnDamagedItems', 1 );
330 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber)->{status}, 'OK', "Patron can reserve damaged item with AllowHoldsOnDamagedItems enabled" );
331 ok( defined( ( CheckReserves($itemnumber) )[1] ), "Hold can be trapped for damaged item with AllowHoldsOnDamagedItems enabled" );
332
333 $hold = Koha::Hold->new(
334     {
335         borrowernumber => $borrowernumbers[0],
336         itemnumber     => $itemnumber,
337         biblionumber   => $biblio->biblionumber,
338     }
339 )->store();
340 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber )->{status},
341     'itemAlreadyOnHold',
342     "Patron cannot place a second item level hold for a given item" );
343 $hold->delete();
344
345 t::lib::Mocks::mock_preference( 'AllowHoldsOnDamagedItems', 0 );
346 ok( CanItemBeReserved( $borrowernumbers[0], $itemnumber)->{status} eq 'damaged', "Patron cannot reserve damaged item with AllowHoldsOnDamagedItems disabled" );
347 ok( !defined( ( CheckReserves($itemnumber) )[1] ), "Hold cannot be trapped for damaged item with AllowHoldsOnDamagedItems disabled" );
348
349 # Items that are not for loan, but holdable should not be trapped until they are available for loan
350 t::lib::Mocks::mock_preference( 'TrapHoldsOnOrder', 0 );
351 Koha::Items->find($itemnumber)->damaged(0)->notforloan(-1)->store;
352 Koha::Holds->search({ biblionumber => $biblio->id })->delete();
353 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber)->{status}, 'OK', "Patron can place hold on item that is not for loan but holdable ( notforloan < 0 )" );
354 $hold = Koha::Hold->new(
355     {
356         borrowernumber => $borrowernumbers[0],
357         itemnumber     => $itemnumber,
358         biblionumber   => $biblio->biblionumber,
359         found          => undef,
360         priority       => 1,
361         reservedate    => dt_from_string,
362         branchcode     => $branch_1,
363     }
364 )->store();
365 ok( !defined( ( CheckReserves($itemnumber) )[1] ), "Hold cannot be trapped for item that is not for loan but holdable ( notforloan < 0 )" );
366 t::lib::Mocks::mock_preference( 'TrapHoldsOnOrder', 1 );
367 ok( defined( ( CheckReserves($itemnumber) )[1] ), "Hold is trapped for item that is not for loan but holdable ( notforloan < 0 )" );
368 t::lib::Mocks::mock_preference( 'SkipHoldTrapOnNotForLoanValue', '-1' );
369 ok( !defined( ( CheckReserves($itemnumber) )[1] ), "Hold cannot be trapped for item with notforloan value matching SkipHoldTrapOnNotForLoanValue" );
370 t::lib::Mocks::mock_preference( 'SkipHoldTrapOnNotForLoanValue', '-1|1' );
371 ok( !defined( ( CheckReserves($itemnumber) )[1] ), "Hold cannot be trapped for item with notforloan value matching SkipHoldTrapOnNotForLoanValue" );
372 is(
373     CanItemBeReserved( $borrowernumbers[0], $itemnumber)->{status}, 'itemAlreadyOnHold',
374     "cannot request item that you have already reservedd"
375 );
376 is(
377     CanItemBeReserved( $borrowernumbers[0], $item->itemnumber, undef, { ignore_hold_counts => 1 })->{status}, 'OK',
378     "can request item if we are not checking holds counts, but only if policy allows or forbids it"
379 );
380 $hold->delete();
381
382 # Regression test for bug 9532
383 $biblio = $builder->build_sample_biblio({ itemtype => 'CANNOT' });
384 $item = $builder->build_sample_item({ library => $branch_1, itype => 'CANNOT', biblionumber => $biblio->biblionumber});
385 AddReserve(
386     {
387         branchcode     => $branch_1,
388         borrowernumber => $borrowernumbers[0],
389         biblionumber   => $biblio->biblionumber,
390         priority       => 1,
391     }
392 );
393 is(
394     CanItemBeReserved( $borrowernumbers[0], $item->itemnumber)->{status}, 'tooManyReserves',
395     "cannot request item if policy that matches on item-level item type forbids it"
396 );
397 is(
398     CanItemBeReserved( $borrowernumbers[0], $item->itemnumber, undef, { ignore_hold_counts => 1 })->{status}, 'tooManyReserves',
399     "cannot request item if policy that matches on item-level item type forbids it even if ignoring counts"
400 );
401
402 $item->itype('CAN')->store;
403 ok(
404     CanItemBeReserved( $borrowernumbers[0], $item->itemnumber)->{status} eq 'OK',
405     "can request item if policy that matches on item type allows it"
406 );
407
408 t::lib::Mocks::mock_preference('item-level_itypes', 0);
409 $item->itype(undef)->store;
410 ok(
411     CanItemBeReserved( $borrowernumbers[0], $item->itemnumber)->{status} eq 'tooManyReserves',
412     "cannot request item if policy that matches on bib-level item type forbids it (bug 9532)"
413 );
414
415
416 # Test branch item rules
417
418 $dbh->do('DELETE FROM circulation_rules');
419 Koha::CirculationRules->set_rules(
420     {
421         categorycode => undef,
422         branchcode   => undef,
423         itemtype     => undef,
424         rules        => {
425             reservesallowed  => 25,
426             holds_per_record => 99,
427         }
428     }
429 );
430 Koha::CirculationRules->set_rules(
431     {
432         branchcode => $branch_1,
433         itemtype   => 'CANNOT',
434         rules => {
435             holdallowed => 0,
436             returnbranch => 'homebranch',
437         }
438     }
439 );
440 Koha::CirculationRules->set_rules(
441     {
442         branchcode => $branch_1,
443         itemtype   => 'CAN',
444         rules => {
445             holdallowed => 1,
446             returnbranch => 'homebranch',
447         }
448     }
449 );
450 $biblio = $builder->build_sample_biblio({ itemtype => 'CANNOT' });
451 $itemnumber = $builder->build_sample_item({ library => $branch_1, itype => 'CANNOT', biblionumber => $biblio->biblionumber})->itemnumber;
452 is(CanItemBeReserved($borrowernumbers[0], $itemnumber)->{status}, 'notReservable',
453     "CanItemBeReserved should return 'notReservable'");
454
455 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
456 $itemnumber = $builder->build_sample_item({ library => $branch_2, itype => 'CAN', biblionumber => $biblio->biblionumber})->itemnumber;
457 is(CanItemBeReserved($borrowernumbers[0], $itemnumber)->{status},
458     'cannotReserveFromOtherBranches',
459     "CanItemBeReserved should use PatronLibrary rule when ReservesControlBranch set to 'PatronLibrary'");
460 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
461 is(CanItemBeReserved($borrowernumbers[0], $itemnumber)->{status},
462     'OK',
463     "CanItemBeReserved should use item home library rule when ReservesControlBranch set to 'ItemsHomeLibrary'");
464
465 $itemnumber = $builder->build_sample_item({ library => $branch_1, itype => 'CAN', biblionumber => $biblio->biblionumber})->itemnumber;
466 is(CanItemBeReserved($borrowernumbers[0], $itemnumber)->{status}, 'OK',
467     "CanItemBeReserved should return 'OK'");
468
469 # Bug 12632
470 t::lib::Mocks::mock_preference( 'item-level_itypes',     1 );
471 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
472
473 $dbh->do('DELETE FROM reserves');
474 $dbh->do('DELETE FROM issues');
475 $dbh->do('DELETE FROM items');
476 $dbh->do('DELETE FROM biblio');
477
478 $biblio = $builder->build_sample_biblio({ itemtype => 'ONLY1' });
479 $itemnumber = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber})->itemnumber;
480
481 Koha::CirculationRules->set_rules(
482     {
483         categorycode => undef,
484         branchcode   => undef,
485         itemtype     => 'ONLY1',
486         rules        => {
487             reservesallowed  => 1,
488             holds_per_record => 99,
489         }
490     }
491 );
492 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber )->{status},
493     'OK', 'Patron can reserve item with hold limit of 1, no holds placed' );
494
495 my $res_id = AddReserve(
496     {
497         branchcode     => $branch_1,
498         borrowernumber => $borrowernumbers[0],
499         biblionumber   => $biblio->biblionumber,
500         priority       => 1,
501     }
502 );
503
504 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber )->{status},
505     'tooManyReserves', 'Patron cannot reserve item with hold limit of 1, 1 bib level hold placed' );
506 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber, undef, { ignore_hold_counts => 1 } )->{status},
507     'OK', 'Patron can reserve item if checking policy but not counts' );
508
509     #results should be the same for both ReservesControlBranch settings
510 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
511 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber )->{status},
512     'tooManyReserves', 'Patron cannot reserve item with hold limit of 1, 1 bib level hold placed' );
513 #reset for further tests
514 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
515
516 subtest 'Test max_holds per library/patron category' => sub {
517     plan tests => 6;
518
519     $dbh->do('DELETE FROM reserves');
520
521     $biblio = $builder->build_sample_biblio;
522     $itemnumber = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber})->itemnumber;
523     Koha::CirculationRules->set_rules(
524         {
525             categorycode => undef,
526             branchcode   => undef,
527             itemtype     => $biblio->itemtype,
528             rules        => {
529                 reservesallowed  => 99,
530                 holds_per_record => 99,
531             }
532         }
533     );
534
535     for ( 1 .. 3 ) {
536         AddReserve(
537             {
538                 branchcode     => $branch_1,
539                 borrowernumber => $borrowernumbers[0],
540                 biblionumber   => $biblio->biblionumber,
541                 priority       => 1,
542             }
543         );
544     }
545
546     my $count =
547       Koha::Holds->search( { borrowernumber => $borrowernumbers[0] } )->count();
548     is( $count, 3, 'Patron now has 3 holds' );
549
550     my $ret = CanItemBeReserved( $borrowernumbers[0], $itemnumber );
551     is( $ret->{status}, 'OK', 'Patron can place hold with no borrower circ rules' );
552
553     my $rule_all = Koha::CirculationRules->set_rule(
554         {
555             categorycode => $category->{categorycode},
556             branchcode   => undef,
557             rule_name    => 'max_holds',
558             rule_value   => 3,
559         }
560     );
561
562     my $rule_branch = Koha::CirculationRules->set_rule(
563         {
564             branchcode   => $branch_1,
565             categorycode => $category->{categorycode},
566             rule_name    => 'max_holds',
567             rule_value   => 5,
568         }
569     );
570
571     $ret = CanItemBeReserved( $borrowernumbers[0], $itemnumber );
572     is( $ret->{status}, 'OK', 'Patron can place hold with branch/category rule of 5, category rule of 3' );
573
574     $rule_branch->delete();
575
576     $ret = CanItemBeReserved( $borrowernumbers[0], $itemnumber );
577     is( $ret->{status}, 'tooManyReserves', 'Patron cannot place hold with only a category rule of 3' );
578
579     $rule_all->delete();
580     $rule_branch->rule_value(3);
581     $rule_branch->store();
582
583     $ret = CanItemBeReserved( $borrowernumbers[0], $itemnumber );
584     is( $ret->{status}, 'tooManyReserves', 'Patron cannot place hold with only a branch/category rule of 3' );
585
586     $rule_branch->rule_value(5);
587     $rule_branch->update();
588     $rule_branch->rule_value(5);
589     $rule_branch->store();
590
591     $ret = CanItemBeReserved( $borrowernumbers[0], $itemnumber );
592     is( $ret->{status}, 'OK', 'Patron can place hold with branch/category rule of 5, category rule of 5' );
593 };
594
595 subtest 'Pickup location availability tests' => sub {
596     plan tests => 4;
597
598     $biblio = $builder->build_sample_biblio({ itemtype => 'ONLY1' });
599     $itemnumber = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber})->itemnumber;
600     #Add a default rule to allow some holds
601
602     Koha::CirculationRules->set_rules(
603         {
604             branchcode   => undef,
605             categorycode => undef,
606             itemtype     => undef,
607             rules        => {
608                 reservesallowed  => 25,
609                 holds_per_record => 99,
610             }
611         }
612     );
613     my $item = Koha::Items->find($itemnumber);
614     my $branch_to = $builder->build({ source => 'Branch' })->{ branchcode };
615     my $library = Koha::Libraries->find($branch_to);
616     $library->pickup_location('1')->store;
617     my $patron = $builder->build({ source => 'Borrower' })->{ borrowernumber };
618
619     t::lib::Mocks::mock_preference('UseBranchTransferLimits', 1);
620     t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'itemtype');
621
622     $library->pickup_location('1')->store;
623     is(CanItemBeReserved($patron, $item->itemnumber, $branch_to)->{status},
624        'OK', 'Library is a pickup location');
625
626     my $limit = Koha::Item::Transfer::Limit->new({
627         fromBranch => $item->holdingbranch,
628         toBranch => $branch_to,
629         itemtype => $item->effective_itemtype,
630     })->store;
631     is(CanItemBeReserved($patron, $item->itemnumber, $branch_to)->{status},
632        'cannotBeTransferred', 'Item cannot be transferred');
633     $limit->delete;
634
635     $library->pickup_location('0')->store;
636     is(CanItemBeReserved($patron, $item->itemnumber, $branch_to)->{status},
637        'libraryNotPickupLocation', 'Library is not a pickup location');
638     is(CanItemBeReserved($patron, $item->itemnumber, 'nonexistent')->{status},
639        'libraryNotFound', 'Cannot set unknown library as pickup location');
640 };
641
642 $schema->storage->txn_rollback;
643
644 subtest 'CanItemBeReserved / holds_per_day tests' => sub {
645
646     plan tests => 10;
647
648     $schema->storage->txn_begin;
649
650     my $itemtype = $builder->build_object( { class => 'Koha::ItemTypes' } );
651     my $library  = $builder->build_object( { class => 'Koha::Libraries' } );
652     my $patron   = $builder->build_object( { class => 'Koha::Patrons' } );
653
654     # Create 3 biblios with items
655     my $biblio_1 = $builder->build_sample_biblio({ itemtype => $itemtype->itemtype });
656     my $itemnumber_1 = $builder->build_sample_item({ library => $library->branchcode, biblionumber => $biblio_1->biblionumber})->itemnumber;
657     my $biblio_2 = $builder->build_sample_biblio({ itemtype => $itemtype->itemtype });
658     my $itemnumber_2 = $builder->build_sample_item({ library => $library->branchcode, biblionumber => $biblio_2->biblionumber})->itemnumber;
659     my $biblio_3 = $builder->build_sample_biblio({ itemtype => $itemtype->itemtype });
660     my $itemnumber_3 = $builder->build_sample_item({ library => $library->branchcode, biblionumber => $biblio_3->biblionumber})->itemnumber;
661
662     Koha::CirculationRules->set_rules(
663         {
664             categorycode => '*',
665             branchcode   => '*',
666             itemtype     => $itemtype->itemtype,
667             rules        => {
668                 reservesallowed  => 1,
669                 holds_per_record => 99,
670                 holds_per_day    => 2
671             }
672         }
673     );
674
675     is_deeply(
676         CanItemBeReserved( $patron->borrowernumber, $itemnumber_1 ),
677         { status => 'OK' },
678         'Patron can reserve item with hold limit of 1, no holds placed'
679     );
680
681     AddReserve(
682         {
683             branchcode     => $library->branchcode,
684             borrowernumber => $patron->borrowernumber,
685             biblionumber   => $biblio_1->biblionumber,
686             priority       => 1,
687         }
688     );
689
690     is_deeply(
691         CanItemBeReserved( $patron->borrowernumber, $itemnumber_1 ),
692         { status => 'tooManyReserves', limit => 1 },
693         'Patron cannot reserve item with hold limit of 1, 1 bib level hold placed'
694     );
695
696     # Raise reservesallowed to avoid tooManyReserves from it
697     Koha::CirculationRules->set_rule(
698         {
699
700             categorycode => '*',
701             branchcode   => '*',
702             itemtype     => $itemtype->itemtype,
703             rule_name  => 'reservesallowed',
704             rule_value => 3,
705         }
706     );
707
708     is_deeply(
709         CanItemBeReserved( $patron->borrowernumber, $itemnumber_2 ),
710         { status => 'OK' },
711         'Patron can reserve item with 2 reserves daily cap'
712     );
713
714     # Add a second reserve
715     my $res_id = AddReserve(
716         {
717             branchcode     => $library->branchcode,
718             borrowernumber => $patron->borrowernumber,
719             biblionumber   => $biblio_2->biblionumber,
720             priority       => 1,
721         }
722     );
723     is_deeply(
724         CanItemBeReserved( $patron->borrowernumber, $itemnumber_2 ),
725         { status => 'tooManyReservesToday', limit => 2 },
726         'Patron cannot a third item with 2 reserves daily cap'
727     );
728
729     # Update last hold so reservedate is in the past, so 2 holds, but different day
730     $hold = Koha::Holds->find($res_id);
731     my $yesterday = dt_from_string() - DateTime::Duration->new( days => 1 );
732     $hold->reservedate($yesterday)->store;
733
734     is_deeply(
735         CanItemBeReserved( $patron->borrowernumber, $itemnumber_2 ),
736         { status => 'OK' },
737         'Patron can reserve item with 2 bib level hold placed on different days, 2 reserves daily cap'
738     );
739
740     # Set holds_per_day to 0
741     Koha::CirculationRules->set_rule(
742         {
743
744             categorycode => '*',
745             branchcode   => '*',
746             itemtype     => $itemtype->itemtype,
747             rule_name  => 'holds_per_day',
748             rule_value => 0,
749         }
750     );
751
752
753     # Delete existing holds
754     Koha::Holds->search->delete;
755     is_deeply(
756         CanItemBeReserved( $patron->borrowernumber, $itemnumber_2 ),
757         { status => 'tooManyReservesToday', limit => 0 },
758         'Patron cannot reserve if holds_per_day is 0 (i.e. 0 is 0)'
759     );
760
761     Koha::CirculationRules->set_rule(
762         {
763
764             categorycode => '*',
765             branchcode   => '*',
766             itemtype     => $itemtype->itemtype,
767             rule_name  => 'holds_per_day',
768             rule_value => undef,
769         }
770     );
771
772     Koha::Holds->search->delete;
773     is_deeply(
774         CanItemBeReserved( $patron->borrowernumber, $itemnumber_2 ),
775         { status => 'OK' },
776         'Patron can reserve if holds_per_day is undef (i.e. undef is unlimited daily cap)'
777     );
778     AddReserve(
779         {
780             branchcode     => $library->branchcode,
781             borrowernumber => $patron->borrowernumber,
782             biblionumber   => $biblio_1->biblionumber,
783             priority       => 1,
784         }
785     );
786     AddReserve(
787         {
788             branchcode     => $library->branchcode,
789             borrowernumber => $patron->borrowernumber,
790             biblionumber   => $biblio_2->biblionumber,
791             priority       => 1,
792         }
793     );
794
795     is_deeply(
796         CanItemBeReserved( $patron->borrowernumber, $itemnumber_3 ),
797         { status => 'OK' },
798         'Patron can reserve if holds_per_day is undef (i.e. undef is unlimited daily cap)'
799     );
800     AddReserve(
801         {
802             branchcode     => $library->branchcode,
803             borrowernumber => $patron->borrowernumber,
804             biblionumber   => $biblio_3->biblionumber,
805             priority       => 1,
806         }
807     );
808     is_deeply(
809         CanItemBeReserved( $patron->borrowernumber, $itemnumber_3 ),
810         { status => 'tooManyReserves', limit => 3 },
811         'Unlimited daily holds, but reached reservesallowed'
812     );
813     #results should be the same for both ReservesControlBranch settings
814     t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary');
815     is_deeply(
816         CanItemBeReserved( $patron->borrowernumber, $itemnumber_3 ),
817         { status => 'tooManyReserves', limit => 3 },
818         'Unlimited daily holds, but reached reservesallowed'
819     );
820
821     $schema->storage->txn_rollback;
822 };
823
824 subtest 'CanItemBeReserved / branch_not_in_hold_group' => sub {
825     plan tests => 9;
826
827     $schema->storage->txn_begin;
828
829     Koha::CirculationRules->set_rule(
830         {
831             branchcode   => undef,
832             categorycode => undef,
833             itemtype     => undef,
834             rule_name    => 'reservesallowed',
835             rule_value   => 25,
836         }
837     );
838
839     # Create item types
840     my $itemtype1 = $builder->build_object( { class => 'Koha::ItemTypes' } );
841     my $itemtype2 = $builder->build_object( { class => 'Koha::ItemTypes' } );
842
843     # Create libraries
844     my $library1  = $builder->build_object( { class => 'Koha::Libraries' } );
845     my $library2  = $builder->build_object( { class => 'Koha::Libraries' } );
846     my $library3  = $builder->build_object( { class => 'Koha::Libraries' } );
847
848     # Create library groups hierarchy
849     my $rootgroup  = $builder->build_object( { class => 'Koha::Library::Groups', value => {ft_local_hold_group => 1} } );
850     my $group1  = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library1->branchcode}} );
851     my $group2  = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library2->branchcode} } );
852
853     # Create 2 patrons
854     my $patron1   = $builder->build_object( { class => 'Koha::Patrons', value => {branchcode => $library1->branchcode} } );
855     my $patron3   = $builder->build_object( { class => 'Koha::Patrons', value => {branchcode => $library3->branchcode} } );
856
857     # Create 3 biblios with items
858     my $biblio_1 = $builder->build_sample_biblio({ itemtype => $itemtype1->itemtype });
859     my $item_1   = $builder->build_sample_item(
860         {
861             biblionumber => $biblio_1->biblionumber,
862             library      => $library1->branchcode
863         }
864     );
865     my $biblio_2 = $builder->build_sample_biblio({ itemtype => $itemtype2->itemtype });
866     my $item_2   = $builder->build_sample_item(
867         {
868             biblionumber => $biblio_2->biblionumber,
869             library      => $library2->branchcode
870         }
871     );
872     my $itemnumber_2 = $item_2->itemnumber;
873     my $biblio_3 = $builder->build_sample_biblio({ itemtype => $itemtype1->itemtype });
874     my $item_3   = $builder->build_sample_item(
875         {
876             biblionumber => $biblio_3->biblionumber,
877             library      => $library1->branchcode
878         }
879     );
880
881     # Test 1: Patron 3 can place hold
882     is_deeply(
883         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2 ),
884         { status => 'OK' },
885         'Patron can place hold if no circ_rules where defined'
886     );
887
888     # Insert default circ rule of holds allowed only from local hold group for all libraries
889     Koha::CirculationRules->set_rules(
890         {
891             branchcode => undef,
892             itemtype   => undef,
893             rules => {
894                 holdallowed => 3,
895                 hold_fulfillment_policy => 'any',
896                 returnbranch => 'any'
897             }
898         }
899     );
900
901     # Test 2: Patron 1 can place hold
902     is_deeply(
903         CanItemBeReserved( $patron1->borrowernumber, $itemnumber_2 ),
904         { status => 'OK' },
905         'Patron can place hold because patron\'s home library is part of hold group'
906     );
907
908     # Test 3: Patron 3 cannot place hold
909     is_deeply(
910         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2 ),
911         { status => 'branchNotInHoldGroup' },
912         'Patron cannot place hold because patron\'s home library is not part of hold group'
913     );
914
915     # Insert default circ rule to "any" for library 2
916     Koha::CirculationRules->set_rules(
917         {
918             branchcode => $library2->branchcode,
919             itemtype   => undef,
920             rules => {
921                 holdallowed => 2,
922                 hold_fulfillment_policy => 'any',
923                 returnbranch => 'any'
924             }
925         }
926     );
927
928     # Test 4: Patron 3 can place hold
929     is_deeply(
930         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2 ),
931         { status => 'OK' },
932         'Patron can place hold if holdallowed is set to "any" for library 2'
933     );
934
935     # Update default circ rule to "hold group" for library 2
936     Koha::CirculationRules->set_rules(
937         {
938             branchcode => $library2->branchcode,
939             itemtype   => undef,
940             rules => {
941                 holdallowed => 3,
942                 hold_fulfillment_policy => 'any',
943                 returnbranch => 'any'
944             }
945         }
946     );
947
948     # Test 5: Patron 3 cannot place hold
949     is_deeply(
950         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2 ),
951         { status => 'branchNotInHoldGroup' },
952         'Patron cannot place hold if holdallowed is set to "hold group" for library 2'
953     );
954
955     # Insert default item rule to "any" for itemtype 2
956     Koha::CirculationRules->set_rules(
957         {
958             branchcode => $library2->branchcode,
959             itemtype   => $itemtype2->itemtype,
960             rules => {
961                 holdallowed => 2,
962                 hold_fulfillment_policy => 'any',
963                 returnbranch => 'any'
964             }
965         }
966     );
967
968     # Test 6: Patron 3 can place hold
969     is_deeply(
970         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2 ),
971         { status => 'OK' },
972         'Patron can place hold if holdallowed is set to "any" for itemtype 2'
973     );
974
975     # Update default item rule to "hold group" for itemtype 2
976     Koha::CirculationRules->set_rules(
977         {
978             branchcode => $library2->branchcode,
979             itemtype   => $itemtype2->itemtype,
980             rules => {
981                 holdallowed => 3,
982                 hold_fulfillment_policy => 'any',
983                 returnbranch => 'any'
984             }
985         }
986     );
987
988     # Test 7: Patron 3 cannot place hold
989     is_deeply(
990         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2 ),
991         { status => 'branchNotInHoldGroup' },
992         'Patron cannot place hold if holdallowed is set to "hold group" for itemtype 2'
993     );
994
995     # Insert branch item rule to "any" for itemtype 2 and library 2
996     Koha::CirculationRules->set_rules(
997         {
998             branchcode => $library2->branchcode,
999             itemtype   => $itemtype2->itemtype,
1000             rules => {
1001                 holdallowed => 2,
1002                 hold_fulfillment_policy => 'any',
1003                 returnbranch => 'any'
1004             }
1005         }
1006     );
1007
1008     # Test 8: Patron 3 can place hold
1009     is_deeply(
1010         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2 ),
1011         { status => 'OK' },
1012         'Patron can place hold if holdallowed is set to "any" for itemtype 2 and library 2'
1013     );
1014
1015     # Update branch item rule to "hold group" for itemtype 2 and library 2
1016     Koha::CirculationRules->set_rules(
1017         {
1018             branchcode => $library2->branchcode,
1019             itemtype   => $itemtype2->itemtype,
1020             rules => {
1021                 holdallowed => 3,
1022                 hold_fulfillment_policy => 'any',
1023                 returnbranch => 'any'
1024             }
1025         }
1026     );
1027
1028     # Test 9: Patron 3 cannot place hold
1029     is_deeply(
1030         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2 ),
1031         { status => 'branchNotInHoldGroup' },
1032         'Patron cannot place hold if holdallowed is set to "hold group" for itemtype 2 and library 2'
1033     );
1034
1035     $schema->storage->txn_rollback;
1036
1037 };
1038
1039 subtest 'CanItemBeReserved / pickup_not_in_hold_group' => sub {
1040     plan tests => 9;
1041
1042     $schema->storage->txn_begin;
1043     Koha::CirculationRules->set_rule(
1044         {
1045             branchcode   => undef,
1046             categorycode => undef,
1047             itemtype     => undef,
1048             rule_name    => 'reservesallowed',
1049             rule_value   => 25,
1050         }
1051     );
1052
1053     # Create item types
1054     my $itemtype1 = $builder->build_object( { class => 'Koha::ItemTypes' } );
1055     my $itemtype2 = $builder->build_object( { class => 'Koha::ItemTypes' } );
1056
1057     # Create libraries
1058     my $library1  = $builder->build_object( { class => 'Koha::Libraries', value => {pickup_location => 1} } );
1059     my $library2  = $builder->build_object( { class => 'Koha::Libraries', value => {pickup_location => 1} } );
1060     my $library3  = $builder->build_object( { class => 'Koha::Libraries', value => {pickup_location => 1} } );
1061
1062     # Create library groups hierarchy
1063     my $rootgroup  = $builder->build_object( { class => 'Koha::Library::Groups', value => {ft_local_hold_group => 1} } );
1064     my $group1  = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library1->branchcode}} );
1065     my $group2  = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library2->branchcode} } );
1066
1067     # Create 2 patrons
1068     my $patron1   = $builder->build_object( { class => 'Koha::Patrons', value => {branchcode => $library1->branchcode} } );
1069     my $patron3   = $builder->build_object( { class => 'Koha::Patrons', value => {branchcode => $library3->branchcode} } );
1070
1071     # Create 3 biblios with items
1072     my $biblio_1 = $builder->build_sample_biblio({ itemtype => $itemtype1->itemtype });
1073     my $item_1   = $builder->build_sample_item(
1074         {
1075             biblionumber => $biblio_1->biblionumber,
1076             library      => $library1->branchcode
1077         }
1078     );
1079     my $biblio_2 = $builder->build_sample_biblio({ itemtype => $itemtype2->itemtype });
1080     my $item_2   = $builder->build_sample_item(
1081         {
1082             biblionumber => $biblio_2->biblionumber,
1083             library      => $library2->branchcode
1084         }
1085     );
1086     my $itemnumber_2 = $item_2->itemnumber;
1087     my $biblio_3 = $builder->build_sample_biblio({ itemtype => $itemtype1->itemtype });
1088     my $item_3   = $builder->build_sample_item(
1089         {
1090             biblionumber => $biblio_3->biblionumber,
1091             library      => $library1->branchcode
1092         }
1093     );
1094
1095     # Test 1: Patron 3 can place hold
1096     is_deeply(
1097         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2, $library3->branchcode ),
1098         { status => 'OK' },
1099         'Patron can place hold if no circ_rules where defined'
1100     );
1101
1102     # Insert default circ rule of holds allowed only from local hold group for all libraries
1103     Koha::CirculationRules->set_rules(
1104         {
1105             branchcode => undef,
1106             itemtype   => undef,
1107             rules => {
1108                 holdallowed => 2,
1109                 hold_fulfillment_policy => 'holdgroup',
1110                 returnbranch => 'any'
1111             }
1112         }
1113     );
1114
1115     # Test 2: Patron 1 can place hold
1116     is_deeply(
1117         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2, $library1->branchcode ),
1118         { status => 'OK' },
1119         'Patron can place hold because pickup location is part of hold group'
1120     );
1121
1122     # Test 3: Patron 3 cannot place hold
1123     is_deeply(
1124         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2, $library3->branchcode ),
1125         { status => 'pickupNotInHoldGroup' },
1126         'Patron cannot place hold because pickup location is not part of hold group'
1127     );
1128
1129     # Insert default circ rule to "any" for library 2
1130     Koha::CirculationRules->set_rules(
1131         {
1132             branchcode => $library2->branchcode,
1133             itemtype   => undef,
1134             rules => {
1135                 holdallowed => 2,
1136                 hold_fulfillment_policy => 'any',
1137                 returnbranch => 'any'
1138             }
1139         }
1140     );
1141
1142     # Test 4: Patron 3 can place hold
1143     is_deeply(
1144         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2, $library3->branchcode ),
1145         { status => 'OK' },
1146         'Patron can place hold if default_branch_circ_rules is set to "any" for library 2'
1147     );
1148
1149     # Update default circ rule to "hold group" for library 2
1150     Koha::CirculationRules->set_rules(
1151         {
1152             branchcode => $library2->branchcode,
1153             itemtype   => undef,
1154             rules => {
1155                 holdallowed => 2,
1156                 hold_fulfillment_policy => 'holdgroup',
1157                 returnbranch => 'any'
1158             }
1159         }
1160     );
1161
1162     # Test 5: Patron 3 cannot place hold
1163     is_deeply(
1164         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2, $library3->branchcode ),
1165         { status => 'pickupNotInHoldGroup' },
1166         'Patron cannot place hold if hold_fulfillment_policy is set to "hold group" for library 2'
1167     );
1168
1169     # Insert default item rule to "any" for itemtype 2
1170     Koha::CirculationRules->set_rules(
1171         {
1172             branchcode => $library2->branchcode,
1173             itemtype   => $itemtype2->itemtype,
1174             rules => {
1175                 holdallowed => 2,
1176                 hold_fulfillment_policy => 'any',
1177                 returnbranch => 'any'
1178             }
1179         }
1180     );
1181
1182     # Test 6: Patron 3 can place hold
1183     is_deeply(
1184         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2, $library3->branchcode ),
1185         { status => 'OK' },
1186         'Patron can place hold if hold_fulfillment_policy is set to "any" for itemtype 2'
1187     );
1188
1189     # Update default item rule to "hold group" for itemtype 2
1190     Koha::CirculationRules->set_rules(
1191         {
1192             branchcode => $library2->branchcode,
1193             itemtype   => $itemtype2->itemtype,
1194             rules => {
1195                 holdallowed => 2,
1196                 hold_fulfillment_policy => 'holdgroup',
1197                 returnbranch => 'any'
1198             }
1199         }
1200     );
1201
1202     # Test 7: Patron 3 cannot place hold
1203     is_deeply(
1204         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2, $library3->branchcode ),
1205         { status => 'pickupNotInHoldGroup' },
1206         'Patron cannot place hold if hold_fulfillment_policy is set to "hold group" for itemtype 2'
1207     );
1208
1209     # Insert branch item rule to "any" for itemtype 2 and library 2
1210     Koha::CirculationRules->set_rules(
1211         {
1212             branchcode => $library2->branchcode,
1213             itemtype   => $itemtype2->itemtype,
1214             rules => {
1215                 holdallowed => 2,
1216                 hold_fulfillment_policy => 'any',
1217                 returnbranch => 'any'
1218             }
1219         }
1220     );
1221
1222     # Test 8: Patron 3 can place hold
1223     is_deeply(
1224         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2, $library3->branchcode ),
1225         { status => 'OK' },
1226         'Patron can place hold if hold_fulfillment_policy is set to "any" for itemtype 2 and library 2'
1227     );
1228
1229     # Update branch item rule to "hold group" for itemtype 2 and library 2
1230     Koha::CirculationRules->set_rules(
1231         {
1232             branchcode => $library2->branchcode,
1233             itemtype   => $itemtype2->itemtype,
1234             rules => {
1235                 holdallowed => 2,
1236                 hold_fulfillment_policy => 'holdgroup',
1237                 returnbranch => 'any'
1238             }
1239         }
1240     );
1241
1242     # Test 9: Patron 3 cannot place hold
1243     is_deeply(
1244         CanItemBeReserved( $patron3->borrowernumber, $itemnumber_2, $library3->branchcode ),
1245         { status => 'pickupNotInHoldGroup' },
1246         'Patron cannot place hold if hold_fulfillment_policy is set to "hold group" for itemtype 2 and library 2'
1247     );
1248
1249     $schema->storage->txn_rollback;
1250 };
1251
1252 subtest 'non priority holds' => sub {
1253
1254     plan tests => 6;
1255
1256     $schema->storage->txn_begin;
1257
1258     Koha::CirculationRules->set_rules(
1259         {
1260             branchcode   => undef,
1261             categorycode => undef,
1262             itemtype     => undef,
1263             rules        => {
1264                 renewalsallowed => 5,
1265                 reservesallowed => 5,
1266             }
1267         }
1268     );
1269
1270     my $item = $builder->build_sample_item;
1271
1272     my $patron1 = $builder->build_object(
1273         {
1274             class => 'Koha::Patrons',
1275             value => { branchcode => $item->homebranch }
1276         }
1277     );
1278     my $patron2 = $builder->build_object(
1279         {
1280             class => 'Koha::Patrons',
1281             value => { branchcode => $item->homebranch }
1282         }
1283     );
1284
1285     Koha::Checkout->new(
1286         {
1287             borrowernumber => $patron1->borrowernumber,
1288             itemnumber     => $item->itemnumber,
1289             branchcode     => $item->homebranch
1290         }
1291     )->store;
1292
1293     my $hid = AddReserve(
1294         {
1295             branchcode     => $item->homebranch,
1296             borrowernumber => $patron2->borrowernumber,
1297             biblionumber   => $item->biblionumber,
1298             priority       => 1,
1299             itemnumber     => $item->itemnumber,
1300         }
1301     );
1302
1303     my ( $ok, $err ) =
1304       CanBookBeRenewed( $patron1->borrowernumber, $item->itemnumber );
1305
1306     ok( !$ok, 'Cannot renew' );
1307     is( $err, 'on_reserve', 'Item is on hold' );
1308
1309     my $hold = Koha::Holds->find($hid);
1310     $hold->non_priority(1)->store;
1311
1312     ( $ok, $err ) =
1313       CanBookBeRenewed( $patron1->borrowernumber, $item->itemnumber );
1314
1315     ok( $ok, 'Can renew' );
1316     is( $err, undef, 'Item is on non priority hold' );
1317
1318     my $patron3 = $builder->build_object(
1319         {
1320             class => 'Koha::Patrons',
1321             value => { branchcode => $item->homebranch }
1322         }
1323     );
1324
1325     # Add second hold with non_priority = 0
1326     AddReserve(
1327         {
1328             branchcode     => $item->homebranch,
1329             borrowernumber => $patron3->borrowernumber,
1330             biblionumber   => $item->biblionumber,
1331             priority       => 2,
1332             itemnumber     => $item->itemnumber,
1333         }
1334     );
1335
1336     ( $ok, $err ) =
1337       CanBookBeRenewed( $patron1->borrowernumber, $item->itemnumber );
1338
1339     ok( !$ok, 'Cannot renew' );
1340     is( $err, 'on_reserve', 'Item is on hold' );
1341
1342     $schema->storage->txn_rollback;
1343
1344 };
1345
1346 subtest 'CanItemBeReserved rule precedence tests' => sub {
1347
1348     plan tests => 3;
1349
1350     t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary');
1351     $schema->storage->txn_begin;
1352     my $library  = $builder->build_object( { class => 'Koha::Libraries', value => {
1353         pickup_location => 1,
1354     }});
1355     my $item = $builder->build_sample_item({
1356         homebranch    => $library->branchcode,
1357         holdingbranch => $library->branchcode
1358     });
1359     my $item2 = $builder->build_sample_item({
1360         homebranch    => $library->branchcode,
1361         holdingbranch => $library->branchcode,
1362         itype         => $item->itype
1363     });
1364     my $patron   = $builder->build_object({ class => 'Koha::Patrons', value => {
1365         branchcode => $library->branchcode
1366     }});
1367     Koha::CirculationRules->set_rules(
1368         {
1369             branchcode   => undef,
1370             categorycode => $patron->categorycode,
1371             itemtype     => $item->itype,
1372             rules        => {
1373                 reservesallowed  => 1,
1374             }
1375         }
1376     );
1377     is_deeply(
1378         CanItemBeReserved( $patron->borrowernumber, $item->itemnumber, $library->branchcode ),
1379         { status => 'OK' },
1380         'Patron of specified category can place 1 hold on specified itemtype'
1381     );
1382     my $hold = $builder->build_object({ class => 'Koha::Holds', value => {
1383         biblionumber   => $item2->biblionumber,
1384         itemnumber     => $item2->itemnumber,
1385         found          => undef,
1386         priority       => 1,
1387         branchcode     => $library->branchcode,
1388         borrowernumber => $patron->borrowernumber,
1389     }});
1390     is_deeply(
1391         CanItemBeReserved( $patron->borrowernumber, $item->itemnumber, $library->branchcode ),
1392         { status => 'tooManyReserves', limit => 1 },
1393         'Patron of specified category can place 1 hold on specified itemtype, cannot place a second'
1394     );
1395     Koha::CirculationRules->set_rules(
1396         {
1397             branchcode   => $library->branchcode,
1398             categorycode => undef,
1399             itemtype     => undef,
1400             rules        => {
1401                 reservesallowed  => 2,
1402             }
1403         }
1404     );
1405     is_deeply(
1406         CanItemBeReserved( $patron->borrowernumber, $item->itemnumber, $library->branchcode ),
1407         { status => 'OK' },
1408         'Patron of specified category can place 1 hold on specified itemtype if library rule for all types and categories set to 2'
1409     );
1410
1411     $schema->storage->txn_rollback;
1412
1413 };