Bug 30447: Unit tests
[koha-ffzg.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 => 75;
11 use Test::Exception;
12
13 use MARC::Record;
14
15 use C4::Biblio;
16 use C4::Calendar;
17 use C4::Items;
18 use C4::Reserves qw( AddReserve CalculatePriority ModReserve ToggleSuspend AutoUnsuspendReserves SuspendAll ModReserveMinusPriority AlterPriority CanItemBeReserved CheckReserves );
19 use C4::Circulation qw( CanBookBeRenewed );
20
21 use Koha::Biblios;
22 use Koha::CirculationRules;
23 use Koha::Database;
24 use Koha::DateUtils qw( dt_from_string output_pref );
25 use Koha::Holds qw( search );
26 use Koha::Checkout;
27 use Koha::Item::Transfer::Limits;
28 use Koha::Items;
29 use Koha::Libraries;
30 use Koha::Library::Groups;
31 use Koha::Patrons;
32 use Koha::Hold qw( get_items_that_can_fill );
33 use Koha::Item::Transfers;
34
35 BEGIN {
36     use FindBin;
37     use lib $FindBin::Bin;
38 }
39
40 my $schema  = Koha::Database->new->schema;
41 $schema->storage->txn_begin;
42
43 my $builder = t::lib::TestBuilder->new();
44 my $dbh     = C4::Context->dbh;
45
46 # Create two random branches
47 my $branch_1 = $builder->build({ source => 'Branch' })->{ branchcode };
48 my $branch_2 = $builder->build({ source => 'Branch' })->{ branchcode };
49
50 my $category = $builder->build({ source => 'Category' });
51
52 my $borrowers_count = 5;
53
54 $dbh->do('DELETE FROM itemtypes');
55 $dbh->do('DELETE FROM reserves');
56 $dbh->do('DELETE FROM circulation_rules');
57 my $insert_sth = $dbh->prepare('INSERT INTO itemtypes (itemtype) VALUES (?)');
58 $insert_sth->execute('CAN');
59 $insert_sth->execute('CANNOT');
60 $insert_sth->execute('DUMMY');
61 $insert_sth->execute('ONLY1');
62
63 # Setup Test------------------------
64 my $biblio = $builder->build_sample_biblio({ itemtype => 'DUMMY' });
65
66 # Create item instance for testing.
67 my $itemnumber = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber })->itemnumber;
68
69 # Create some borrowers
70 my @borrowernumbers;
71 my @patrons;
72 foreach (1..$borrowers_count) {
73     my $patron = Koha::Patron->new({
74         firstname =>  'my firstname',
75         surname => 'my surname ' . $_,
76         categorycode => $category->{categorycode},
77         branchcode => $branch_1,
78     })->store;
79     push @patrons, $patron;
80     push @borrowernumbers, $patron->borrowernumber;
81 }
82
83 # Create five item level holds
84 foreach my $borrowernumber ( @borrowernumbers ) {
85     AddReserve(
86         {
87             branchcode     => $branch_1,
88             borrowernumber => $borrowernumber,
89             biblionumber   => $biblio->biblionumber,
90             priority       => C4::Reserves::CalculatePriority( $biblio->biblionumber ),
91             itemnumber     => $itemnumber,
92         }
93     );
94 }
95
96 my $holds = $biblio->holds;
97 is( $holds->count, $borrowers_count, 'Test GetReserves()' );
98 is( $holds->next->priority, 1, "Reserve 1 has a priority of 1" );
99 is( $holds->next->priority, 2, "Reserve 2 has a priority of 2" );
100 is( $holds->next->priority, 3, "Reserve 3 has a priority of 3" );
101 is( $holds->next->priority, 4, "Reserve 4 has a priority of 4" );
102 is( $holds->next->priority, 5, "Reserve 5 has a priority of 5" );
103
104 my $item = Koha::Items->find( $itemnumber );
105 $holds = $item->current_holds;
106 my $first_hold = $holds->next;
107 my $reservedate = $first_hold->reservedate;
108 my $borrowernumber = $first_hold->borrowernumber;
109 my $branch_1code = $first_hold->branchcode;
110 my $reserve_id = $first_hold->reserve_id;
111 is( $reservedate, output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }), "holds_placed_today should return a valid reserve date");
112 is( $borrowernumber, $borrowernumbers[0], "holds_placed_today should return a valid borrowernumber");
113 is( $branch_1code, $branch_1, "holds_placed_today should return a valid branchcode");
114 ok($reserve_id, "Test holds_placed_today()");
115
116 my $hold = Koha::Holds->find( $reserve_id );
117 ok( $hold, "Koha::Holds found the hold" );
118 my $hold_biblio = $hold->biblio();
119 ok( $hold_biblio, "Got biblio using biblio() method" );
120 ok( $hold_biblio == $hold->biblio(), "biblio method returns stashed biblio" );
121 my $hold_item = $hold->item();
122 ok( $hold_item, "Got item using item() method" );
123 ok( $hold_item == $hold->item(), "item method returns stashed item" );
124 my $hold_branch = $hold->branch();
125 ok( $hold_branch, "Got branch using branch() method" );
126 ok( $hold_branch == $hold->branch(), "branch method returns stashed branch" );
127 my $hold_found = $hold->found();
128 $hold->set({ found => 'W'})->store();
129 is( Koha::Holds->waiting()->count(), 1, "Koha::Holds->waiting returns waiting holds" );
130 is( Koha::Holds->unfilled()->count(), 4, "Koha::Holds->unfilled returns unfilled holds" );
131
132 my $patron = Koha::Patrons->find( $borrowernumbers[0] );
133 $holds = $patron->holds;
134 is( $holds->next->borrowernumber, $borrowernumbers[0], "Test Koha::Patron->holds");
135
136
137 $holds = $item->current_holds;
138 $first_hold = $holds->next;
139 $borrowernumber = $first_hold->borrowernumber;
140 $branch_1code = $first_hold->branchcode;
141 $reserve_id = $first_hold->reserve_id;
142
143 ModReserve({
144     reserve_id    => $reserve_id,
145     rank          => '4',
146     branchcode    => $branch_1,
147     itemnumber    => $itemnumber,
148     suspend_until => output_pref( { dt => dt_from_string( "2013-01-01", "iso" ), dateonly => 1 } ),
149 });
150
151 $hold = Koha::Holds->find( $reserve_id );
152 ok( $hold->priority eq '4', "Test ModReserve, priority changed correctly" );
153 ok( $hold->suspend, "Test ModReserve, suspend hold" );
154 is( $hold->suspend_until, '2013-01-01 00:00:00', "Test ModReserve, suspend until date" );
155
156 ModReserve({ # call without reserve_id
157     rank          => '3',
158     biblionumber  => $biblio->biblionumber,
159     itemnumber    => $itemnumber,
160     borrowernumber => $borrowernumber,
161 });
162 $hold = Koha::Holds->find( $reserve_id );
163 ok( $hold->priority eq '3', "Test ModReserve, priority changed correctly" );
164
165 ToggleSuspend( $reserve_id );
166 $hold = Koha::Holds->find( $reserve_id );
167 ok( ! $hold->suspend, "Test ToggleSuspend(), no date" );
168
169 ToggleSuspend( $reserve_id, '2012-01-01' );
170 $hold = Koha::Holds->find( $reserve_id );
171 is( $hold->suspend_until, '2012-01-01 00:00:00', "Test ToggleSuspend(), with date" );
172
173 AutoUnsuspendReserves();
174 $hold = Koha::Holds->find( $reserve_id );
175 ok( ! $hold->suspend, "Test AutoUnsuspendReserves()" );
176
177 SuspendAll(
178     borrowernumber => $borrowernumber,
179     biblionumber   => $biblio->biblionumber,
180     suspend => 1,
181     suspend_until => '2012-01-01',
182 );
183 $hold = Koha::Holds->find( $reserve_id );
184 is( $hold->suspend, 1, "Test SuspendAll()" );
185 is( $hold->suspend_until, '2012-01-01 00:00:00', "Test SuspendAll(), with date" );
186
187 SuspendAll(
188     borrowernumber => $borrowernumber,
189     biblionumber   => $biblio->biblionumber,
190     suspend => 0,
191 );
192 $hold = Koha::Holds->find( $reserve_id );
193 is( $hold->suspend, 0, "Test resuming with SuspendAll()" );
194 is( $hold->suspend_until, undef, "Test resuming with SuspendAll(), should have no suspend until date" );
195
196 # Add a new hold for the borrower whose hold we canceled earlier, this time at the bib level
197     AddReserve(
198         {
199             branchcode     => $branch_1,
200             borrowernumber => $borrowernumbers[0],
201             biblionumber   => $biblio->biblionumber,
202         }
203     );
204
205 $patron = Koha::Patrons->find( $borrowernumber );
206 $holds = $patron->holds;
207 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $borrowernumbers[0] })->next->reserve_id;
208 ModReserveMinusPriority( $itemnumber, $reserveid );
209 $holds = $patron->holds;
210 is( $holds->search({ itemnumber => $itemnumber })->count, 1, "Test ModReserveMinusPriority()" );
211
212 $holds = $biblio->holds;
213 $hold = $holds->next;
214 AlterPriority( 'top', $hold->reserve_id, undef, 2, 1, 6 );
215 $hold = Koha::Holds->find( $reserveid );
216 is( $hold->priority, '1', "Test AlterPriority(), move to top" );
217
218 AlterPriority( 'down', $hold->reserve_id, undef, 2, 1, 6 );
219 $hold = Koha::Holds->find( $reserveid );
220 is( $hold->priority, '2', "Test AlterPriority(), move down" );
221
222 AlterPriority( 'up', $hold->reserve_id, 1, 3, 1, 6 );
223 $hold = Koha::Holds->find( $reserveid );
224 is( $hold->priority, '1', "Test AlterPriority(), move up" );
225
226 AlterPriority( 'bottom', $hold->reserve_id, undef, 2, 1, 6 );
227 $hold = Koha::Holds->find( $reserveid );
228 is( $hold->priority, '6', "Test AlterPriority(), move to bottom" );
229
230
231 $hold->delete;
232 throws_ok
233     { C4::Reserves::ModReserve({ reserve_id => $hold->reserve_id }) }
234     'Koha::Exceptions::ObjectNotFound',
235     'No hold with id ' . $hold->reserve_id;
236
237 # Regression test for bug 2394
238 #
239 # If IndependentBranches is ON and canreservefromotherbranches is OFF,
240 # a patron is not permittedo to request an item whose homebranch (i.e.,
241 # owner of the item) is different from the patron's own library.
242 # However, if canreservefromotherbranches is turned ON, the patron can
243 # create such hold requests.
244 #
245 # Note that canreservefromotherbranches has no effect if
246 # IndependentBranches is OFF.
247
248 my $foreign_biblio = $builder->build_sample_biblio({ itemtype => 'DUMMY' });
249 my $foreign_item = $builder->build_sample_item({ library => $branch_2, biblionumber => $foreign_biblio->biblionumber });
250 Koha::CirculationRules->set_rules(
251     {
252         categorycode => undef,
253         branchcode   => undef,
254         itemtype     => undef,
255         rules        => {
256             reservesallowed  => 25,
257             holds_per_record => 99,
258         }
259     }
260 );
261 Koha::CirculationRules->set_rules(
262     {
263         categorycode => undef,
264         branchcode   => undef,
265         itemtype     => 'CANNOT',
266         rules        => {
267             reservesallowed  => 0,
268             holds_per_record => 99,
269         }
270     }
271 );
272
273 # make sure some basic sysprefs are set
274 t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary');
275 t::lib::Mocks::mock_preference('item-level_itypes', 1);
276
277 # if IndependentBranches is OFF, a $branch_1 patron can reserve an $branch_2 item
278 t::lib::Mocks::mock_preference('IndependentBranches', 0);
279
280 is(
281     CanItemBeReserved($patrons[0], $foreign_item)->{status}, 'OK',
282     '$branch_1 patron allowed to reserve $branch_2 item with IndependentBranches OFF (bug 2394)'
283 );
284
285 # if IndependentBranches is OFF, a $branch_1 patron cannot reserve an $branch_2 item
286 t::lib::Mocks::mock_preference('IndependentBranches', 1);
287 t::lib::Mocks::mock_preference('canreservefromotherbranches', 0);
288 ok(
289     CanItemBeReserved($patrons[0], $foreign_item)->{status} eq 'cannotReserveFromOtherBranches',
290     '$branch_1 patron NOT allowed to reserve $branch_2 item with IndependentBranches ON ... (bug 2394)'
291 );
292
293 # ... unless canreservefromotherbranches is ON
294 t::lib::Mocks::mock_preference('canreservefromotherbranches', 1);
295 ok(
296     CanItemBeReserved($patrons[0], $foreign_item)->{status} eq 'OK',
297     '... unless canreservefromotherbranches is ON (bug 2394)'
298 );
299
300 {
301     # Regression test for bug 11336 # Test if ModReserve correctly recalculate the priorities
302     $biblio = $builder->build_sample_biblio({ itemtype => 'DUMMY' });
303     $itemnumber = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber })->itemnumber;
304     my $reserveid1 = AddReserve(
305         {
306             branchcode     => $branch_1,
307             borrowernumber => $borrowernumbers[0],
308             biblionumber   => $biblio->biblionumber,
309             priority       => 1
310         }
311     );
312
313     $itemnumber = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber })->itemnumber;
314     my $reserveid2 = AddReserve(
315         {
316             branchcode     => $branch_1,
317             borrowernumber => $borrowernumbers[1],
318             biblionumber   => $biblio->biblionumber,
319             priority       => 2
320         }
321     );
322
323     $itemnumber = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber })->itemnumber;
324     my $reserveid3 = AddReserve(
325         {
326             branchcode     => $branch_1,
327             borrowernumber => $borrowernumbers[2],
328             biblionumber   => $biblio->biblionumber,
329             priority       => 3
330         }
331     );
332
333     my $hhh = Koha::Holds->search({ biblionumber => $biblio->biblionumber });
334     my $hold3 = Koha::Holds->find( $reserveid3 );
335     is( $hold3->priority, 3, "The 3rd hold should have a priority set to 3" );
336     ModReserve({ reserve_id => $reserveid1, rank => 'del' });
337     ModReserve({ reserve_id => $reserveid2, rank => 'del' });
338     is( $hold3->discard_changes->priority, 1, "After ModReserve, the 3rd reserve becomes the first on the waiting list" );
339 }
340
341 my $damaged_item = Koha::Items->find($itemnumber)->damaged(1)->store; # FIXME The $itemnumber is a bit confusing here
342 t::lib::Mocks::mock_preference( 'AllowHoldsOnDamagedItems', 1 );
343 is( CanItemBeReserved( $patrons[0], $damaged_item)->{status}, 'OK', "Patron can reserve damaged item with AllowHoldsOnDamagedItems enabled" );
344 ok( defined( ( CheckReserves($itemnumber) )[1] ), "Hold can be trapped for damaged item with AllowHoldsOnDamagedItems enabled" );
345
346 $hold = Koha::Hold->new(
347     {
348         borrowernumber => $borrowernumbers[0],
349         itemnumber     => $itemnumber,
350         biblionumber   => $biblio->biblionumber,
351     }
352 )->store();
353 is( CanItemBeReserved( $patrons[0], $damaged_item )->{status},
354     'itemAlreadyOnHold',
355     "Patron cannot place a second item level hold for a given item" );
356 $hold->delete();
357
358 t::lib::Mocks::mock_preference( 'AllowHoldsOnDamagedItems', 0 );
359 ok( CanItemBeReserved( $patrons[0], $damaged_item)->{status} eq 'damaged', "Patron cannot reserve damaged item with AllowHoldsOnDamagedItems disabled" );
360 ok( !defined( ( CheckReserves($itemnumber) )[1] ), "Hold cannot be trapped for damaged item with AllowHoldsOnDamagedItems disabled" );
361
362 # Items that are not for loan, but holdable should not be trapped until they are available for loan
363 t::lib::Mocks::mock_preference( 'TrapHoldsOnOrder', 0 );
364 my $nfl_item = Koha::Items->find($itemnumber)->damaged(0)->notforloan(-1)->store;
365 Koha::Holds->search({ biblionumber => $biblio->id })->delete();
366 is( CanItemBeReserved( $patrons[0], $nfl_item)->{status}, 'OK', "Patron can place hold on item that is not for loan but holdable ( notforloan < 0 )" );
367 $hold = Koha::Hold->new(
368     {
369         borrowernumber => $borrowernumbers[0],
370         itemnumber     => $itemnumber,
371         biblionumber   => $biblio->biblionumber,
372         found          => undef,
373         priority       => 1,
374         reservedate    => dt_from_string,
375         branchcode     => $branch_1,
376     }
377 )->store();
378 ok( !defined( ( CheckReserves($itemnumber) )[1] ), "Hold cannot be trapped for item that is not for loan but holdable ( notforloan < 0 )" );
379 t::lib::Mocks::mock_preference( 'TrapHoldsOnOrder', 1 );
380 ok( defined( ( CheckReserves($itemnumber) )[1] ), "Hold is trapped for item that is not for loan but holdable ( notforloan < 0 )" );
381 t::lib::Mocks::mock_preference( 'SkipHoldTrapOnNotForLoanValue', '-1' );
382 ok( !defined( ( CheckReserves($itemnumber) )[1] ), "Hold cannot be trapped for item with notforloan value matching SkipHoldTrapOnNotForLoanValue" );
383 t::lib::Mocks::mock_preference( 'SkipHoldTrapOnNotForLoanValue', '-1|1' );
384 ok( !defined( ( CheckReserves($itemnumber) )[1] ), "Hold cannot be trapped for item with notforloan value matching SkipHoldTrapOnNotForLoanValue" );
385 is(
386     CanItemBeReserved( $patrons[0], $nfl_item)->{status}, 'itemAlreadyOnHold',
387     "cannot request item that you have already reservedd"
388 );
389 is(
390     CanItemBeReserved( $patrons[0], $item, undef, { ignore_hold_counts => 1 })->{status}, 'OK',
391     "can request item if we are not checking holds counts, but only if policy allows or forbids it"
392 );
393 $hold->delete();
394
395 # Regression test for bug 9532
396 $biblio = $builder->build_sample_biblio({ itemtype => 'CANNOT' });
397 $item = $builder->build_sample_item({ library => $branch_1, itype => 'CANNOT', biblionumber => $biblio->biblionumber});
398 AddReserve(
399     {
400         branchcode     => $branch_1,
401         borrowernumber => $borrowernumbers[0],
402         biblionumber   => $biblio->biblionumber,
403         priority       => 1,
404     }
405 );
406 is(
407     CanItemBeReserved( $patrons[0], $item)->{status}, 'noReservesAllowed',
408     "cannot request item if policy that matches on item-level item type forbids it"
409 );
410 is(
411     CanItemBeReserved( $patrons[0], $item, undef, { ignore_hold_counts => 1 })->{status}, 'noReservesAllowed',
412     "cannot request item if policy that matches on item-level item type forbids it even if ignoring counts"
413 );
414
415 subtest 'CanItemBeReserved' => sub {
416     plan tests => 2;
417
418     my $itemtype_can         = $builder->build({source => "Itemtype"})->{itemtype};
419     my $itemtype_cant        = $builder->build({source => "Itemtype"})->{itemtype};
420     my $itemtype_cant_record = $builder->build({source => "Itemtype"})->{itemtype};
421
422     Koha::CirculationRules->set_rules(
423         {
424             categorycode => undef,
425             branchcode   => undef,
426             itemtype     => $itemtype_cant,
427             rules        => {
428                 reservesallowed  => 0,
429                 holds_per_record => 99,
430             }
431         }
432     );
433     Koha::CirculationRules->set_rules(
434         {
435             categorycode => undef,
436             branchcode   => undef,
437             itemtype     => $itemtype_can,
438             rules        => {
439                 reservesallowed  => 2,
440                 holds_per_record => 2,
441             }
442         }
443     );
444     Koha::CirculationRules->set_rules(
445         {
446             categorycode => undef,
447             branchcode   => undef,
448             itemtype     => $itemtype_cant_record,
449             rules        => {
450                 reservesallowed  => 0,
451                 holds_per_record => 0,
452             }
453         }
454     );
455
456     Koha::CirculationRules->set_rules(
457         {
458             branchcode => $branch_1,
459             itemtype   => $itemtype_cant,
460             rules => {
461                 holdallowed => 0,
462                 returnbranch => 'homebranch',
463             }
464         }
465     );
466     Koha::CirculationRules->set_rules(
467         {
468             branchcode => $branch_1,
469             itemtype   => $itemtype_can,
470             rules => {
471                 holdallowed => 1,
472                 returnbranch => 'homebranch',
473             }
474         }
475     );
476
477     subtest 'noReservesAllowed' => sub {
478         plan tests => 5;
479
480         my $biblionumber_cannot = $builder->build_sample_biblio({ itemtype => $itemtype_cant })->biblionumber;
481         my $biblionumber_can = $builder->build_sample_biblio({ itemtype => $itemtype_can })->biblionumber;
482         my $biblionumber_record_cannot = $builder->build_sample_biblio({ itemtype => $itemtype_cant_record })->biblionumber;
483
484         my $item_1_can = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, biblionumber => $biblionumber_cannot });
485         my $item_1_cannot = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_cant, biblionumber => $biblionumber_cannot });
486         my $item_2_can = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, biblionumber => $biblionumber_can });
487         my $item_2_cannot = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_cant, biblionumber => $biblionumber_can });
488         my $item_3_cannot = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_cant_record, biblionumber => $biblionumber_record_cannot });
489
490         Koha::Holds->search({borrowernumber => $borrowernumbers[0]})->delete;
491
492         t::lib::Mocks::mock_preference('item-level_itypes', 1);
493         is(
494             CanItemBeReserved( $patrons[0], $item_2_cannot)->{status}, 'noReservesAllowed',
495             "With item level set, rule from item must be picked (CANNOT)"
496         );
497         is(
498             CanItemBeReserved( $patrons[0], $item_1_can)->{status}, 'OK',
499             "With item level set, rule from item must be picked (CAN)"
500         );
501         t::lib::Mocks::mock_preference('item-level_itypes', 0);
502         is(
503             CanItemBeReserved( $patrons[0], $item_1_can)->{status}, 'noReservesAllowed',
504             "With biblio level set, rule from biblio must be picked (CANNOT)"
505         );
506         is(
507             CanItemBeReserved( $patrons[0], $item_2_cannot)->{status}, 'OK',
508             "With biblio level set, rule from biblio must be picked (CAN)"
509         );
510         is(
511             CanItemBeReserved( $patrons[0], $item_3_cannot)->{status}, 'noReservesAllowed',
512             "When no holds allowed and no holds per record allowed should return noReservesAllowed"
513         );
514     };
515
516     subtest 'tooManyHoldsForThisRecord + tooManyReserves + itemAlreadyOnHold' => sub {
517         plan tests => 7;
518
519         my $biblionumber_1 = $builder->build_sample_biblio({ itemtype => $itemtype_can })->biblionumber;
520         my $item_11 = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, biblionumber => $biblionumber_1 });
521         my $item_12 = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, biblionumber => $biblionumber_1 });
522         my $biblionumber_2 = $builder->build_sample_biblio({ itemtype => $itemtype_can })->biblionumber;
523         my $item_21 = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, biblionumber => $biblionumber_2 });
524         my $item_22 = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, biblionumber => $biblionumber_2 });
525
526         Koha::Holds->search({borrowernumber => $borrowernumbers[0]})->delete;
527
528         # Biblio-level hold
529         AddReserve({
530             branch => $branch_1,
531             borrowernumber => $borrowernumbers[0],
532             biblionumber => $biblionumber_1,
533         });
534         for my $item_level ( 0..1 ) {
535             t::lib::Mocks::mock_preference('item-level_itypes', $item_level);
536             is(
537                 # FIXME This is not really correct, but CanItemBeReserved does not check if biblio-level holds already exist
538                 CanItemBeReserved( $patrons[0], $item_11)->{status}, 'OK',
539                 "A biblio-level hold already exists - another hold can be placed on a specific item item"
540             );
541         }
542
543         Koha::Holds->search({borrowernumber => $borrowernumbers[0]})->delete;
544         # Item-level hold
545         AddReserve({
546             branch => $branch_1,
547             borrowernumber => $borrowernumbers[0],
548             biblionumber => $biblionumber_1,
549             itemnumber => $item_11->itemnumber,
550         });
551
552         $dbh->do('DELETE FROM circulation_rules');
553         Koha::CirculationRules->set_rules(
554             {
555                 categorycode => undef,
556                 branchcode   => undef,
557                 itemtype     => undef,
558                 rules        => {
559                     reservesallowed  => 5,
560                     holds_per_record => 1,
561                 }
562             }
563         );
564         is(
565             CanItemBeReserved( $patrons[0], $item_12)->{status}, 'tooManyHoldsForThisRecord',
566             "A item-level hold already exists and holds_per_record=1, another hold cannot be placed on this record"
567         );
568         Koha::CirculationRules->set_rules(
569             {
570                 categorycode => undef,
571                 branchcode   => undef,
572                 itemtype     => undef,
573                 rules        => {
574                     reservesallowed  => 1,
575                     holds_per_record => 1,
576                 }
577             }
578         );
579         is(
580             CanItemBeReserved( $patrons[0], $item_12)->{status}, 'tooManyHoldsForThisRecord',
581             "A item-level hold already exists and holds_per_record=1 - tooManyHoldsForThisRecord has priority over tooManyReserves"
582         );
583         Koha::CirculationRules->set_rules(
584             {
585                 categorycode => undef,
586                 branchcode   => undef,
587                 itemtype     => undef,
588                 rules        => {
589                     reservesallowed  => 5,
590                     holds_per_record => 2,
591                 }
592             }
593         );
594         is(
595             CanItemBeReserved( $patrons[0], $item_12)->{status}, 'OK',
596             "A item-level hold already exists but holds_per_record=2- another item-level hold can be placed on this record"
597         );
598
599         AddReserve({
600             branch => $branch_1,
601             borrowernumber => $borrowernumbers[0],
602             biblionumber => $biblionumber_2,
603             itemnumber => $item_21->itemnumber
604         });
605         Koha::CirculationRules->set_rules(
606             {
607                 categorycode => undef,
608                 branchcode   => undef,
609                 itemtype     => undef,
610                 rules        => {
611                     reservesallowed  => 2,
612                     holds_per_record => 2,
613                 }
614             }
615         );
616         is(
617             CanItemBeReserved( $patrons[0], $item_21)->{status}, 'itemAlreadyOnHold',
618             "A item-level holds already exists on this item, itemAlreadyOnHold should be raised"
619         );
620         is(
621             CanItemBeReserved( $patrons[0], $item_22)->{status}, 'tooManyReserves',
622             "This patron has already placed reservesallowed holds, tooManyReserves should be raised"
623         );
624     };
625 };
626
627
628 # Test branch item rules
629
630 $dbh->do('DELETE FROM circulation_rules');
631 Koha::CirculationRules->set_rules(
632     {
633         categorycode => undef,
634         branchcode   => undef,
635         itemtype     => undef,
636         rules        => {
637             reservesallowed  => 25,
638             holds_per_record => 99,
639         }
640     }
641 );
642 Koha::CirculationRules->set_rules(
643     {
644         branchcode => $branch_1,
645         itemtype   => 'CANNOT',
646         rules => {
647             holdallowed => 'not_allowed',
648             returnbranch => 'homebranch',
649         }
650     }
651 );
652 Koha::CirculationRules->set_rules(
653     {
654         branchcode => $branch_1,
655         itemtype   => 'CAN',
656         rules => {
657             holdallowed => 'from_home_library',
658             returnbranch => 'homebranch',
659         }
660     }
661 );
662 $biblio = $builder->build_sample_biblio({ itemtype => 'CANNOT' });
663 my $branch_rule_item = $builder->build_sample_item({ library => $branch_1, itype => 'CANNOT', biblionumber => $biblio->biblionumber});
664 is(CanItemBeReserved($patrons[0], $branch_rule_item)->{status}, 'notReservable',
665     "CanItemBeReserved should return 'notReservable'");
666
667 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
668 $branch_rule_item = $builder->build_sample_item({ library => $branch_2, itype => 'CAN', biblionumber => $biblio->biblionumber});
669 is(CanItemBeReserved($patrons[0], $branch_rule_item)->{status},
670     'cannotReserveFromOtherBranches',
671     "CanItemBeReserved should use PatronLibrary rule when ReservesControlBranch set to 'PatronLibrary'");
672 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
673 is(CanItemBeReserved($patrons[0], $branch_rule_item)->{status},
674     'OK',
675     "CanItemBeReserved should use item home library rule when ReservesControlBranch set to 'ItemsHomeLibrary'");
676
677 $branch_rule_item = $builder->build_sample_item({ library => $branch_1, itype => 'CAN', biblionumber => $biblio->biblionumber});
678 is(CanItemBeReserved($patrons[0], $branch_rule_item)->{status}, 'OK',
679     "CanItemBeReserved should return 'OK'");
680
681 # Bug 12632
682 t::lib::Mocks::mock_preference( 'item-level_itypes',     1 );
683 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
684
685 $dbh->do('DELETE FROM reserves');
686 $dbh->do('DELETE FROM issues');
687 $dbh->do('DELETE FROM items');
688 $dbh->do('DELETE FROM biblio');
689
690 $biblio = $builder->build_sample_biblio({ itemtype => 'ONLY1' });
691 my $limit_count_item = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber});
692
693 Koha::CirculationRules->set_rules(
694     {
695         categorycode => undef,
696         branchcode   => undef,
697         itemtype     => 'ONLY1',
698         rules        => {
699             reservesallowed  => 1,
700             holds_per_record => 99,
701         }
702     }
703 );
704 is( CanItemBeReserved( $patrons[0], $limit_count_item )->{status},
705     'OK', 'Patron can reserve item with hold limit of 1, no holds placed' );
706
707 my $res_id = AddReserve(
708     {
709         branchcode     => $branch_1,
710         borrowernumber => $borrowernumbers[0],
711         biblionumber   => $biblio->biblionumber,
712         priority       => 1,
713     }
714 );
715
716 is( CanItemBeReserved( $patrons[0], $limit_count_item )->{status},
717     'tooManyReserves', 'Patron cannot reserve item with hold limit of 1, 1 bib level hold placed' );
718 is( CanItemBeReserved( $patrons[0], $limit_count_item, undef, { ignore_hold_counts => 1 } )->{status},
719     'OK', 'Patron can reserve item if checking policy but not counts' );
720
721     #results should be the same for both ReservesControlBranch settings
722 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
723 is( CanItemBeReserved( $patrons[0], $limit_count_item )->{status},
724     'tooManyReserves', 'Patron cannot reserve item with hold limit of 1, 1 bib level hold placed' );
725 #reset for further tests
726 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
727
728 subtest 'Test max_holds per library/patron category' => sub {
729     plan tests => 6;
730
731     $dbh->do('DELETE FROM reserves');
732
733     $biblio = $builder->build_sample_biblio;
734     my $max_holds_item = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber});
735     Koha::CirculationRules->set_rules(
736         {
737             categorycode => undef,
738             branchcode   => undef,
739             itemtype     => $biblio->itemtype,
740             rules        => {
741                 reservesallowed  => 99,
742                 holds_per_record => 99,
743             }
744         }
745     );
746
747     for ( 1 .. 3 ) {
748         AddReserve(
749             {
750                 branchcode     => $branch_1,
751                 borrowernumber => $borrowernumbers[0],
752                 biblionumber   => $biblio->biblionumber,
753                 priority       => 1,
754             }
755         );
756     }
757
758     my $count =
759       Koha::Holds->search( { borrowernumber => $borrowernumbers[0] } )->count();
760     is( $count, 3, 'Patron now has 3 holds' );
761
762     my $ret = CanItemBeReserved( $patrons[0], $max_holds_item );
763     is( $ret->{status}, 'OK', 'Patron can place hold with no borrower circ rules' );
764
765     my $rule_all = Koha::CirculationRules->set_rule(
766         {
767             categorycode => $category->{categorycode},
768             branchcode   => undef,
769             rule_name    => 'max_holds',
770             rule_value   => 3,
771         }
772     );
773
774     my $rule_branch = Koha::CirculationRules->set_rule(
775         {
776             branchcode   => $branch_1,
777             categorycode => $category->{categorycode},
778             rule_name    => 'max_holds',
779             rule_value   => 5,
780         }
781     );
782
783     $ret = CanItemBeReserved( $patrons[0], $max_holds_item );
784     is( $ret->{status}, 'OK', 'Patron can place hold with branch/category rule of 5, category rule of 3' );
785
786     $rule_branch->delete();
787
788     $ret = CanItemBeReserved( $patrons[0], $max_holds_item );
789     is( $ret->{status}, 'tooManyReserves', 'Patron cannot place hold with only a category rule of 3' );
790
791     $rule_all->delete();
792     $rule_branch->rule_value(3);
793     $rule_branch->store();
794
795     $ret = CanItemBeReserved( $patrons[0], $max_holds_item );
796     is( $ret->{status}, 'tooManyReserves', 'Patron cannot place hold with only a branch/category rule of 3' );
797
798     $rule_branch->rule_value(5);
799     $rule_branch->update();
800     $rule_branch->rule_value(5);
801     $rule_branch->store();
802
803     $ret = CanItemBeReserved( $patrons[0], $max_holds_item );
804     is( $ret->{status}, 'OK', 'Patron can place hold with branch/category rule of 5, category rule of 5' );
805 };
806
807 subtest 'Pickup location availability tests' => sub {
808     plan tests => 4;
809
810     $biblio = $builder->build_sample_biblio({ itemtype => 'ONLY1' });
811     my $pickup_item = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber});
812     #Add a default rule to allow some holds
813
814     Koha::CirculationRules->set_rules(
815         {
816             branchcode   => undef,
817             categorycode => undef,
818             itemtype     => undef,
819             rules        => {
820                 reservesallowed  => 25,
821                 holds_per_record => 99,
822             }
823         }
824     );
825     my $branch_to = $builder->build({ source => 'Branch' })->{ branchcode };
826     my $library = Koha::Libraries->find($branch_to);
827     $library->pickup_location('1')->store;
828     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
829
830     t::lib::Mocks::mock_preference('UseBranchTransferLimits', 1);
831     t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'itemtype');
832
833     $library->pickup_location('1')->store;
834     is(CanItemBeReserved($patron, $pickup_item, $branch_to)->{status},
835        'OK', 'Library is a pickup location');
836
837     my $limit = Koha::Item::Transfer::Limit->new({
838         fromBranch => $pickup_item->holdingbranch,
839         toBranch => $branch_to,
840         itemtype => $pickup_item->effective_itemtype,
841     })->store;
842     is(CanItemBeReserved($patron, $pickup_item, $branch_to)->{status},
843        'cannotBeTransferred', 'Item cannot be transferred');
844     $limit->delete;
845
846     $library->pickup_location('0')->store;
847     is(CanItemBeReserved($patron, $pickup_item, $branch_to)->{status},
848        'libraryNotPickupLocation', 'Library is not a pickup location');
849     is(CanItemBeReserved($patron, $pickup_item, 'nonexistent')->{status},
850        'libraryNotFound', 'Cannot set unknown library as pickup location');
851 };
852
853 $schema->storage->txn_rollback;
854
855 subtest 'CanItemBeReserved / holds_per_day tests' => sub {
856
857     plan tests => 10;
858
859     $schema->storage->txn_begin;
860
861     my $itemtype = $builder->build_object( { class => 'Koha::ItemTypes' } );
862     my $library  = $builder->build_object( { class => 'Koha::Libraries' } );
863     my $patron   = $builder->build_object( { class => 'Koha::Patrons' } );
864
865     # Create 3 biblios with items
866     my $biblio_1 = $builder->build_sample_biblio({ itemtype => $itemtype->itemtype });
867     my $item_1 = $builder->build_sample_item({ library => $library->branchcode, biblionumber => $biblio_1->biblionumber});
868     my $biblio_2 = $builder->build_sample_biblio({ itemtype => $itemtype->itemtype });
869     my $item_2 = $builder->build_sample_item({ library => $library->branchcode, biblionumber => $biblio_2->biblionumber});
870     my $biblio_3 = $builder->build_sample_biblio({ itemtype => $itemtype->itemtype });
871     my $item_3 = $builder->build_sample_item({ library => $library->branchcode, biblionumber => $biblio_3->biblionumber});
872
873     Koha::CirculationRules->set_rules(
874         {
875             categorycode => '*',
876             branchcode   => '*',
877             itemtype     => $itemtype->itemtype,
878             rules        => {
879                 reservesallowed  => 1,
880                 holds_per_record => 99,
881                 holds_per_day    => 2
882             }
883         }
884     );
885
886     is_deeply(
887         CanItemBeReserved( $patron, $item_1 ),
888         { status => 'OK' },
889         'Patron can reserve item with hold limit of 1, no holds placed'
890     );
891
892     AddReserve(
893         {
894             branchcode     => $library->branchcode,
895             borrowernumber => $patron->borrowernumber,
896             biblionumber   => $biblio_1->biblionumber,
897             priority       => 1,
898         }
899     );
900
901     is_deeply(
902         CanItemBeReserved( $patron, $item_1 ),
903         { status => 'tooManyReserves', limit => 1 },
904         'Patron cannot reserve item with hold limit of 1, 1 bib level hold placed'
905     );
906
907     # Raise reservesallowed to avoid tooManyReserves from it
908     Koha::CirculationRules->set_rule(
909         {
910
911             categorycode => '*',
912             branchcode   => '*',
913             itemtype     => $itemtype->itemtype,
914             rule_name  => 'reservesallowed',
915             rule_value => 3,
916         }
917     );
918
919     is_deeply(
920         CanItemBeReserved( $patron, $item_2 ),
921         { status => 'OK' },
922         'Patron can reserve item with 2 reserves daily cap'
923     );
924
925     # Add a second reserve
926     my $res_id = AddReserve(
927         {
928             branchcode     => $library->branchcode,
929             borrowernumber => $patron->borrowernumber,
930             biblionumber   => $biblio_2->biblionumber,
931             priority       => 1,
932         }
933     );
934     is_deeply(
935         CanItemBeReserved( $patron, $item_2 ),
936         { status => 'tooManyReservesToday', limit => 2 },
937         'Patron cannot a third item with 2 reserves daily cap'
938     );
939
940     # Update last hold so reservedate is in the past, so 2 holds, but different day
941     $hold = Koha::Holds->find($res_id);
942     my $yesterday = dt_from_string() - DateTime::Duration->new( days => 1 );
943     $hold->reservedate($yesterday)->store;
944
945     is_deeply(
946         CanItemBeReserved( $patron, $item_2 ),
947         { status => 'OK' },
948         'Patron can reserve item with 2 bib level hold placed on different days, 2 reserves daily cap'
949     );
950
951     # Set holds_per_day to 0
952     Koha::CirculationRules->set_rule(
953         {
954
955             categorycode => '*',
956             branchcode   => '*',
957             itemtype     => $itemtype->itemtype,
958             rule_name  => 'holds_per_day',
959             rule_value => 0,
960         }
961     );
962
963
964     # Delete existing holds
965     Koha::Holds->search->delete;
966     is_deeply(
967         CanItemBeReserved( $patron, $item_2 ),
968         { status => 'tooManyReservesToday', limit => 0 },
969         'Patron cannot reserve if holds_per_day is 0 (i.e. 0 is 0)'
970     );
971
972     Koha::CirculationRules->set_rule(
973         {
974
975             categorycode => '*',
976             branchcode   => '*',
977             itemtype     => $itemtype->itemtype,
978             rule_name  => 'holds_per_day',
979             rule_value => undef,
980         }
981     );
982
983     Koha::Holds->search->delete;
984     is_deeply(
985         CanItemBeReserved( $patron, $item_2 ),
986         { status => 'OK' },
987         'Patron can reserve if holds_per_day is undef (i.e. undef is unlimited daily cap)'
988     );
989     AddReserve(
990         {
991             branchcode     => $library->branchcode,
992             borrowernumber => $patron->borrowernumber,
993             biblionumber   => $biblio_1->biblionumber,
994             priority       => 1,
995         }
996     );
997     AddReserve(
998         {
999             branchcode     => $library->branchcode,
1000             borrowernumber => $patron->borrowernumber,
1001             biblionumber   => $biblio_2->biblionumber,
1002             priority       => 1,
1003         }
1004     );
1005
1006     is_deeply(
1007         CanItemBeReserved( $patron, $item_3 ),
1008         { status => 'OK' },
1009         'Patron can reserve if holds_per_day is undef (i.e. undef is unlimited daily cap)'
1010     );
1011     AddReserve(
1012         {
1013             branchcode     => $library->branchcode,
1014             borrowernumber => $patron->borrowernumber,
1015             biblionumber   => $biblio_3->biblionumber,
1016             priority       => 1,
1017         }
1018     );
1019     is_deeply(
1020         CanItemBeReserved( $patron, $item_3 ),
1021         { status => 'tooManyReserves', limit => 3 },
1022         'Unlimited daily holds, but reached reservesallowed'
1023     );
1024     #results should be the same for both ReservesControlBranch settings
1025     t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary');
1026     is_deeply(
1027         CanItemBeReserved( $patron, $item_3 ),
1028         { status => 'tooManyReserves', limit => 3 },
1029         'Unlimited daily holds, but reached reservesallowed'
1030     );
1031
1032     $schema->storage->txn_rollback;
1033 };
1034
1035 subtest 'CanItemBeReserved / branch_not_in_hold_group' => sub {
1036     plan tests => 9;
1037
1038     $schema->storage->txn_begin;
1039
1040     Koha::CirculationRules->set_rule(
1041         {
1042             branchcode   => undef,
1043             categorycode => undef,
1044             itemtype     => undef,
1045             rule_name    => 'reservesallowed',
1046             rule_value   => 25,
1047         }
1048     );
1049
1050     # Create item types
1051     my $itemtype1 = $builder->build_object( { class => 'Koha::ItemTypes' } );
1052     my $itemtype2 = $builder->build_object( { class => 'Koha::ItemTypes' } );
1053
1054     # Create libraries
1055     my $library1  = $builder->build_object( { class => 'Koha::Libraries' } );
1056     my $library2  = $builder->build_object( { class => 'Koha::Libraries' } );
1057     my $library3  = $builder->build_object( { class => 'Koha::Libraries' } );
1058
1059     # Create library groups hierarchy
1060     my $rootgroup  = $builder->build_object( { class => 'Koha::Library::Groups', value => {ft_local_hold_group => 1} } );
1061     my $group1  = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library1->branchcode}} );
1062     my $group2  = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library2->branchcode} } );
1063
1064     # Create 2 patrons
1065     my $patron1   = $builder->build_object( { class => 'Koha::Patrons', value => {branchcode => $library1->branchcode} } );
1066     my $patron3   = $builder->build_object( { class => 'Koha::Patrons', value => {branchcode => $library3->branchcode} } );
1067
1068     # Create 3 biblios with items
1069     my $biblio_1 = $builder->build_sample_biblio({ itemtype => $itemtype1->itemtype });
1070     my $item_1   = $builder->build_sample_item(
1071         {
1072             biblionumber => $biblio_1->biblionumber,
1073             library      => $library1->branchcode
1074         }
1075     );
1076     my $biblio_2 = $builder->build_sample_biblio({ itemtype => $itemtype2->itemtype });
1077     my $item_2   = $builder->build_sample_item(
1078         {
1079             biblionumber => $biblio_2->biblionumber,
1080             library      => $library2->branchcode
1081         }
1082     );
1083     my $itemnumber_2 = $item_2->itemnumber;
1084     my $biblio_3 = $builder->build_sample_biblio({ itemtype => $itemtype1->itemtype });
1085     my $item_3   = $builder->build_sample_item(
1086         {
1087             biblionumber => $biblio_3->biblionumber,
1088             library      => $library1->branchcode
1089         }
1090     );
1091
1092     # Test 1: Patron 3 can place hold
1093     is_deeply(
1094         CanItemBeReserved( $patron3, $item_2 ),
1095         { status => 'OK' },
1096         'Patron can place hold if no circ_rules where defined'
1097     );
1098
1099     # Insert default circ rule of holds allowed only from local hold group for all libraries
1100     Koha::CirculationRules->set_rules(
1101         {
1102             branchcode => undef,
1103             itemtype   => undef,
1104             rules => {
1105                 holdallowed => 'from_local_hold_group',
1106                 hold_fulfillment_policy => 'any',
1107                 returnbranch => 'any'
1108             }
1109         }
1110     );
1111
1112     # Test 2: Patron 1 can place hold
1113     is_deeply(
1114         CanItemBeReserved( $patron1, $item_2 ),
1115         { status => 'OK' },
1116         'Patron can place hold because patron\'s home library is part of hold group'
1117     );
1118
1119     # Test 3: Patron 3 cannot place hold
1120     is_deeply(
1121         CanItemBeReserved( $patron3, $item_2 ),
1122         { status => 'branchNotInHoldGroup' },
1123         'Patron cannot place hold because patron\'s home library is not part of hold group'
1124     );
1125
1126     # Insert default circ rule to "any" for library 2
1127     Koha::CirculationRules->set_rules(
1128         {
1129             branchcode => $library2->branchcode,
1130             itemtype   => undef,
1131             rules => {
1132                 holdallowed => 'from_any_library',
1133                 hold_fulfillment_policy => 'any',
1134                 returnbranch => 'any'
1135             }
1136         }
1137     );
1138
1139     # Test 4: Patron 3 can place hold
1140     is_deeply(
1141         CanItemBeReserved( $patron3, $item_2 ),
1142         { status => 'OK' },
1143         'Patron can place hold if holdallowed is set to "any" for library 2'
1144     );
1145
1146     # Update default circ rule to "hold group" for library 2
1147     Koha::CirculationRules->set_rules(
1148         {
1149             branchcode => $library2->branchcode,
1150             itemtype   => undef,
1151             rules => {
1152                 holdallowed => 'from_local_hold_group',
1153                 hold_fulfillment_policy => 'any',
1154                 returnbranch => 'any'
1155             }
1156         }
1157     );
1158
1159     # Test 5: Patron 3 cannot place hold
1160     is_deeply(
1161         CanItemBeReserved( $patron3, $item_2 ),
1162         { status => 'branchNotInHoldGroup' },
1163         'Patron cannot place hold if holdallowed is set to "hold group" for library 2'
1164     );
1165
1166     # Insert default item rule to "any" for itemtype 2
1167     Koha::CirculationRules->set_rules(
1168         {
1169             branchcode => $library2->branchcode,
1170             itemtype   => $itemtype2->itemtype,
1171             rules => {
1172                 holdallowed => 'from_any_library',
1173                 hold_fulfillment_policy => 'any',
1174                 returnbranch => 'any'
1175             }
1176         }
1177     );
1178
1179     # Test 6: Patron 3 can place hold
1180     is_deeply(
1181         CanItemBeReserved( $patron3, $item_2 ),
1182         { status => 'OK' },
1183         'Patron can place hold if holdallowed is set to "any" for itemtype 2'
1184     );
1185
1186     # Update default item rule to "hold group" for itemtype 2
1187     Koha::CirculationRules->set_rules(
1188         {
1189             branchcode => $library2->branchcode,
1190             itemtype   => $itemtype2->itemtype,
1191             rules => {
1192                 holdallowed => 'from_local_hold_group',
1193                 hold_fulfillment_policy => 'any',
1194                 returnbranch => 'any'
1195             }
1196         }
1197     );
1198
1199     # Test 7: Patron 3 cannot place hold
1200     is_deeply(
1201         CanItemBeReserved( $patron3, $item_2 ),
1202         { status => 'branchNotInHoldGroup' },
1203         'Patron cannot place hold if holdallowed is set to "hold group" for itemtype 2'
1204     );
1205
1206     # Insert branch item rule to "any" for itemtype 2 and library 2
1207     Koha::CirculationRules->set_rules(
1208         {
1209             branchcode => $library2->branchcode,
1210             itemtype   => $itemtype2->itemtype,
1211             rules => {
1212                 holdallowed => 'from_any_library',
1213                 hold_fulfillment_policy => 'any',
1214                 returnbranch => 'any'
1215             }
1216         }
1217     );
1218
1219     # Test 8: Patron 3 can place hold
1220     is_deeply(
1221         CanItemBeReserved( $patron3, $item_2 ),
1222         { status => 'OK' },
1223         'Patron can place hold if holdallowed is set to "any" for itemtype 2 and library 2'
1224     );
1225
1226     # Update branch item rule to "hold group" for itemtype 2 and library 2
1227     Koha::CirculationRules->set_rules(
1228         {
1229             branchcode => $library2->branchcode,
1230             itemtype   => $itemtype2->itemtype,
1231             rules => {
1232                 holdallowed => 'from_local_hold_group',
1233                 hold_fulfillment_policy => 'any',
1234                 returnbranch => 'any'
1235             }
1236         }
1237     );
1238
1239     # Test 9: Patron 3 cannot place hold
1240     is_deeply(
1241         CanItemBeReserved( $patron3, $item_2 ),
1242         { status => 'branchNotInHoldGroup' },
1243         'Patron cannot place hold if holdallowed is set to "hold group" for itemtype 2 and library 2'
1244     );
1245
1246     $schema->storage->txn_rollback;
1247
1248 };
1249
1250 subtest 'CanItemBeReserved / pickup_not_in_hold_group' => sub {
1251     plan tests => 9;
1252
1253     $schema->storage->txn_begin;
1254     Koha::CirculationRules->set_rule(
1255         {
1256             branchcode   => undef,
1257             categorycode => undef,
1258             itemtype     => undef,
1259             rule_name    => 'reservesallowed',
1260             rule_value   => 25,
1261         }
1262     );
1263
1264     # Create item types
1265     my $itemtype1 = $builder->build_object( { class => 'Koha::ItemTypes' } );
1266     my $itemtype2 = $builder->build_object( { class => 'Koha::ItemTypes' } );
1267
1268     # Create libraries
1269     my $library1  = $builder->build_object( { class => 'Koha::Libraries', value => {pickup_location => 1} } );
1270     my $library2  = $builder->build_object( { class => 'Koha::Libraries', value => {pickup_location => 1} } );
1271     my $library3  = $builder->build_object( { class => 'Koha::Libraries', value => {pickup_location => 1} } );
1272
1273     # Create library groups hierarchy
1274     my $rootgroup  = $builder->build_object( { class => 'Koha::Library::Groups', value => {ft_local_hold_group => 1} } );
1275     my $group1  = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library1->branchcode}} );
1276     my $group2  = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library2->branchcode} } );
1277
1278     # Create 2 patrons
1279     my $patron1   = $builder->build_object( { class => 'Koha::Patrons', value => {branchcode => $library1->branchcode} } );
1280     my $patron3   = $builder->build_object( { class => 'Koha::Patrons', value => {branchcode => $library3->branchcode} } );
1281
1282     # Create 3 biblios with items
1283     my $biblio_1 = $builder->build_sample_biblio({ itemtype => $itemtype1->itemtype });
1284     my $item_1   = $builder->build_sample_item(
1285         {
1286             biblionumber => $biblio_1->biblionumber,
1287             library      => $library1->branchcode
1288         }
1289     );
1290     my $biblio_2 = $builder->build_sample_biblio({ itemtype => $itemtype2->itemtype });
1291     my $item_2   = $builder->build_sample_item(
1292         {
1293             biblionumber => $biblio_2->biblionumber,
1294             library      => $library2->branchcode
1295         }
1296     );
1297     my $itemnumber_2 = $item_2->itemnumber;
1298     my $biblio_3 = $builder->build_sample_biblio({ itemtype => $itemtype1->itemtype });
1299     my $item_3   = $builder->build_sample_item(
1300         {
1301             biblionumber => $biblio_3->biblionumber,
1302             library      => $library1->branchcode
1303         }
1304     );
1305
1306     # Test 1: Patron 3 can place hold
1307     is_deeply(
1308         CanItemBeReserved( $patron3, $item_2, $library3->branchcode ),
1309         { status => 'OK' },
1310         'Patron can place hold if no circ_rules where defined'
1311     );
1312
1313     # Insert default circ rule of holds allowed only from local hold group for all libraries
1314     Koha::CirculationRules->set_rules(
1315         {
1316             branchcode => undef,
1317             itemtype   => undef,
1318             rules => {
1319                 holdallowed => 'from_any_library',
1320                 hold_fulfillment_policy => 'holdgroup',
1321                 returnbranch => 'any'
1322             }
1323         }
1324     );
1325
1326     # Test 2: Patron 1 can place hold
1327     is_deeply(
1328         CanItemBeReserved( $patron3, $item_2, $library1->branchcode ),
1329         { status => 'OK' },
1330         'Patron can place hold because pickup location is part of hold group'
1331     );
1332
1333     # Test 3: Patron 3 cannot place hold
1334     is_deeply(
1335         CanItemBeReserved( $patron3, $item_2, $library3->branchcode ),
1336         { status => 'pickupNotInHoldGroup' },
1337         'Patron cannot place hold because pickup location is not part of hold group'
1338     );
1339
1340     # Insert default circ rule to "any" for library 2
1341     Koha::CirculationRules->set_rules(
1342         {
1343             branchcode => $library2->branchcode,
1344             itemtype   => undef,
1345             rules => {
1346                 holdallowed => 'from_any_library',
1347                 hold_fulfillment_policy => 'any',
1348                 returnbranch => 'any'
1349             }
1350         }
1351     );
1352
1353     # Test 4: Patron 3 can place hold
1354     is_deeply(
1355         CanItemBeReserved( $patron3, $item_2, $library3->branchcode ),
1356         { status => 'OK' },
1357         'Patron can place hold if default_branch_circ_rules is set to "any" for library 2'
1358     );
1359
1360     # Update default circ rule to "hold group" for library 2
1361     Koha::CirculationRules->set_rules(
1362         {
1363             branchcode => $library2->branchcode,
1364             itemtype   => undef,
1365             rules => {
1366                 holdallowed => 'from_any_library',
1367                 hold_fulfillment_policy => 'holdgroup',
1368                 returnbranch => 'any'
1369             }
1370         }
1371     );
1372
1373     # Test 5: Patron 3 cannot place hold
1374     is_deeply(
1375         CanItemBeReserved( $patron3, $item_2, $library3->branchcode ),
1376         { status => 'pickupNotInHoldGroup' },
1377         'Patron cannot place hold if hold_fulfillment_policy is set to "hold group" for library 2'
1378     );
1379
1380     # Insert default item rule to "any" for itemtype 2
1381     Koha::CirculationRules->set_rules(
1382         {
1383             branchcode => $library2->branchcode,
1384             itemtype   => $itemtype2->itemtype,
1385             rules => {
1386                 holdallowed => 'from_any_library',
1387                 hold_fulfillment_policy => 'any',
1388                 returnbranch => 'any'
1389             }
1390         }
1391     );
1392
1393     # Test 6: Patron 3 can place hold
1394     is_deeply(
1395         CanItemBeReserved( $patron3, $item_2, $library3->branchcode ),
1396         { status => 'OK' },
1397         'Patron can place hold if hold_fulfillment_policy is set to "any" for itemtype 2'
1398     );
1399
1400     # Update default item rule to "hold group" for itemtype 2
1401     Koha::CirculationRules->set_rules(
1402         {
1403             branchcode => $library2->branchcode,
1404             itemtype   => $itemtype2->itemtype,
1405             rules => {
1406                 holdallowed => 'from_any_library',
1407                 hold_fulfillment_policy => 'holdgroup',
1408                 returnbranch => 'any'
1409             }
1410         }
1411     );
1412
1413     # Test 7: Patron 3 cannot place hold
1414     is_deeply(
1415         CanItemBeReserved( $patron3, $item_2, $library3->branchcode ),
1416         { status => 'pickupNotInHoldGroup' },
1417         'Patron cannot place hold if hold_fulfillment_policy is set to "hold group" for itemtype 2'
1418     );
1419
1420     # Insert branch item rule to "any" for itemtype 2 and library 2
1421     Koha::CirculationRules->set_rules(
1422         {
1423             branchcode => $library2->branchcode,
1424             itemtype   => $itemtype2->itemtype,
1425             rules => {
1426                 holdallowed => 'from_any_library',
1427                 hold_fulfillment_policy => 'any',
1428                 returnbranch => 'any'
1429             }
1430         }
1431     );
1432
1433     # Test 8: Patron 3 can place hold
1434     is_deeply(
1435         CanItemBeReserved( $patron3, $item_2, $library3->branchcode ),
1436         { status => 'OK' },
1437         'Patron can place hold if hold_fulfillment_policy is set to "any" for itemtype 2 and library 2'
1438     );
1439
1440     # Update branch item rule to "hold group" for itemtype 2 and library 2
1441     Koha::CirculationRules->set_rules(
1442         {
1443             branchcode => $library2->branchcode,
1444             itemtype   => $itemtype2->itemtype,
1445             rules => {
1446                 holdallowed => 'from_any_library',
1447                 hold_fulfillment_policy => 'holdgroup',
1448                 returnbranch => 'any'
1449             }
1450         }
1451     );
1452
1453     # Test 9: Patron 3 cannot place hold
1454     is_deeply(
1455         CanItemBeReserved( $patron3, $item_2, $library3->branchcode ),
1456         { status => 'pickupNotInHoldGroup' },
1457         'Patron cannot place hold if hold_fulfillment_policy is set to "hold group" for itemtype 2 and library 2'
1458     );
1459
1460     $schema->storage->txn_rollback;
1461 };
1462
1463 subtest 'non priority holds' => sub {
1464
1465     plan tests => 6;
1466
1467     $schema->storage->txn_begin;
1468
1469     Koha::CirculationRules->set_rules(
1470         {
1471             branchcode   => undef,
1472             categorycode => undef,
1473             itemtype     => undef,
1474             rules        => {
1475                 renewalsallowed => 5,
1476                 reservesallowed => 5,
1477             }
1478         }
1479     );
1480
1481     my $item = $builder->build_sample_item;
1482
1483     my $patron1 = $builder->build_object(
1484         {
1485             class => 'Koha::Patrons',
1486             value => { branchcode => $item->homebranch }
1487         }
1488     );
1489     my $patron2 = $builder->build_object(
1490         {
1491             class => 'Koha::Patrons',
1492             value => { branchcode => $item->homebranch }
1493         }
1494     );
1495
1496     Koha::Checkout->new(
1497         {
1498             borrowernumber => $patron1->borrowernumber,
1499             itemnumber     => $item->itemnumber,
1500             branchcode     => $item->homebranch
1501         }
1502     )->store;
1503
1504     my $hid = AddReserve(
1505         {
1506             branchcode     => $item->homebranch,
1507             borrowernumber => $patron2->borrowernumber,
1508             biblionumber   => $item->biblionumber,
1509             priority       => 1,
1510             itemnumber     => $item->itemnumber,
1511         }
1512     );
1513
1514     my ( $ok, $err ) =
1515       CanBookBeRenewed( $patron1->borrowernumber, $item->itemnumber );
1516
1517     ok( !$ok, 'Cannot renew' );
1518     is( $err, 'on_reserve', 'Item is on hold' );
1519
1520     my $hold = Koha::Holds->find($hid);
1521     $hold->non_priority(1)->store;
1522
1523     ( $ok, $err ) =
1524       CanBookBeRenewed( $patron1->borrowernumber, $item->itemnumber );
1525
1526     ok( $ok, 'Can renew' );
1527     is( $err, undef, 'Item is on non priority hold' );
1528
1529     my $patron3 = $builder->build_object(
1530         {
1531             class => 'Koha::Patrons',
1532             value => { branchcode => $item->homebranch }
1533         }
1534     );
1535
1536     # Add second hold with non_priority = 0
1537     AddReserve(
1538         {
1539             branchcode     => $item->homebranch,
1540             borrowernumber => $patron3->borrowernumber,
1541             biblionumber   => $item->biblionumber,
1542             priority       => 2,
1543             itemnumber     => $item->itemnumber,
1544         }
1545     );
1546
1547     ( $ok, $err ) =
1548       CanBookBeRenewed( $patron1->borrowernumber, $item->itemnumber );
1549
1550     ok( !$ok, 'Cannot renew' );
1551     is( $err, 'on_reserve', 'Item is on hold' );
1552
1553     $schema->storage->txn_rollback;
1554 };
1555
1556 subtest 'CanItemBeReserved / recall' => sub {
1557     plan tests => 1;
1558
1559     $schema->storage->txn_begin;
1560
1561     my $itemtype1 = $builder->build_object( { class => 'Koha::ItemTypes' } );
1562     my $library1  = $builder->build_object( { class => 'Koha::Libraries', value => {pickup_location => 1} } );
1563     my $patron1   = $builder->build_object( { class => 'Koha::Patrons', value => {branchcode => $library1->branchcode} } );
1564     my $biblio1 = $builder->build_sample_biblio({ itemtype => $itemtype1->itemtype });
1565     my $item1   = $builder->build_sample_item(
1566         {
1567             biblionumber => $biblio1->biblionumber,
1568             library      => $library1->branchcode
1569         }
1570     );
1571     Koha::Recall->new({
1572         patron_id => $patron1->borrowernumber,
1573         biblio_id => $biblio1->biblionumber,
1574         pickup_library_id => $library1->branchcode,
1575         item_id => $item1->itemnumber,
1576         created_date => '2020-05-04 10:10:10',
1577         item_level => 1,
1578     })->store;
1579     is( CanItemBeReserved( $patron1, $item1, $library1->branchcode )->{status}, 'recall', "Can't reserve an item that they have already recalled" );
1580
1581     $schema->storage->txn_rollback;
1582 };
1583
1584 subtest 'CanItemBeReserved rule precedence tests' => sub {
1585
1586     plan tests => 3;
1587
1588     t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary');
1589     $schema->storage->txn_begin;
1590     my $library  = $builder->build_object( { class => 'Koha::Libraries', value => {
1591         pickup_location => 1,
1592     }});
1593     my $item = $builder->build_sample_item({
1594         homebranch    => $library->branchcode,
1595         holdingbranch => $library->branchcode
1596     });
1597     my $item2 = $builder->build_sample_item({
1598         homebranch    => $library->branchcode,
1599         holdingbranch => $library->branchcode,
1600         itype         => $item->itype
1601     });
1602     my $patron   = $builder->build_object({ class => 'Koha::Patrons', value => {
1603         branchcode => $library->branchcode
1604     }});
1605     Koha::CirculationRules->set_rules(
1606         {
1607             branchcode   => undef,
1608             categorycode => $patron->categorycode,
1609             itemtype     => $item->itype,
1610             rules        => {
1611                 reservesallowed  => 1,
1612             }
1613         }
1614     );
1615     is_deeply(
1616         CanItemBeReserved( $patron, $item, $library->branchcode ),
1617         { status => 'OK' },
1618         'Patron of specified category can place 1 hold on specified itemtype'
1619     );
1620     my $hold = $builder->build_object({ class => 'Koha::Holds', value => {
1621         biblionumber   => $item2->biblionumber,
1622         itemnumber     => $item2->itemnumber,
1623         found          => undef,
1624         priority       => 1,
1625         branchcode     => $library->branchcode,
1626         borrowernumber => $patron->borrowernumber,
1627     }});
1628     is_deeply(
1629         CanItemBeReserved( $patron, $item, $library->branchcode ),
1630         { status => 'tooManyReserves', limit => 1 },
1631         'Patron of specified category can place 1 hold on specified itemtype, cannot place a second'
1632     );
1633     Koha::CirculationRules->set_rules(
1634         {
1635             branchcode   => $library->branchcode,
1636             categorycode => undef,
1637             itemtype     => undef,
1638             rules        => {
1639                 reservesallowed  => 2,
1640             }
1641         }
1642     );
1643     is_deeply(
1644         CanItemBeReserved( $patron, $item, $library->branchcode ),
1645         { status => 'OK' },
1646         'Patron of specified category can place 1 hold on specified itemtype if library rule for all types and categories set to 2'
1647     );
1648
1649     $schema->storage->txn_rollback;
1650
1651 };
1652
1653 subtest 'ModReserve can only update expirationdate for found holds' => sub {
1654     plan tests => 2;
1655
1656     $schema->storage->txn_begin;
1657
1658     my $category = $builder->build({ source => 'Category' });
1659     my $branch = $builder->build({ source => 'Branch' })->{ branchcode };
1660     my $biblio = $builder->build_sample_biblio( { itemtype => 'DUMMY' } );
1661     my $itemnumber = $builder->build_sample_item(
1662         { library => $branch, biblionumber => $biblio->biblionumber } )
1663       ->itemnumber;
1664
1665     my $borrowernumber = Koha::Patron->new(
1666         {
1667             firstname    => 'my firstname',
1668             surname      => 'whatever surname',
1669             categorycode => $category->{categorycode},
1670             branchcode   => $branch,
1671         }
1672     )->store->borrowernumber;
1673
1674     my $reserve_id = AddReserve(
1675         {
1676             branchcode     => $branch,
1677             borrowernumber => $borrowernumber,
1678             biblionumber   => $biblio->biblionumber,
1679             priority       =>
1680               C4::Reserves::CalculatePriority( $biblio->biblionumber ),
1681             itemnumber => $itemnumber,
1682         }
1683     );
1684
1685     my $hold = Koha::Holds->find($reserve_id);
1686
1687     $hold->set( { priority => 0, found => 'W' } )->store();
1688
1689     ModReserve(
1690         {
1691             reserve_id     => $hold->id,
1692             expirationdate => '1981-06-10',
1693             priority       => 99,
1694             rank           => 0,
1695         }
1696     );
1697
1698     $hold = Koha::Holds->find($reserve_id);
1699
1700     is( $hold->expirationdate, '1981-06-10',
1701         'Found hold expiration date updated correctly' );
1702     is( $hold->priority, '0', 'Found hold priority was not updated' );
1703
1704     $schema->storage->txn_rollback;
1705
1706 };
1707
1708 subtest 'Koha::Holds->get_items_that_can_fill returns items with datecancelled or (inclusive) datearrived' => sub {
1709     plan tests => 8;
1710     # biblio item with date arrived and date cancelled
1711     my $biblio1 = $builder->build_sample_biblio();
1712     my $item1 = $builder->build_sample_item({ biblionumber => $biblio1->biblionumber });
1713
1714     my $transfer1 = $builder->build_object({ class => "Koha::Item::Transfers", value => {
1715         datecancelled => '2022-06-12',
1716         itemnumber => $item1->itemnumber
1717     }});
1718
1719     my $hold1 = $builder->build_object({ class => 'Koha::Holds', value => {
1720         biblionumber => $biblio1->biblionumber,
1721         itemnumber => undef,
1722         itemtype => undef,
1723         found => undef
1724     }});
1725
1726     # biblio item with date arrived and NO date cancelled
1727     my $biblio2 = $builder->build_sample_biblio();
1728     my $item2 = $builder->build_sample_item({ biblionumber => $biblio2->biblionumber });
1729
1730     my $transfer2 = $builder->build_object({ class => "Koha::Item::Transfers", value => {
1731         datecancelled => undef,
1732         itemnumber => $item2->itemnumber
1733     }});
1734
1735     my $hold2 = $builder->build_object({ class => 'Koha::Holds', value => {
1736         biblionumber => $biblio2->biblionumber,
1737         itemnumber => undef,
1738         itemtype => undef,
1739         found => undef
1740     }});
1741
1742     # biblio item with NO date arrived and date cancelled
1743     my $biblio3 = $builder->build_sample_biblio();
1744     my $item3 = $builder->build_sample_item({ biblionumber => $biblio3->biblionumber });
1745
1746     my $transfer3 = $builder->build_object({ class => "Koha::Item::Transfers", value => {
1747         datecancelled => '2022-06-12',
1748         itemnumber => $item3->itemnumber,
1749         datearrived => undef
1750     }});
1751
1752     my $hold3 = $builder->build_object({ class => 'Koha::Holds', value => {
1753         biblionumber => $biblio3->biblionumber,
1754         itemnumber => undef,
1755         itemtype => undef,
1756         found => undef
1757     }});
1758
1759
1760     # biblio item with NO date arrived and NO date cancelled
1761     my $biblio4 = $builder->build_sample_biblio();
1762     my $item4 = $builder->build_sample_item({ biblionumber => $biblio4->biblionumber });
1763
1764     my $transfer4 = $builder->build_object({ class => "Koha::Item::Transfers", value => {
1765         datecancelled => undef,
1766         itemnumber => $item4->itemnumber,
1767         datearrived => undef
1768     }});
1769
1770     my $hold4 = $builder->build_object({ class => 'Koha::Holds', value => {
1771         biblionumber => $biblio4->biblionumber,
1772         itemnumber => undef,
1773         itemtype => undef,
1774         found => undef
1775     }});
1776
1777     # create the holds which get_items_that_can_fill will be ran on
1778     my $holds1 = Koha::Holds->search({reserve_id => $hold1->id});
1779     my $holds2 = Koha::Holds->search({reserve_id => $hold2->id});
1780     my $holds3 = Koha::Holds->search({reserve_id => $hold3->id});
1781     my $holds4 = Koha::Holds->search({reserve_id => $hold4->id});
1782
1783     my $items_that_can_fill1 = $holds1->get_items_that_can_fill;
1784     my $items_that_can_fill2 = $holds2->get_items_that_can_fill;
1785     my $items_that_can_fill3 = $holds3->get_items_that_can_fill;
1786     my $items_that_can_fill4 = $holds4->get_items_that_can_fill;
1787
1788     is($items_that_can_fill1->next->id, $item1->id, "Koha::Holds->get_items_that_can_fill returns item with defined datearrived and datecancelled");
1789     is($items_that_can_fill1->count, 1, "Koha::Holds->get_items_that_can_fill returns 1 item with correct parameters");
1790     is($items_that_can_fill2->next->id, $item2->id, "Koha::Holds->get_items_that_can_fill returns item with defined datearrived and undefined datecancelled");
1791     is($items_that_can_fill2->count, 1, "Koha::Holds->get_items_that_can_fill returns 1 item with correct parameters");
1792     is($items_that_can_fill3->next->id, $item3->id, "Koha::Holds->get_items_that_can_fill returns item with undefined datearrived and defined datecancelled");
1793     is($items_that_can_fill3->count, 1, "Koha::Holds->get_items_that_can_fill returns 1 item with correct parameters");
1794     is($items_that_can_fill4->next, undef, "Koha::Holds->get_items_that_can_fill doesn't return item with undefined datearrived and undefined datecancelled");
1795     is($items_that_can_fill4->count, 0, "Koha::Holds->get_items_that_can_fill returns 0 item");
1796 }