Bug 25850: Add tests for weekday holidays
[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 => 62;
11 use MARC::Record;
12
13 use C4::Biblio;
14 use C4::Calendar;
15 use C4::Items;
16 use C4::Reserves;
17
18 use Koha::Biblios;
19 use Koha::CirculationRules;
20 use Koha::Database;
21 use Koha::DateUtils qw( dt_from_string output_pref );
22 use Koha::Holds;
23 use Koha::IssuingRules;
24 use Koha::Item::Transfer::Limits;
25 use Koha::Items;
26 use Koha::Libraries;
27 use Koha::Patrons;
28
29 BEGIN {
30     use FindBin;
31     use lib $FindBin::Bin;
32 }
33
34 my $schema  = Koha::Database->new->schema;
35 $schema->storage->txn_begin;
36
37 my $builder = t::lib::TestBuilder->new();
38 my $dbh     = C4::Context->dbh;
39
40 # Create two random branches
41 my $branch_1 = $builder->build({ source => 'Branch' })->{ branchcode };
42 my $branch_2 = $builder->build({ source => 'Branch' })->{ branchcode };
43
44 my $category = $builder->build({ source => 'Category' });
45
46 my $borrowers_count = 5;
47
48 $dbh->do('DELETE FROM itemtypes');
49 $dbh->do('DELETE FROM reserves');
50 $dbh->do('DELETE FROM circulation_rules');
51 my $insert_sth = $dbh->prepare('INSERT INTO itemtypes (itemtype) VALUES (?)');
52 $insert_sth->execute('CAN');
53 $insert_sth->execute('CANNOT');
54 $insert_sth->execute('DUMMY');
55 $insert_sth->execute('ONLY1');
56
57 # Setup Test------------------------
58 my $biblio = $builder->build_sample_biblio({ itemtype => 'DUMMY' });
59
60 # Create item instance for testing.
61 my ($item_bibnum, $item_bibitemnum, $itemnumber)
62     = AddItem({ homebranch => $branch_1, holdingbranch => $branch_1 } , $biblio->biblionumber);
63
64 # Create some borrowers
65 my @borrowernumbers;
66 foreach (1..$borrowers_count) {
67     my $borrowernumber = Koha::Patron->new({
68         firstname =>  'my firstname',
69         surname => 'my surname ' . $_,
70         categorycode => $category->{categorycode},
71         branchcode => $branch_1,
72     })->store->borrowernumber;
73     push @borrowernumbers, $borrowernumber;
74 }
75
76 # Create five item level holds
77 foreach my $borrowernumber ( @borrowernumbers ) {
78     AddReserve(
79         $branch_1,
80         $borrowernumber,
81         $biblio->biblionumber,
82         my $bibitems = q{},
83         my $priority = C4::Reserves::CalculatePriority( $biblio->biblionumber ),
84         my $resdate,
85         my $expdate,
86         my $notes = q{},
87         'a title',
88         my $checkitem = $itemnumber,
89         my $found,
90     );
91 }
92
93 my $holds = $biblio->holds;
94 is( $holds->count, $borrowers_count, 'Test GetReserves()' );
95 is( $holds->next->priority, 1, "Reserve 1 has a priority of 1" );
96 is( $holds->next->priority, 2, "Reserve 2 has a priority of 2" );
97 is( $holds->next->priority, 3, "Reserve 3 has a priority of 3" );
98 is( $holds->next->priority, 4, "Reserve 4 has a priority of 4" );
99 is( $holds->next->priority, 5, "Reserve 5 has a priority of 5" );
100
101 my $item = Koha::Items->find( $itemnumber );
102 $holds = $item->current_holds;
103 my $first_hold = $holds->next;
104 my $reservedate = $first_hold->reservedate;
105 my $borrowernumber = $first_hold->borrowernumber;
106 my $branch_1code = $first_hold->branchcode;
107 my $reserve_id = $first_hold->reserve_id;
108 is( $reservedate, output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }), "holds_placed_today should return a valid reserve date");
109 is( $borrowernumber, $borrowernumbers[0], "holds_placed_today should return a valid borrowernumber");
110 is( $branch_1code, $branch_1, "holds_placed_today should return a valid branchcode");
111 ok($reserve_id, "Test holds_placed_today()");
112
113 my $hold = Koha::Holds->find( $reserve_id );
114 ok( $hold, "Koha::Holds found the hold" );
115 my $hold_biblio = $hold->biblio();
116 ok( $hold_biblio, "Got biblio using biblio() method" );
117 ok( $hold_biblio == $hold->biblio(), "biblio method returns stashed biblio" );
118 my $hold_item = $hold->item();
119 ok( $hold_item, "Got item using item() method" );
120 ok( $hold_item == $hold->item(), "item method returns stashed item" );
121 my $hold_branch = $hold->branch();
122 ok( $hold_branch, "Got branch using branch() method" );
123 ok( $hold_branch == $hold->branch(), "branch method returns stashed branch" );
124 my $hold_found = $hold->found();
125 $hold->set({ found => 'W'})->store();
126 is( Koha::Holds->waiting()->count(), 1, "Koha::Holds->waiting returns waiting holds" );
127 is( Koha::Holds->unfilled()->count(), 4, "Koha::Holds->unfilled returns unfilled holds" );
128
129 my $patron = Koha::Patrons->find( $borrowernumbers[0] );
130 $holds = $patron->holds;
131 is( $holds->next->borrowernumber, $borrowernumbers[0], "Test Koha::Patron->holds");
132
133
134 $holds = $item->current_holds;
135 $first_hold = $holds->next;
136 $borrowernumber = $first_hold->borrowernumber;
137 $branch_1code = $first_hold->branchcode;
138 $reserve_id = $first_hold->reserve_id;
139
140 ModReserve({
141     reserve_id    => $reserve_id,
142     rank          => '4',
143     branchcode    => $branch_1,
144     itemnumber    => $itemnumber,
145     suspend_until => output_pref( { dt => dt_from_string( "2013-01-01", "iso" ), dateonly => 1 } ),
146 });
147
148 $hold = Koha::Holds->find( $reserve_id );
149 ok( $hold->priority eq '4', "Test ModReserve, priority changed correctly" );
150 ok( $hold->suspend, "Test ModReserve, suspend hold" );
151 is( $hold->suspend_until, '2013-01-01 00:00:00', "Test ModReserve, suspend until date" );
152
153 ModReserve({ # call without reserve_id
154     rank          => '3',
155     biblionumber  => $item_bibnum,
156     itemnumber    => $itemnumber,
157     borrowernumber => $borrowernumber,
158 });
159 $hold = Koha::Holds->find( $reserve_id );
160 ok( $hold->priority eq '3', "Test ModReserve, priority changed correctly" );
161
162 ToggleSuspend( $reserve_id );
163 $hold = Koha::Holds->find( $reserve_id );
164 ok( ! $hold->suspend, "Test ToggleSuspend(), no date" );
165
166 ToggleSuspend( $reserve_id, '2012-01-01' );
167 $hold = Koha::Holds->find( $reserve_id );
168 is( $hold->suspend_until, '2012-01-01 00:00:00', "Test ToggleSuspend(), with date" );
169
170 AutoUnsuspendReserves();
171 $hold = Koha::Holds->find( $reserve_id );
172 ok( ! $hold->suspend, "Test AutoUnsuspendReserves()" );
173
174 SuspendAll(
175     borrowernumber => $borrowernumber,
176     biblionumber   => $biblio->biblionumber,
177     suspend => 1,
178     suspend_until => '2012-01-01',
179 );
180 $hold = Koha::Holds->find( $reserve_id );
181 is( $hold->suspend, 1, "Test SuspendAll()" );
182 is( $hold->suspend_until, '2012-01-01 00:00:00', "Test SuspendAll(), with date" );
183
184 SuspendAll(
185     borrowernumber => $borrowernumber,
186     biblionumber   => $biblio->biblionumber,
187     suspend => 0,
188 );
189 $hold = Koha::Holds->find( $reserve_id );
190 is( $hold->suspend, 0, "Test resuming with SuspendAll()" );
191 is( $hold->suspend_until, undef, "Test resuming with SuspendAll(), should have no suspend until date" );
192
193 # Add a new hold for the borrower whose hold we canceled earlier, this time at the bib level
194 AddReserve(
195     $branch_1,
196     $borrowernumbers[0],
197     $biblio->biblionumber,
198     my $bibitems = q{},
199     my $priority,
200     my $resdate,
201     my $expdate,
202     my $notes = q{},
203     'a title',
204     my $checkitem,
205     my $found,
206 );
207 $patron = Koha::Patrons->find( $borrowernumber );
208 $holds = $patron->holds;
209 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $borrowernumbers[0] })->next->reserve_id;
210 ModReserveMinusPriority( $itemnumber, $reserveid );
211 $holds = $patron->holds;
212 is( $holds->next->itemnumber, $itemnumber, "Test ModReserveMinusPriority()" );
213
214 $holds = $biblio->holds;
215 $hold = $holds->next;
216 AlterPriority( 'top', $hold->reserve_id, undef, 2, 1, 6 );
217 $hold = Koha::Holds->find( $reserveid );
218 is( $hold->priority, '1', "Test AlterPriority(), move to top" );
219
220 AlterPriority( 'down', $hold->reserve_id, undef, 2, 1, 6 );
221 $hold = Koha::Holds->find( $reserveid );
222 is( $hold->priority, '2', "Test AlterPriority(), move down" );
223
224 AlterPriority( 'up', $hold->reserve_id, 1, 3, 1, 6 );
225 $hold = Koha::Holds->find( $reserveid );
226 is( $hold->priority, '1', "Test AlterPriority(), move up" );
227
228 AlterPriority( 'bottom', $hold->reserve_id, undef, 2, 1, 6 );
229 $hold = Koha::Holds->find( $reserveid );
230 is( $hold->priority, '6', "Test AlterPriority(), move to bottom" );
231
232 # Regression test for bug 2394
233 #
234 # If IndependentBranches is ON and canreservefromotherbranches is OFF,
235 # a patron is not permittedo to request an item whose homebranch (i.e.,
236 # owner of the item) is different from the patron's own library.
237 # However, if canreservefromotherbranches is turned ON, the patron can
238 # create such hold requests.
239 #
240 # Note that canreservefromotherbranches has no effect if
241 # IndependentBranches is OFF.
242
243 my $foreign_biblio = $builder->build_sample_biblio({ itemtype => 'DUMMY' });
244 my ($foreign_item_bibnum, $foreign_item_bibitemnum, $foreign_itemnumber)
245   = AddItem({ homebranch => $branch_2, holdingbranch => $branch_2 } , $foreign_biblio->biblionumber);
246 $dbh->do('DELETE FROM issuingrules');
247 $dbh->do(
248     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed, holds_per_record)
249       VALUES (?, ?, ?, ?, ?)},
250     {},
251     '*', '*', '*', 25, 99
252 );
253 $dbh->do(
254     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed, holds_per_record)
255       VALUES (?, ?, ?, ?, ?)},
256     {},
257     '*', '*', 'CANNOT', 0, 99
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 ok(
267     CanItemBeReserved($borrowernumbers[0], $foreign_itemnumber)->{status} eq 'OK',
268     '$branch_1 patron allowed to reserve $branch_2 item with IndependentBranches OFF (bug 2394)'
269 );
270
271 # if IndependentBranches is OFF, a $branch_1 patron cannot reserve an $branch_2 item
272 t::lib::Mocks::mock_preference('IndependentBranches', 1);
273 t::lib::Mocks::mock_preference('canreservefromotherbranches', 0);
274 ok(
275     CanItemBeReserved($borrowernumbers[0], $foreign_itemnumber)->{status} eq 'cannotReserveFromOtherBranches',
276     '$branch_1 patron NOT allowed to reserve $branch_2 item with IndependentBranches ON ... (bug 2394)'
277 );
278
279 # ... unless canreservefromotherbranches is ON
280 t::lib::Mocks::mock_preference('canreservefromotherbranches', 1);
281 ok(
282     CanItemBeReserved($borrowernumbers[0], $foreign_itemnumber)->{status} eq 'OK',
283     '... unless canreservefromotherbranches is ON (bug 2394)'
284 );
285
286 {
287     # Regression test for bug 11336 # Test if ModReserve correctly recalculate the priorities
288     $biblio = $builder->build_sample_biblio({ itemtype => 'DUMMY' });
289     ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $branch_1, holdingbranch => $branch_1 } , $biblio->biblionumber);
290     my $reserveid1 = AddReserve($branch_1, $borrowernumbers[0], $biblio->biblionumber, '', 1);
291     ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $branch_1, holdingbranch => $branch_1 } , $biblio->biblionumber);
292     my $reserveid2 = AddReserve($branch_1, $borrowernumbers[1], $biblio->biblionumber, '', 2);
293     ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $branch_1, holdingbranch => $branch_1 } , $biblio->biblionumber);
294     my $reserveid3 = AddReserve($branch_1, $borrowernumbers[2], $biblio->biblionumber, '', 3);
295     my $hhh = Koha::Holds->search({ biblionumber => $biblio->biblionumber });
296     my $hold3 = Koha::Holds->find( $reserveid3 );
297     is( $hold3->priority, 3, "The 3rd hold should have a priority set to 3" );
298     ModReserve({ reserve_id => $reserveid1, rank => 'del' });
299     ModReserve({ reserve_id => $reserveid2, rank => 'del' });
300     is( $hold3->discard_changes->priority, 1, "After ModReserve, the 3rd reserve becomes the first on the waiting list" );
301 }
302
303 ModItem({ damaged => 1 }, $item_bibnum, $itemnumber);
304 t::lib::Mocks::mock_preference( 'AllowHoldsOnDamagedItems', 1 );
305 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber)->{status}, 'OK', "Patron can reserve damaged item with AllowHoldsOnDamagedItems enabled" );
306 ok( defined( ( CheckReserves($itemnumber) )[1] ), "Hold can be trapped for damaged item with AllowHoldsOnDamagedItems enabled" );
307
308 $hold = Koha::Hold->new(
309     {
310         borrowernumber => $borrowernumbers[0],
311         itemnumber     => $itemnumber,
312         biblionumber   => $item_bibnum,
313     }
314 )->store();
315 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber )->{status},
316     'itemAlreadyOnHold',
317     "Patron cannot place a second item level hold for a given item" );
318 $hold->delete();
319
320 t::lib::Mocks::mock_preference( 'AllowHoldsOnDamagedItems', 0 );
321 ok( CanItemBeReserved( $borrowernumbers[0], $itemnumber)->{status} eq 'damaged', "Patron cannot reserve damaged item with AllowHoldsOnDamagedItems disabled" );
322 ok( !defined( ( CheckReserves($itemnumber) )[1] ), "Hold cannot be trapped for damaged item with AllowHoldsOnDamagedItems disabled" );
323
324 # Items that are not for loan, but holdable should not be trapped until they are available for loan
325 t::lib::Mocks::mock_preference( 'TrapHoldsOnOrder', 0 );
326 Koha::Items->find($itemnumber)->damaged(0)->notforloan(-1)->store;
327 Koha::Holds->search({ biblionumber => $biblio->id })->delete();
328 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber)->{status}, 'OK', "Patron can place hold on item that is not for loan but holdable ( notforloan < 0 )" );
329 $hold = Koha::Hold->new(
330     {
331         borrowernumber => $borrowernumbers[0],
332         itemnumber     => $itemnumber,
333         biblionumber   => $biblio->biblionumber,
334         found          => undef,
335         priority       => 1,
336         reservedate    => dt_from_string,
337         branchcode     => $branch_1,
338     }
339 )->store();
340 ok( !defined( ( CheckReserves($itemnumber) )[1] ), "Hold cannot be trapped for item that is not for loan but holdable ( notforloan < 0 )" );
341 t::lib::Mocks::mock_preference( 'TrapHoldsOnOrder', 1 );
342 ok( defined( ( CheckReserves($itemnumber) )[1] ), "Hold is trapped for item that is not for loan but holdable ( notforloan < 0 )" );
343 $hold->delete();
344
345 # Regression test for bug 9532
346 $biblio = $builder->build_sample_biblio({ itemtype => 'CANNOT' });
347 ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $branch_1, holdingbranch => $branch_1, itype => 'CANNOT' } , $biblio->biblionumber);
348 AddReserve(
349     $branch_1,
350     $borrowernumbers[0],
351     $biblio->biblionumber,
352     '',
353     1,
354 );
355 is(
356     CanItemBeReserved( $borrowernumbers[0], $itemnumber)->{status}, 'tooManyReserves',
357     "cannot request item if policy that matches on item-level item type forbids it"
358 );
359 ModItem({ itype => 'CAN' }, $item_bibnum, $itemnumber);
360 ok(
361     CanItemBeReserved( $borrowernumbers[0], $itemnumber)->{status} eq 'OK',
362     "can request item if policy that matches on item type allows it"
363 );
364
365 t::lib::Mocks::mock_preference('item-level_itypes', 0);
366 ModItem({ itype => undef }, $item_bibnum, $itemnumber);
367 ok(
368     CanItemBeReserved( $borrowernumbers[0], $itemnumber)->{status} eq 'tooManyReserves',
369     "cannot request item if policy that matches on bib-level item type forbids it (bug 9532)"
370 );
371
372
373 # Test branch item rules
374
375 $dbh->do('DELETE FROM issuingrules');
376 $dbh->do('DELETE FROM circulation_rules');
377 $dbh->do(
378     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed)
379       VALUES (?, ?, ?, ?)},
380     {},
381     '*', '*', '*', 25
382 );
383 Koha::CirculationRules->set_rules(
384     {
385         branchcode => $branch_1,
386         itemtype   => 'CANNOT',
387         categorycode => undef,
388         rules => {
389             holdallowed => 0,
390             returnbranch => 'homebranch',
391         }
392     }
393 );
394 Koha::CirculationRules->set_rules(
395     {
396         branchcode => $branch_1,
397         itemtype   => 'CAN',
398         categorycode => undef,
399         rules => {
400             holdallowed => 1,
401             returnbranch => 'homebranch',
402         }
403     }
404 );
405 $biblio = $builder->build_sample_biblio({ itemtype => 'CANNOT' });
406 ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem(
407     { homebranch => $branch_1, holdingbranch => $branch_1, itype => 'CANNOT' } , $biblio->biblionumber);
408 is(CanItemBeReserved($borrowernumbers[0], $itemnumber)->{status}, 'notReservable',
409     "CanItemBeReserved should return 'notReservable'");
410
411 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
412 ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem(
413     { homebranch => $branch_2, holdingbranch => $branch_1, itype => 'CAN' } , $biblio->biblionumber);
414 is(CanItemBeReserved($borrowernumbers[0], $itemnumber)->{status},
415     'cannotReserveFromOtherBranches',
416     "CanItemBeReserved should use PatronLibrary rule when ReservesControlBranch set to 'PatronLibrary'");
417 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
418 is(CanItemBeReserved($borrowernumbers[0], $itemnumber)->{status},
419     'OK',
420     "CanItemBeReserved should use item home library rule when ReservesControlBranch set to 'ItemsHomeLibrary'");
421
422 ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem(
423     { homebranch => $branch_1, holdingbranch => $branch_1, itype => 'CAN' } , $biblio->biblionumber);
424 is(CanItemBeReserved($borrowernumbers[0], $itemnumber)->{status}, 'OK',
425     "CanItemBeReserved should return 'OK'");
426
427 # Bug 12632
428 t::lib::Mocks::mock_preference( 'item-level_itypes',     1 );
429 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
430
431 $dbh->do('DELETE FROM reserves');
432 $dbh->do('DELETE FROM issues');
433 $dbh->do('DELETE FROM items');
434 $dbh->do('DELETE FROM biblio');
435
436 $biblio = $builder->build_sample_biblio({ itemtype => 'ONLY1' });
437 ( $item_bibnum, $item_bibitemnum, $itemnumber )
438     = AddItem( { homebranch => $branch_1, holdingbranch => $branch_1 }, $biblio->biblionumber );
439
440 $dbh->do(
441     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed, holds_per_record)
442       VALUES (?, ?, ?, ?, ?)},
443     {},
444     '*', '*', 'ONLY1', 1, 99
445 );
446 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber )->{status},
447     'OK', 'Patron can reserve item with hold limit of 1, no holds placed' );
448
449 my $res_id = AddReserve( $branch_1, $borrowernumbers[0], $biblio->biblionumber, '', 1, );
450
451 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber )->{status},
452     'tooManyReserves', 'Patron cannot reserve item with hold limit of 1, 1 bib level hold placed' );
453
454     #results should be the same for both ReservesControlBranch settings
455 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' );
456 is( CanItemBeReserved( $borrowernumbers[0], $itemnumber )->{status},
457     'tooManyReserves', 'Patron cannot reserve item with hold limit of 1, 1 bib level hold placed' );
458 #reset for further tests
459 t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' );
460
461 subtest 'Test max_holds per library/patron category' => sub {
462     plan tests => 6;
463
464     $dbh->do('DELETE FROM reserves');
465     $dbh->do('DELETE FROM issuingrules');
466     $dbh->do('DELETE FROM circulation_rules');
467
468     $biblio = $builder->build_sample_biblio({ itemtype => 'TEST' });
469     ( $item_bibnum, $item_bibitemnum, $itemnumber ) =
470       AddItem( { homebranch => $branch_1, holdingbranch => $branch_1 },
471         $biblio->biblionumber );
472     $dbh->do(
473         q{
474             INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed, holds_per_record)
475             VALUES (?, ?, ?, ?, ?)
476         },
477         {},
478         '*', '*', 'TEST', 99, 99
479     );
480     AddReserve( $branch_1, $borrowernumbers[0], $biblio->biblionumber, '', 1, );
481     AddReserve( $branch_1, $borrowernumbers[0], $biblio->biblionumber, '', 1, );
482     AddReserve( $branch_1, $borrowernumbers[0], $biblio->biblionumber, '', 1, );
483
484     my $count =
485       Koha::Holds->search( { borrowernumber => $borrowernumbers[0] } )->count();
486     is( $count, 3, 'Patron now has 3 holds' );
487
488     my $ret = CanItemBeReserved( $borrowernumbers[0], $itemnumber );
489     is( $ret->{status}, 'OK', 'Patron can place hold with no borrower circ rules' );
490
491     my $rule_all = Koha::CirculationRules->set_rule(
492         {
493             categorycode => $category->{categorycode},
494             branchcode   => undef,
495             itemtype     => undef,
496             rule_name    => 'max_holds',
497             rule_value   => 3,
498         }
499     );
500
501     my $rule_branch = Koha::CirculationRules->set_rule(
502         {
503             branchcode   => $branch_1,
504             categorycode => $category->{categorycode},
505             itemtype     => undef,
506             rule_name    => 'max_holds',
507             rule_value   => 5,
508         }
509     );
510
511     $ret = CanItemBeReserved( $borrowernumbers[0], $itemnumber );
512     is( $ret->{status}, 'OK', 'Patron can place hold with branch/category rule of 5, category rule of 3' );
513
514     $rule_branch->delete();
515
516     $ret = CanItemBeReserved( $borrowernumbers[0], $itemnumber );
517     is( $ret->{status}, 'tooManyReserves', 'Patron cannot place hold with only a category rule of 3' );
518
519     $rule_all->delete();
520     $rule_branch->rule_value(3);
521     $rule_branch->store();
522
523     $ret = CanItemBeReserved( $borrowernumbers[0], $itemnumber );
524     is( $ret->{status}, 'tooManyReserves', 'Patron cannot place hold with only a branch/category rule of 3' );
525
526     $rule_branch->rule_value(5);
527     $rule_branch->update();
528     $rule_branch->rule_value(5);
529     $rule_branch->store();
530
531     $ret = CanItemBeReserved( $borrowernumbers[0], $itemnumber );
532     is( $ret->{status}, 'OK', 'Patron can place hold with branch/category rule of 5, category rule of 5' );
533 };
534
535 subtest 'Pickup location availability tests' => sub {
536     plan tests => 4;
537
538     $biblio = $builder->build_sample_biblio({ itemtype => 'ONLY1' });
539     my ( $item_bibnum, $item_bibitemnum, $itemnumber )
540     = AddItem( { homebranch => $branch_1, holdingbranch => $branch_1 }, $biblio->biblionumber );
541     #Add a default rule to allow some holds
542     $dbh->do(
543         q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed, holds_per_record)
544           VALUES (?, ?, ?, ?, ?)},
545         {},
546         '*', '*', '*', 25, 99
547     );
548     my $item = Koha::Items->find($itemnumber);
549     my $branch_to = $builder->build({ source => 'Branch' })->{ branchcode };
550     my $library = Koha::Libraries->find($branch_to);
551     $library->pickup_location('1')->store;
552     my $patron = $builder->build({ source => 'Borrower' })->{ borrowernumber };
553
554     t::lib::Mocks::mock_preference('UseBranchTransferLimits', 1);
555     t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'itemtype');
556
557     $library->pickup_location('1')->store;
558     is(CanItemBeReserved($patron, $item->itemnumber, $branch_to)->{status},
559        'OK', 'Library is a pickup location');
560
561     my $limit = Koha::Item::Transfer::Limit->new({
562         fromBranch => $item->holdingbranch,
563         toBranch => $branch_to,
564         itemtype => $item->effective_itemtype,
565     })->store;
566     is(CanItemBeReserved($patron, $item->itemnumber, $branch_to)->{status},
567        'cannotBeTransferred', 'Item cannot be transferred');
568     $limit->delete;
569
570     $library->pickup_location('0')->store;
571     is(CanItemBeReserved($patron, $item->itemnumber, $branch_to)->{status},
572        'libraryNotPickupLocation', 'Library is not a pickup location');
573     is(CanItemBeReserved($patron, $item->itemnumber, 'nonexistent')->{status},
574        'libraryNotFound', 'Cannot set unknown library as pickup location');
575 };
576
577 $schema->storage->txn_rollback;
578
579 subtest 'CanItemBeReserved / holds_per_day tests' => sub {
580
581     plan tests => 10;
582
583     $schema->storage->txn_begin;
584
585     Koha::Holds->search->delete;
586     $dbh->do('DELETE FROM issues');
587     Koha::Items->search->delete;
588     Koha::Biblios->search->delete;
589
590     my $itemtype = $builder->build_object( { class => 'Koha::ItemTypes' } );
591     my $library  = $builder->build_object( { class => 'Koha::Libraries' } );
592     my $patron   = $builder->build_object( { class => 'Koha::Patrons' } );
593
594     # Create 3 biblios with items
595     my $biblio_1 = $builder->build_sample_biblio({ itemtype => $itemtype->itemtype });
596     my ( undef, undef, $itemnumber_1 ) = AddItem(
597         {   homebranch    => $library->branchcode,
598             holdingbranch => $library->branchcode
599         },
600         $biblio_1->biblionumber
601     );
602     my $biblio_2 = $builder->build_sample_biblio({ itemtype => $itemtype->itemtype });
603     my ( undef, undef, $itemnumber_2 ) = AddItem(
604         {   homebranch    => $library->branchcode,
605             holdingbranch => $library->branchcode
606         },
607         $biblio_2->biblionumber
608     );
609     my $biblio_3 = $builder->build_sample_biblio({ itemtype => $itemtype->itemtype });
610     my ( undef, undef, $itemnumber_3 ) = AddItem(
611         {   homebranch    => $library->branchcode,
612             holdingbranch => $library->branchcode
613         },
614         $biblio_3->biblionumber
615     );
616
617     Koha::IssuingRules->search->delete;
618     my $issuingrule = Koha::IssuingRule->new(
619         {   categorycode     => '*',
620             branchcode       => '*',
621             itemtype         => $itemtype->itemtype,
622             reservesallowed  => 1,
623             holds_per_record => 99,
624             holds_per_day    => 2
625         }
626     )->store;
627
628     is_deeply(
629         CanItemBeReserved( $patron->borrowernumber, $itemnumber_1 ),
630         { status => 'OK' },
631         'Patron can reserve item with hold limit of 1, no holds placed'
632     );
633
634     AddReserve( $library->branchcode, $patron->borrowernumber, $biblio_1->biblionumber, '', 1, );
635
636     is_deeply(
637         CanItemBeReserved( $patron->borrowernumber, $itemnumber_1 ),
638         { status => 'tooManyReserves', limit => 1 },
639         'Patron cannot reserve item with hold limit of 1, 1 bib level hold placed'
640     );
641
642     # Raise reservesallowed to avoid tooManyReserves from it
643     $issuingrule->set( { reservesallowed => 3 } )->store;
644
645     is_deeply(
646         CanItemBeReserved( $patron->borrowernumber, $itemnumber_2 ),
647         { status => 'OK' },
648         'Patron can reserve item with 2 reserves daily cap'
649     );
650
651     # Add a second reserve
652     my $res_id = AddReserve( $library->branchcode, $patron->borrowernumber, $biblio_2->biblionumber, '', 1, );
653     is_deeply(
654         CanItemBeReserved( $patron->borrowernumber, $itemnumber_2 ),
655         { status => 'tooManyReservesToday', limit => 2 },
656         'Patron cannot a third item with 2 reserves daily cap'
657     );
658
659     # Update last hold so reservedate is in the past, so 2 holds, but different day
660     $hold = Koha::Holds->find($res_id);
661     my $yesterday = dt_from_string() - DateTime::Duration->new( days => 1 );
662     $hold->reservedate($yesterday)->store;
663
664     is_deeply(
665         CanItemBeReserved( $patron->borrowernumber, $itemnumber_2 ),
666         { status => 'OK' },
667         'Patron can reserve item with 2 bib level hold placed on different days, 2 reserves daily cap'
668     );
669
670     # Set holds_per_day to 0
671     $issuingrule->set( { holds_per_day => 0 } )->store;
672
673     # Delete existing holds
674     Koha::Holds->search->delete;
675     is_deeply(
676         CanItemBeReserved( $patron->borrowernumber, $itemnumber_2 ),
677         { status => 'tooManyReservesToday', limit => 0 },
678         'Patron cannot reserve if holds_per_day is 0 (i.e. 0 is 0)'
679     );
680
681     $issuingrule->set( { holds_per_day => undef } )->store;
682     Koha::Holds->search->delete;
683     is_deeply(
684         CanItemBeReserved( $patron->borrowernumber, $itemnumber_2 ),
685         { status => 'OK' },
686         'Patron can reserve if holds_per_day is undef (i.e. undef is unlimited daily cap)'
687     );
688     AddReserve( $library->branchcode, $patron->borrowernumber, $biblio_1->biblionumber, '', 1, );
689     AddReserve( $library->branchcode, $patron->borrowernumber, $biblio_2->biblionumber, '', 1, );
690     is_deeply(
691         CanItemBeReserved( $patron->borrowernumber, $itemnumber_3 ),
692         { status => 'OK' },
693         'Patron can reserve if holds_per_day is undef (i.e. undef is unlimited daily cap)'
694     );
695     AddReserve( $library->branchcode, $patron->borrowernumber, $biblio_3->biblionumber, '', 1, );
696     is_deeply(
697         CanItemBeReserved( $patron->borrowernumber, $itemnumber_3 ),
698         { status => 'tooManyReserves', limit => 3 },
699         'Unlimited daily holds, but reached reservesallowed'
700     );
701     #results should be the same for both ReservesControlBranch settings
702     t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary');
703     is_deeply(
704         CanItemBeReserved( $patron->borrowernumber, $itemnumber_3 ),
705         { status => 'tooManyReserves', limit => 3 },
706         'Unlimited daily holds, but reached reservesallowed'
707     );
708
709     $schema->storage->txn_rollback;
710 };