Bug 19889: Add tests
[koha.git] / t / db_dependent / HoldsQueue.t
1 #!/usr/bin/perl
2
3 # Test C4::HoldsQueue::CreateQueue() for both transport cost matrix
4 # and StaticHoldsQueueWeight array (no RandomizeHoldsQueueWeight, no point)
5 # Wraps tests in transaction that's rolled back, so no data is destroyed
6 # MySQL WARNING: This makes sense only if your tables are InnoDB, otherwise
7 # transactions are not supported and mess is left behind
8
9 use Modern::Perl;
10
11 use Test::More tests => 54;
12 use Data::Dumper;
13
14 use C4::Calendar;
15 use C4::Context;
16 use C4::Members;
17 use Koha::Database;
18 use Koha::DateUtils;
19 use Koha::Items;
20 use Koha::Holds;
21 use Koha::CirculationRules;
22
23 use t::lib::TestBuilder;
24 use t::lib::Mocks;
25
26 BEGIN {
27     use FindBin;
28     use lib $FindBin::Bin;
29     use_ok('C4::Reserves');
30     use_ok('C4::HoldsQueue');
31 }
32
33 my $schema = Koha::Database->schema;
34 $schema->storage->txn_begin;
35 my $dbh = C4::Context->dbh;
36 $dbh->do("DELETE FROM circulation_rules");
37
38 my $builder = t::lib::TestBuilder->new;
39
40 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits',  '0' );
41 t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' );
42
43 my $library1 = $builder->build({
44     source => 'Branch',
45 });
46 my $library2 = $builder->build({
47     source => 'Branch',
48 });
49 my $library3 = $builder->build({
50     source => 'Branch',
51 });
52
53 my $TITLE = "Test Holds Queue XXX";
54
55 my $borrower = $builder->build({
56     source => 'Borrower',
57     value => {
58         branchcode => $library1->{branchcode},
59     }
60 });
61
62 my $borrowernumber = $borrower->{borrowernumber};
63 # Set special (for this test) branches
64 my $borrower_branchcode = $borrower->{branchcode};
65 my @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} );
66 my @other_branches = ( $library2->{branchcode}, $library3->{branchcode} );
67 my $least_cost_branch_code = pop @other_branches;
68 my $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
69
70 #Set up the stage
71 # Sysprefs and cost matrix
72 t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 0);
73 t::lib::Mocks::mock_preference('LocalHoldsPriority', 0);
74 $dbh->do("UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'", undef,
75          join( ',', @other_branches, $borrower_branchcode, $least_cost_branch_code));
76 $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'RandomizeHoldsQueueWeight'");
77
78 $dbh->do("DELETE FROM transport_cost");
79 my $transport_cost_insert_sth = $dbh->prepare("insert into transport_cost (frombranch, tobranch, cost) values (?, ?, ?)");
80 # Favour $least_cost_branch_code
81 $transport_cost_insert_sth->execute($borrower_branchcode, $least_cost_branch_code, 0.2);
82 $transport_cost_insert_sth->execute($least_cost_branch_code, $borrower_branchcode, 0.2);
83 my @b = @other_branches;
84 while ( my $b1 = shift @b ) {
85     foreach my $b2 ($borrower_branchcode, $least_cost_branch_code, @b) {
86         $transport_cost_insert_sth->execute($b1, $b2, 0.5);
87         $transport_cost_insert_sth->execute($b2, $b1, 0.5);
88     }
89 }
90
91
92 # Loanable items - all possible combinations of homebranch and holdingbranch
93 $dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated)
94           VALUES             ('SER', 'Koha test', '$TITLE', '2011-02-01')");
95 my $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
96   or BAIL_OUT("Cannot find newly created biblio record");
97 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype)
98           VALUES                  ($biblionumber, '$itemtype')");
99 my $biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
100   or BAIL_OUT("Cannot find newly created biblioitems record");
101
102 my $items_insert_sth = $dbh->prepare("INSERT INTO items (biblionumber, biblioitemnumber, barcode, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
103                                       VALUES            ($biblionumber, $biblioitemnumber, ?, ?, ?, 0, 0, 0, 0, NULL, '$itemtype')"); # CURRENT_DATE - 3)");
104 my $first_barcode = int(rand(1000000000000)); # XXX
105 my $barcode = $first_barcode;
106 foreach ( $borrower_branchcode, $least_cost_branch_code, @other_branches ) {
107     $items_insert_sth->execute($barcode++, $borrower_branchcode, $_);
108     $items_insert_sth->execute($barcode++, $_, $_);
109     $items_insert_sth->execute($barcode++, $_, $borrower_branchcode);
110 }
111
112 # Remove existing reserves, makes debugging easier
113 $dbh->do("DELETE FROM reserves");
114 my $bibitems = undef;
115 my $priority = 1;
116 # Make a reserve
117 AddReserve(
118     {
119         branchcode     => $borrower_branchcode,
120         borrowernumber => $borrowernumber,
121         biblionumber   => $biblionumber,
122         priority       => $priority,
123     }
124 );
125 #                           $resdate, $expdate, $notes, $title, $checkitem, $found
126 $dbh->do("UPDATE reserves SET reservedate = DATE_SUB( reservedate, INTERVAL 1 DAY )");
127
128 # Tests
129 my $use_cost_matrix_sth = $dbh->prepare("UPDATE systempreferences SET value = ? WHERE variable = 'UseTransportCostMatrix'");
130 my $test_sth = $dbh->prepare("SELECT * FROM hold_fill_targets
131                               JOIN tmp_holdsqueue USING (borrowernumber, biblionumber, itemnumber)
132                               JOIN items USING (itemnumber)
133                               WHERE borrowernumber = $borrowernumber");
134
135 # We have a book available homed in borrower branch, no point fiddling with AutomaticItemReturn
136 t::lib::Mocks::mock_preference('AutomaticItemReturn', 0);
137 test_queue ('take from homebranch',  0, $borrower_branchcode, $borrower_branchcode);
138 test_queue ('take from homebranch',  1, $borrower_branchcode, $borrower_branchcode);
139
140 $dbh->do("DELETE FROM tmp_holdsqueue");
141 $dbh->do("DELETE FROM hold_fill_targets");
142 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode')");
143 $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode'");
144 # test_queue will flush
145 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
146 # Not sure how to make this test more difficult - holding branch does not matter
147
148 $dbh->do("DELETE FROM tmp_holdsqueue");
149 $dbh->do("DELETE FROM hold_fill_targets");
150 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode')");
151 $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode'");
152 t::lib::Mocks::mock_preference('AutomaticItemReturn', 0);
153 # We have a book available held in borrower branch
154 test_queue ('take from holdingbranch', 0, $borrower_branchcode, $borrower_branchcode);
155 test_queue ('take from holdingbranch', 1, $borrower_branchcode, $borrower_branchcode);
156
157 $dbh->do("DELETE FROM tmp_holdsqueue");
158 $dbh->do("DELETE FROM hold_fill_targets");
159 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE holdingbranch = '$borrower_branchcode')");
160 $dbh->do("DELETE FROM items WHERE holdingbranch = '$borrower_branchcode'");
161 # No book available in borrower branch, pick according to the rules
162 # Frst branch from StaticHoldsQueueWeight
163 test_queue ('take from lowest cost branch', 0, $borrower_branchcode, $other_branches[0]);
164 test_queue ('take from lowest cost branch', 1, $borrower_branchcode, $least_cost_branch_code);
165 my $queue = C4::HoldsQueue::GetHoldsQueueItems($least_cost_branch_code) || [];
166 my $queue_item = $queue->[0];
167 ok( $queue_item
168  && $queue_item->{pickbranch} eq $borrower_branchcode
169  && $queue_item->{holdingbranch} eq $least_cost_branch_code, "GetHoldsQueueItems" )
170   or diag( "Expected item for pick $borrower_branchcode, hold $least_cost_branch_code, got ".Dumper($queue_item) );
171 ok( exists($queue_item->{itype}), 'item type included in queued items list (bug 5825)' );
172
173 ok(
174     C4::HoldsQueue::least_cost_branch( 'B', [ 'A', 'B', 'C' ] ) eq 'B',
175     'C4::HoldsQueue::least_cost_branch returns the local branch if it is in the list of branches to pull from'
176 );
177
178 # XXX All this tests are for borrower branch pick-up.
179 # Maybe needs expanding to homebranch or holdingbranch pick-up.
180
181 $schema->txn_rollback;
182 $schema->txn_begin;
183
184 ### Test holds queue builder does not violate holds policy ###
185
186 # Clear out existing rules relating to holdallowed
187 $dbh->do("DELETE FROM circulation_rules");
188
189 t::lib::Mocks::mock_preference('UseTransportCostMatrix', 0);
190
191 $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
192
193 $library1 = $builder->build({
194     source => 'Branch',
195 });
196 $library2 = $builder->build({
197     source => 'Branch',
198 });
199 $library3 = $builder->build({
200     source => 'Branch',
201 });
202 @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} );
203
204 my $category = $builder->build({ source => 'Category', value => {exclude_from_local_holds_priority => 0} } );
205
206 my $borrower1 = $builder->build({
207     source => 'Borrower',
208     value => {
209         branchcode => $branchcodes[0],
210         categorycode => $category->{categorycode},
211     },
212 });
213 my $borrower2 = $builder->build({
214     source => 'Borrower',
215     value => {
216         branchcode => $branchcodes[1],
217         categorycode => $category->{categorycode},
218     },
219 });
220 my $borrower3 = $builder->build({
221     source => 'Borrower',
222     value => {
223         branchcode => $branchcodes[2],
224         categorycode => $category->{categorycode},
225     },
226 });
227
228 $dbh->do(qq{
229     INSERT INTO biblio (
230         frameworkcode,
231         author,
232         title,
233         datecreated
234     ) VALUES (
235         'SER',
236         'Koha test',
237         '$TITLE',
238         '2011-02-01'
239     )
240 });
241 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
242   or BAIL_OUT("Cannot find newly created biblio record");
243
244 $dbh->do(qq{
245     INSERT INTO biblioitems (
246         biblionumber,
247         itemtype
248     ) VALUES (
249         $biblionumber,
250         '$itemtype'
251     )
252 });
253 $biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
254   or BAIL_OUT("Cannot find newly created biblioitems record");
255
256 $items_insert_sth = $dbh->prepare(qq{
257     INSERT INTO items (
258         biblionumber,
259         biblioitemnumber,
260         barcode,
261         homebranch,
262         holdingbranch,
263         notforloan,
264         damaged,
265         itemlost,
266         withdrawn,
267         onloan,
268         itype,
269         exclude_from_local_holds_priority
270     ) VALUES (
271         $biblionumber,
272         $biblioitemnumber,
273         ?,
274         ?,
275         ?,
276         0,
277         0,
278         0,
279         0,
280         NULL,
281         '$itemtype',
282         0
283     )
284 });
285 # Create 3 items from 2 branches ( branches are for borrowers 1 and 2 respectively )
286 $barcode = int( rand(1000000000000) );
287 $items_insert_sth->execute( $barcode + 0, $branchcodes[0], $branchcodes[0] );
288 $items_insert_sth->execute( $barcode + 1, $branchcodes[1], $branchcodes[1] );
289 $items_insert_sth->execute( $barcode + 2, $branchcodes[1], $branchcodes[1] );
290
291 $dbh->do("DELETE FROM reserves");
292 my $sth = $dbh->prepare(q{
293     INSERT INTO reserves (
294         borrowernumber,
295         biblionumber,
296         branchcode,
297         priority,
298         reservedate
299     ) VALUES ( ?,?,?,?, CURRENT_DATE() )
300 });
301 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
302 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
303 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
304
305 my $holds_queue;
306
307 $dbh->do("DELETE FROM circulation_rules");
308 Koha::CirculationRules->set_rule(
309     {
310         rule_name    => 'holdallowed',
311         rule_value   => 1,
312         branchcode   => undef,
313         itemtype     => undef,
314     }
315 );
316 C4::HoldsQueue::CreateQueue();
317 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
318 is( @$holds_queue, 2, "Holds queue filling correct number for default holds policy 'from home library'" );
319 is( $holds_queue->[0]->{cardnumber}, $borrower1->{cardnumber}, "Holds queue filling 1st correct hold for default holds policy 'from home library'");
320 is( $holds_queue->[1]->{cardnumber}, $borrower2->{cardnumber}, "Holds queue filling 2nd correct hold for default holds policy 'from home library'");
321
322 # Test skipping hold picks for closed libraries.
323 # At this point in the test, we have 2 rows in the holds queue
324 # 1 of which is coming from MPL. Let's enable HoldsQueueSkipClosed
325 # and make today a holiday for MPL. When we run it again we should only
326 # have 1 row in the holds queue
327 t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 1);
328 my $today = dt_from_string();
329 C4::Calendar->new( branchcode => $branchcodes[0] )->insert_single_holiday(
330     day         => $today->day(),
331     month       => $today->month(),
332     year        => $today->year(),
333     title       => "$today",
334     description => "$today",
335 );
336 # If the test below is removed, aother tests using the holiday will fail. For some reason if we call is_holiday now
337 # the holiday will get set in cache correctly, but not if we let C4::HoldsQueue call is_holiday instead.
338 is( Koha::Calendar->new( branchcode => $branchcodes[0] )->is_holiday( $today ), 1, 'Is today a holiday for pickup branch' );
339 C4::HoldsQueue::CreateQueue();
340 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
341 is( scalar( @$holds_queue ), 1, "Holds not filled with items from closed libraries" );
342 t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 0);
343
344 $dbh->do("DELETE FROM circulation_rules");
345 Koha::CirculationRules->set_rule(
346     {
347         rule_name    => 'holdallowed',
348         rule_value   => 2,
349         branchcode   => undef,
350         itemtype     => undef,
351     }
352 );
353 C4::HoldsQueue::CreateQueue();
354 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
355 is( @$holds_queue, 3, "Holds queue filling correct number for holds for default holds policy 'from any library'" );
356
357 # Test skipping hold picks for closed libraries without transport cost matrix
358 # At this point in the test, we have 3 rows in the holds queue
359 # one of which is coming from MPL. Let's enable HoldsQueueSkipClosed
360 # and use our previously created holiday for MPL
361 # When we run it again we should only have 2 rows in the holds queue
362 t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 1 );
363 C4::HoldsQueue::CreateQueue();
364 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
365 is( scalar( @$holds_queue ), 2, "Holds not filled with items from closed libraries" );
366 t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 0 );
367
368 ## Test LocalHoldsPriority
369 t::lib::Mocks::mock_preference('LocalHoldsPriority', 1);
370
371 $dbh->do("DELETE FROM circulation_rules");
372 Koha::CirculationRules->set_rule(
373     {
374         rule_name    => 'holdallowed',
375         rule_value   => 2,
376         branchcode   => undef,
377         itemtype     => undef,
378     }
379 );
380 $dbh->do("DELETE FROM issues");
381
382 # Test homebranch = patron branch
383 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary');
384 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'homebranch');
385 C4::Context->clear_syspref_cache();
386 $dbh->do("DELETE FROM reserves");
387 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
388 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
389 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
390
391 $dbh->do("DELETE FROM items");
392 # barcode, homebranch, holdingbranch, itemtype
393 $items_insert_sth->execute( $barcode + 4, $branchcodes[2], $branchcodes[0] );
394
395 C4::HoldsQueue::CreateQueue();
396 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
397 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's home library");
398
399 ### Test branch transfer limits ###
400 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary');
401 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch');
402 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' );
403 C4::Context->clear_syspref_cache();
404 $dbh->do("DELETE FROM reserves");
405 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
406 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[1], 2 );
407
408 $dbh->do("DELETE FROM items");
409 # barcode, homebranch, holdingbranch, itemtype
410 $items_insert_sth->execute( $barcode, $branchcodes[2], $branchcodes[2] );
411 my $item = Koha::Items->find( { barcode => $barcode } );
412
413 my $limit1 = Koha::Item::Transfer::Limit->new(
414     {
415         toBranch   => $branchcodes[0],
416         fromBranch => $branchcodes[2],
417         itemtype   => $item->effective_itemtype,
418     }
419 )->store();
420
421 C4::HoldsQueue::CreateQueue();
422 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
423 is( $holds_queue->[0]->{cardnumber}, $borrower2->{cardnumber}, "Holds queue skips hold transfer that would violate branch transfer limits");
424
425 my $limit2 = Koha::Item::Transfer::Limit->new(
426     {
427         toBranch   => $branchcodes[1],
428         fromBranch => $branchcodes[2],
429         itemtype   => $item->effective_itemtype,
430     }
431 )->store();
432
433 C4::HoldsQueue::CreateQueue();
434 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
435 is( $holds_queue->[0]->{cardnumber}, undef, "Holds queue doesn't fill hold where all available items would violate branch transfer limits");
436
437 $limit1->delete();
438 $limit2->delete();
439 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' );
440 ### END Test branch transfer limits ###
441
442 # Test holdingbranch = patron branch
443 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary');
444 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch');
445 C4::Context->clear_syspref_cache();
446 $dbh->do("DELETE FROM reserves");
447 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
448 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
449 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
450
451 $dbh->do("DELETE FROM items");
452 # barcode, homebranch, holdingbranch, itemtype
453 $items_insert_sth->execute( $barcode + 4, $branchcodes[0], $branchcodes[2] );
454
455 C4::HoldsQueue::CreateQueue();
456 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
457 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library");
458
459 # Test holdingbranch = pickup branch
460 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'PickupLibrary');
461 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch');
462 C4::Context->clear_syspref_cache();
463 $dbh->do("DELETE FROM reserves");
464 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
465 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
466 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[2], 3 );
467
468 $dbh->do("DELETE FROM items");
469 # barcode, homebranch, holdingbranch, itemtype
470 $items_insert_sth->execute( $barcode + 4, $branchcodes[0], $branchcodes[2] );
471
472 C4::HoldsQueue::CreateQueue();
473 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
474 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library");
475
476 # Test homebranch = pickup branch
477 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'PickupLibrary');
478 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'homebranch');
479 C4::Context->clear_syspref_cache();
480 $dbh->do("DELETE FROM reserves");
481 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
482 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
483 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[2], 3 );
484
485 $dbh->do("DELETE FROM items");
486 # barcode, homebranch, holdingbranch, itemtype
487 $items_insert_sth->execute( $barcode + 4, $branchcodes[2], $branchcodes[0] );
488
489 C4::HoldsQueue::CreateQueue();
490 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
491 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library");
492
493 t::lib::Mocks::mock_preference('LocalHoldsPriority', 0);
494 ## End testing of LocalHoldsPriority
495
496
497 # Bug 14297
498 $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
499 $borrowernumber = $borrower3->{borrowernumber};
500 my $library_A = $library1->{branchcode};
501 my $library_B = $library2->{branchcode};
502 my $library_C = $borrower3->{branchcode};
503 $dbh->do("DELETE FROM reserves");
504 $dbh->do("DELETE FROM issues");
505 $dbh->do("DELETE FROM items");
506 $dbh->do("DELETE FROM biblio");
507 $dbh->do("DELETE FROM biblioitems");
508 $dbh->do("DELETE FROM transport_cost");
509 $dbh->do("DELETE FROM tmp_holdsqueue");
510 $dbh->do("DELETE FROM hold_fill_targets");
511
512 $dbh->do("
513     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
514 ");
515
516 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
517   or BAIL_OUT("Cannot find newly created biblio record");
518
519 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
520
521 $biblioitemnumber =
522   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
523   or BAIL_OUT("Cannot find newly created biblioitems record");
524
525 $dbh->do("
526     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype, exclude_from_local_holds_priority)
527     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype', 0)
528 ");
529
530 $dbh->do("
531     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype, exclude_from_local_holds_priority)
532     VALUES ($biblionumber, $biblioitemnumber, '$library_B', '$library_B', 0, 0, 0, 0, NULL, '$itemtype', 0)
533 ");
534
535 Koha::CirculationRules->set_rules(
536     {
537         branchcode   => $library_A,
538         itemtype     => $itemtype,
539         rules        => {
540             holdallowed  => 2,
541             returnbranch => 'homebranch',
542         }
543     }
544 );
545
546 $dbh->do( "UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'",
547     undef, join( ',', $library_B, $library_A, $library_C ) );
548 $dbh->do( "UPDATE systempreferences SET value = 0 WHERE variable = 'RandomizeHoldsQueueWeight'" );
549
550 my $reserve_id = AddReserve(
551     {
552         branchcode     => $library_C,
553         borrowernumber => $borrowernumber,
554         biblionumber   => $biblionumber,
555         priority       => 1,
556     }
557 );
558 C4::HoldsQueue::CreateQueue();
559 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
560 is( @$holds_queue, 1, "Bug 14297 - Holds Queue building ignoring holds where pickup & home branch don't match and item is not from le");
561 # End Bug 14297
562
563 # Bug 15062
564 $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
565 $borrowernumber = $borrower2->{borrowernumber};
566 $library_A = $library1->{branchcode};
567 $library_B = $library2->{branchcode};
568 $dbh->do("DELETE FROM reserves");
569 $dbh->do("DELETE FROM issues");
570 $dbh->do("DELETE FROM items");
571 $dbh->do("DELETE FROM biblio");
572 $dbh->do("DELETE FROM biblioitems");
573 $dbh->do("DELETE FROM transport_cost");
574 $dbh->do("DELETE FROM tmp_holdsqueue");
575 $dbh->do("DELETE FROM hold_fill_targets");
576
577 t::lib::Mocks::mock_preference("UseTransportCostMatrix",1);
578
579 my $tc_rs = $schema->resultset('TransportCost');
580 $tc_rs->create({ frombranch => $library_A, tobranch => $library_B, cost => 0, disable_transfer => 1 });
581 $tc_rs->create({ frombranch => $library_B, tobranch => $library_A, cost => 0, disable_transfer => 1 });
582
583 $dbh->do("
584     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
585 ");
586
587 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
588   or BAIL_OUT("Cannot find newly created biblio record");
589
590 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
591
592 $biblioitemnumber =
593   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
594   or BAIL_OUT("Cannot find newly created biblioitems record");
595
596 $dbh->do("
597     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype, exclude_from_local_holds_priority)
598     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype', 0)
599 ");
600
601 $reserve_id = AddReserve(
602     {
603         branchcode     => $library_B,
604         borrowernumber => $borrowernumber,
605         biblionumber   => $biblionumber,
606         priority       => 1,
607     }
608 );
609
610 C4::HoldsQueue::CreateQueue();
611 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
612 is( @$holds_queue, 0, "Bug 15062 - Holds queue with Transport Cost Matrix will transfer item even if transfers disabled");
613 # End Bug 15062
614
615 # Test hold_fulfillment_policy
616 t::lib::Mocks::mock_preference( "UseTransportCostMatrix", 0 );
617 $borrowernumber = $borrower3->{borrowernumber};
618 $library_A = $library1->{branchcode};
619 $library_B = $library2->{branchcode};
620 $library_C = $library3->{branchcode};
621 $dbh->do("DELETE FROM reserves");
622 $dbh->do("DELETE FROM issues");
623 $dbh->do("DELETE FROM items");
624 $dbh->do("DELETE FROM biblio");
625 $dbh->do("DELETE FROM biblioitems");
626 $dbh->do("DELETE FROM transport_cost");
627 $dbh->do("DELETE FROM tmp_holdsqueue");
628 $dbh->do("DELETE FROM hold_fill_targets");
629
630 $dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')");
631
632 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
633   or BAIL_OUT("Cannot find newly created biblio record");
634
635 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
636
637 $biblioitemnumber =
638   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
639   or BAIL_OUT("Cannot find newly created biblioitems record");
640
641 $dbh->do("
642     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype, exclude_from_local_holds_priority)
643     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_B', 0, 0, 0, 0, NULL, '$itemtype', 0)
644 ");
645
646 # With hold_fulfillment_policy = homebranch, hold should only be picked up if pickup branch = homebranch
647 $dbh->do("DELETE FROM circulation_rules");
648 Koha::CirculationRules->set_rules(
649     {
650         branchcode   => undef,
651         itemtype     => undef,
652         rules        => {
653             holdallowed             => 2,
654             hold_fulfillment_policy => 'homebranch',
655         }
656     }
657 );
658
659 # Home branch matches pickup branch
660 $reserve_id = AddReserve(
661     {
662         branchcode     => $library_A,
663         borrowernumber => $borrowernumber,
664         biblionumber   => $biblionumber,
665         priority       => 1,
666     }
667 );
668
669 C4::HoldsQueue::CreateQueue();
670 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
671 is( @$holds_queue, 1, "Hold where pickup branch matches home branch targeted" );
672 Koha::Holds->find( $reserve_id )->cancel;
673
674 # Holding branch matches pickup branch
675 $reserve_id = AddReserve(
676     {
677         branchcode     => $library_B,
678         borrowernumber => $borrowernumber,
679         biblionumber   => $biblionumber,
680         priority       => 1,
681     }
682 );
683
684
685 C4::HoldsQueue::CreateQueue();
686 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
687 is( @$holds_queue, 0, "Hold where pickup ne home, pickup eq home not targeted" );
688 Koha::Holds->find( $reserve_id )->cancel;
689
690 # Neither branch matches pickup branch
691 $reserve_id = AddReserve(
692     {
693         branchcode     => $library_C,
694         borrowernumber => $borrowernumber,
695         biblionumber   => $biblionumber,
696         priority       => 1,
697     }
698 );
699
700 C4::HoldsQueue::CreateQueue();
701 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
702 is( @$holds_queue, 0, "Hold where pickup ne home, pickup ne holding not targeted" );
703 Koha::Holds->find( $reserve_id )->cancel;
704
705 # With hold_fulfillment_policy = holdingbranch, hold should only be picked up if pickup branch = holdingbranch
706 $dbh->do("DELETE FROM circulation_rules");
707 Koha::CirculationRules->set_rules(
708     {
709         branchcode   => undef,
710         itemtype     => undef,
711         rules        => {
712             holdallowed             => 2,
713             hold_fulfillment_policy => 'holdingbranch',
714         }
715     }
716 );
717
718 # Home branch matches pickup branch
719 $reserve_id = AddReserve(
720     {
721         branchcode     => $library_A,
722         borrowernumber => $borrowernumber,
723         biblionumber   => $biblionumber,
724         priority       => 1,
725     }
726 );
727
728 C4::HoldsQueue::CreateQueue();
729 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
730 is( @$holds_queue, 0, "Hold where pickup eq home, pickup ne holding not targeted" );
731 Koha::Holds->find( $reserve_id )->cancel;
732
733 # Holding branch matches pickup branch
734 $reserve_id = AddReserve(
735     {
736         branchcode     => $library_B,
737         borrowernumber => $borrowernumber,
738         biblionumber   => $biblionumber,
739         priority       => 1,
740     }
741 );
742
743 C4::HoldsQueue::CreateQueue();
744 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
745 is( @$holds_queue, 1, "Hold where pickup ne home, pickup eq holding targeted" );
746 Koha::Holds->find( $reserve_id )->cancel;
747
748 # Neither branch matches pickup branch
749 $reserve_id = AddReserve(
750     {
751         branchcode     => $library_C,
752         borrowernumber => $borrowernumber,
753         biblionumber   => $biblionumber,
754         priority       => 1,
755     }
756 );
757
758 C4::HoldsQueue::CreateQueue();
759 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
760 is( @$holds_queue, 0, "Hold where pickup ne home, pickup ne holding not targeted" );
761 Koha::Holds->find( $reserve_id )->cancel;
762
763 # With hold_fulfillment_policy = any, hold should be pikcup up reguardless of matching home or holding branch
764 $dbh->do("DELETE FROM circulation_rules");
765 Koha::CirculationRules->set_rules(
766     {
767         branchcode   => undef,
768         itemtype     => undef,
769         rules        => {
770             holdallowed             => 2,
771             hold_fulfillment_policy => 'any',
772         }
773     }
774 );
775
776 # Home branch matches pickup branch
777 $reserve_id = AddReserve(
778     {
779         branchcode     => $library_A,
780         borrowernumber => $borrowernumber,
781         biblionumber   => $biblionumber,
782         priority       => 1,
783     }
784 );
785
786 C4::HoldsQueue::CreateQueue();
787 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
788 is( @$holds_queue, 1, "Hold where pickup eq home, pickup ne holding targeted" );
789 Koha::Holds->find( $reserve_id )->cancel;
790
791 # Holding branch matches pickup branch
792 $reserve_id = AddReserve(
793     {
794         branchcode     => $library_B,
795         borrowernumber => $borrowernumber,
796         biblionumber   => $biblionumber,
797         priority       => 1,
798     }
799 );
800
801 C4::HoldsQueue::CreateQueue();
802 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
803 is( @$holds_queue, 1, "Hold where pickup ne home, pickup eq holding targeted" );
804 Koha::Holds->find( $reserve_id )->cancel;
805
806 # Neither branch matches pickup branch
807 $reserve_id = AddReserve(
808     {
809         branchcode     => $library_C,
810         borrowernumber => $borrowernumber,
811         biblionumber   => $biblionumber,
812         priority       => 1,
813     }
814 );
815
816 C4::HoldsQueue::CreateQueue();
817 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
818 is( @$holds_queue, 1, "Hold where pickup ne home, pickup ne holding targeted" );
819 Koha::Holds->find( $reserve_id )->cancel;
820
821 # End testing hold_fulfillment_policy
822
823 # Test hold itemtype limit
824 t::lib::Mocks::mock_preference( "UseTransportCostMatrix", 0 );
825 my $wrong_itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
826 my $right_itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
827 $borrowernumber = $borrower3->{borrowernumber};
828 my $branchcode = $library1->{branchcode};
829 $dbh->do("DELETE FROM reserves");
830 $dbh->do("DELETE FROM issues");
831 $dbh->do("DELETE FROM items");
832 $dbh->do("DELETE FROM biblio");
833 $dbh->do("DELETE FROM biblioitems");
834 $dbh->do("DELETE FROM transport_cost");
835 $dbh->do("DELETE FROM tmp_holdsqueue");
836 $dbh->do("DELETE FROM hold_fill_targets");
837
838 $dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')");
839
840 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
841   or BAIL_OUT("Cannot find newly created biblio record");
842
843 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
844
845 $biblioitemnumber =
846   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
847   or BAIL_OUT("Cannot find newly created biblioitems record");
848
849 $dbh->do("
850     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype, exclude_from_local_holds_priority)
851     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_B', 0, 0, 0, 0, NULL, '$right_itemtype', 0)
852 ");
853
854 # With hold_fulfillment_policy = homebranch, hold should only be picked up if pickup branch = homebranch
855 $dbh->do("DELETE FROM circulation_rules");
856 Koha::CirculationRules->set_rules(
857     {
858         branchcode   => undef,
859         itemtype     => undef,
860         rules        => {
861             holdallowed             => 2,
862             hold_fulfillment_policy => 'any',
863         }
864     }
865 );
866
867 # Home branch matches pickup branch
868 $reserve_id = AddReserve(
869     {
870         branchcode     => $library_A,
871         borrowernumber => $borrowernumber,
872         biblionumber   => $biblionumber,
873         priority       => 1,
874         itemtype       => $wrong_itemtype,
875     }
876 );
877
878 C4::HoldsQueue::CreateQueue();
879 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
880 is( @$holds_queue, 0, "Item with incorrect itemtype not targeted" );
881 Koha::Holds->find( $reserve_id )->cancel;
882
883 # Holding branch matches pickup branch
884 $reserve_id = AddReserve(
885     {
886         branchcode     => $library_A,
887         borrowernumber => $borrowernumber,
888         biblionumber   => $biblionumber,
889         priority       => 1,
890         itemtype       => $right_itemtype,
891     }
892 );
893
894 C4::HoldsQueue::CreateQueue();
895 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
896 is( @$holds_queue, 1, "Item with matching itemtype is targeted" );
897 Koha::Holds->find( $reserve_id )->cancel;
898
899 # Neither branch matches pickup branch
900 $reserve_id = AddReserve(
901     {
902         branchcode     => $library_A,
903         borrowernumber => $borrowernumber,
904         biblionumber   => $biblionumber,
905         priority       => 1,
906     }
907 );
908
909 C4::HoldsQueue::CreateQueue();
910 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
911 is( @$holds_queue, 1, "Item targeted when hold itemtype is not set" );
912 Koha::Holds->find( $reserve_id )->cancel;
913
914 # End testing hold itemtype limit
915
916
917 subtest "Test Local Holds Priority - Bib level" => sub {
918     plan tests => 2;
919
920     Koha::Biblios->delete();
921     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
922     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
923     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
924     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
925     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
926     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
927     my $local_patron = $builder->build_object(
928         {
929             class => "Koha::Patrons",
930             value => {
931                 branchcode => $branch->branchcode,
932                 categorycode => $category->categorycode
933             }
934         }
935     );
936     my $other_patron = $builder->build_object(
937         {
938             class => "Koha::Patrons",
939             value => {
940                 branchcode => $branch2->branchcode,
941                 categorycode => $category->categorycode
942             }
943         }
944     );
945     my $biblio = $builder->build_sample_biblio();
946     my $item   = $builder->build_sample_item(
947         {
948             biblionumber  => $biblio->biblionumber,
949             library    => $branch->branchcode,
950             exclude_from_local_holds_priority => 0,
951         }
952     );
953
954     my $reserve_id = AddReserve(
955         {
956             branchcode     => $branch2->branchcode,
957             borrowernumber => $other_patron->borrowernumber,
958             biblionumber   => $biblio->biblionumber,
959             priority       => 1,
960         }
961     );
962     my $reserve_id2 = AddReserve(
963         {
964             branchcode     => $item->homebranch,
965             borrowernumber => $local_patron->borrowernumber,
966             biblionumber   => $biblio->biblionumber,
967             priority       => 2,
968         }
969     );
970
971     C4::HoldsQueue::CreateQueue();
972
973     my $queue_rs = $schema->resultset('TmpHoldsqueue');
974     is( $queue_rs->count(), 1,
975         "Hold queue contains one hold" );
976     is(
977         $queue_rs->next->borrowernumber,
978         $local_patron->borrowernumber,
979         "We should pick the local hold over the next available"
980     );
981 };
982
983 subtest "Test Local Holds Priority - Item level" => sub {
984     plan tests => 2;
985
986     Koha::Biblios->delete();
987     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
988     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
989     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
990     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
991     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
992     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
993     my $local_patron = $builder->build_object(
994         {
995             class => "Koha::Patrons",
996             value => {
997                 branchcode => $branch->branchcode,
998                 categorycode => $category->categorycode
999             }
1000         }
1001     );
1002     my $other_patron = $builder->build_object(
1003         {
1004             class => "Koha::Patrons",
1005             value => {
1006                 branchcode => $branch2->branchcode,
1007                 categorycode => $category->categorycode
1008             }
1009         }
1010     );
1011     my $biblio = $builder->build_sample_biblio();
1012     my $item   = $builder->build_sample_item(
1013         {
1014             biblionumber  => $biblio->biblionumber,
1015             library    => $branch->branchcode,
1016             exclude_from_local_holds_priority => 0,
1017         }
1018     );
1019
1020     my $reserve_id = AddReserve(
1021         {
1022             branchcode     => $branch2->branchcode,
1023             borrowernumber => $other_patron->borrowernumber,
1024             biblionumber   => $biblio->biblionumber,
1025             priority       => 1,
1026             itemnumber     => $item->id,
1027         }
1028     );
1029     my $reserve_id2 = AddReserve(
1030         {
1031             branchcode     => $item->homebranch,
1032             borrowernumber => $local_patron->borrowernumber,
1033             biblionumber   => $biblio->biblionumber,
1034             priority       => 2,
1035             itemnumber     => $item->id,
1036         }
1037     );
1038
1039     C4::HoldsQueue::CreateQueue();
1040
1041     my $queue_rs = $schema->resultset('TmpHoldsqueue');
1042     my $q = $queue_rs->next;
1043     is( $queue_rs->count(), 1,
1044         "Hold queue contains one hold" );
1045     is(
1046         $q->borrowernumber,
1047         $local_patron->borrowernumber,
1048         "We should pick the local hold over the next available"
1049     );
1050 };
1051
1052 subtest "Test Local Holds Priority - Item level hold over Record level hold (Bug 23934)" => sub {
1053     plan tests => 2;
1054
1055     Koha::Biblios->delete();
1056     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
1057     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
1058     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
1059     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
1060     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
1061     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
1062     my $local_patron = $builder->build_object(
1063         {
1064             class => "Koha::Patrons",
1065             value => {
1066                 branchcode => $branch->branchcode,
1067                 categorycode => $category->categorycode,
1068             }
1069         }
1070     );
1071     my $other_patron = $builder->build_object(
1072         {
1073             class => "Koha::Patrons",
1074             value => {
1075                 branchcode => $branch2->branchcode,
1076                 categorycode => $category->categorycode,
1077             }
1078         }
1079     );
1080     my $biblio = $builder->build_sample_biblio();
1081     my $item   = $builder->build_sample_item(
1082         {
1083             biblionumber  => $biblio->biblionumber,
1084             library    => $branch->branchcode,
1085             exclude_from_local_holds_priority => 0,
1086         }
1087     );
1088
1089     my $reserve_id = AddReserve(
1090         {
1091             branchcode     => $branch2->branchcode,
1092             borrowernumber => $other_patron->borrowernumber,
1093             biblionumber   => $biblio->biblionumber,
1094             priority       => 1,
1095         }
1096     );
1097     my $reserve_id2 = AddReserve(
1098         {
1099             branchcode     => $item->homebranch,
1100             borrowernumber => $local_patron->borrowernumber,
1101             biblionumber   => $biblio->biblionumber,
1102             priority       => 2,
1103             itemnumber     => $item->id,
1104         }
1105     );
1106
1107     C4::HoldsQueue::CreateQueue();
1108
1109     my $queue_rs = $schema->resultset('TmpHoldsqueue');
1110     my $q = $queue_rs->next;
1111     is( $queue_rs->count(), 1,
1112         "Hold queue contains one hold" );
1113     is(
1114         $q->borrowernumber,
1115         $local_patron->borrowernumber,
1116         "We should pick the local hold over the next available"
1117     );
1118 };
1119
1120 subtest "Test Local Holds Priority - Get correct item for item level hold" => sub {
1121     plan tests => 3;
1122
1123     Koha::Biblios->delete();
1124     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
1125     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
1126     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
1127     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
1128     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
1129     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
1130     my $local_patron = $builder->build_object(
1131         {
1132             class => "Koha::Patrons",
1133             value => {
1134                 branchcode => $branch->branchcode,
1135                 categorycode => $category->categorycode,
1136             }
1137         }
1138     );
1139     my $other_patron = $builder->build_object(
1140         {
1141             class => "Koha::Patrons",
1142             value => {
1143                 branchcode => $branch2->branchcode,
1144                 categorycode => $category->categorycode,
1145             }
1146         }
1147     );
1148     my $biblio = $builder->build_sample_biblio();
1149
1150     my $item1 = $builder->build_sample_item(
1151         {
1152             biblionumber  => $biblio->biblionumber,
1153             library    => $branch->branchcode,
1154             exclude_from_local_holds_priority => 0,
1155         }
1156     );
1157     my $item2 = $builder->build_sample_item(
1158         {
1159             biblionumber  => $biblio->biblionumber,
1160             library    => $branch->branchcode,
1161             exclude_from_local_holds_priority => 0,
1162         }
1163     );
1164     my $item3 = $builder->build_sample_item(
1165         {
1166             biblionumber  => $biblio->biblionumber,
1167             library    => $branch->branchcode,
1168             exclude_from_local_holds_priority => 0,
1169         }
1170     );
1171
1172     my $reserve_id2 =
1173         AddReserve(
1174             {
1175                 branchcode     => $item2->homebranch,
1176                 borrowernumber => $local_patron->borrowernumber,
1177                 biblionumber   => $biblio->biblionumber,
1178                 priority       => 2,
1179                 itemnumber     => $item2->id,
1180             }
1181         );
1182
1183
1184     C4::HoldsQueue::CreateQueue();
1185
1186     my $queue_rs = $schema->resultset('TmpHoldsqueue');
1187     my $q = $queue_rs->next;
1188     is( $queue_rs->count(), 1,
1189         "Hold queue contains one hold" );
1190     is(
1191         $q->borrowernumber,
1192         $local_patron->borrowernumber,
1193         "We should pick the local hold over the next available"
1194     );
1195     is( $q->itemnumber->id, $item2->id, "Got the correct item for item level local holds priority" );
1196 };
1197
1198 subtest "Test Local Holds Priority - Ensure no duplicate requests in holds queue (Bug 18001)" => sub {
1199     plan tests => 1;
1200
1201     $dbh->do("DELETE FROM tmp_holdsqueue");
1202     $dbh->do("DELETE FROM hold_fill_targets");
1203     $dbh->do("DELETE FROM reserves");
1204     $dbh->do("DELETE FROM circulation_rules");
1205     Koha::Biblios->delete();
1206
1207     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
1208     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
1209     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
1210     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
1211     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
1212     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
1213     my $patron  = $builder->build_object(
1214         {
1215             class => "Koha::Patrons",
1216             value => {
1217                 branchcode => $branch->branchcode,
1218                 categorycode => $category->categorycode,
1219             }
1220         }
1221     );
1222     my $biblio = $builder->build_sample_biblio();
1223     my $item1  = $builder->build_sample_item(
1224         {
1225             biblionumber => $biblio->biblionumber,
1226             library      => $branch->branchcode,
1227             exclude_from_local_holds_priority => 0,
1228         }
1229     );
1230     my $item2 = $builder->build_sample_item(
1231         {
1232             biblionumber => $biblio->biblionumber,
1233             library      => $branch->branchcode,
1234             exclude_from_local_holds_priority => 0,
1235         }
1236     );
1237
1238     my $item3 = $builder->build_sample_item(
1239         {
1240             biblionumber => $biblio->biblionumber,
1241             library      => $branch->branchcode,
1242             exclude_from_local_holds_priority => 0,
1243         }
1244     );
1245
1246     $reserve_id = AddReserve(
1247         {
1248             branchcode     => $item1->homebranch,
1249             borrowernumber => $patron->borrowernumber,
1250             biblionumber   => $biblio->id,
1251             priority       => 1
1252         }
1253     );
1254
1255     C4::HoldsQueue::CreateQueue();
1256
1257     my $queue_rs = $schema->resultset('TmpHoldsqueue');
1258
1259     is( $queue_rs->count(), 1,
1260         "Hold queue contains one hold from chosen from three possible items" );
1261 };
1262
1263
1264 subtest "Item level holds info is preserved (Bug 25738)" => sub {
1265
1266     plan tests => 3;
1267
1268     $dbh->do("DELETE FROM tmp_holdsqueue");
1269     $dbh->do("DELETE FROM hold_fill_targets");
1270     $dbh->do("DELETE FROM reserves");
1271     $dbh->do("DELETE FROM circulation_rules");
1272
1273     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
1274     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
1275     my $patron_1 = $builder->build_object(
1276         {
1277             class => "Koha::Patrons",
1278             value => {
1279                 branchcode => $library->branchcode,
1280                 categorycode => $category->categorycode
1281             }
1282         }
1283     );
1284
1285     my $patron_2 = $builder->build_object(
1286         {
1287             class => "Koha::Patrons",
1288             value => {
1289                 branchcode => $library->branchcode,
1290                 categorycode => $category->categorycode
1291             }
1292         }
1293     );
1294
1295     my $biblio = $builder->build_sample_biblio();
1296     my $item_1 = $builder->build_sample_item(
1297         {
1298             biblionumber => $biblio->biblionumber,
1299             library      => $library->branchcode,
1300             exclude_from_local_holds_priority => 0,
1301         }
1302     );
1303     my $item_2 = $builder->build_sample_item(
1304         {
1305             biblionumber => $biblio->biblionumber,
1306             library      => $library->branchcode,
1307             exclude_from_local_holds_priority => 0,
1308         }
1309     );
1310
1311     # Add item-level hold for patron_1
1312     my $reserve_id_1 = AddReserve(
1313         {
1314             branchcode     => $library->branchcode,
1315             borrowernumber => $patron_1->borrowernumber,
1316             biblionumber   => $biblio->id,
1317             itemnumber     => $item_1->itemnumber,
1318             priority       => 1
1319         }
1320     );
1321
1322     my $reserve_id_2 = AddReserve(
1323         {
1324             branchcode     => $library->branchcode,
1325             borrowernumber => $patron_2->borrowernumber,
1326             biblionumber   => $biblio->id,
1327             priority       => 2
1328         }
1329     );
1330
1331     C4::HoldsQueue::CreateQueue();
1332
1333     my $queue_rs = $schema->resultset('TmpHoldsqueue');
1334
1335     is( $queue_rs->count(), 2, "Hold queue contains two holds" );
1336
1337     my $queue_line_1 = $queue_rs->next;
1338     is( $queue_line_1->item_level_request, 1, 'Request is correctly advertised as item-level' );
1339
1340     my $queue_line_2 = $queue_rs->next;
1341     is( $queue_line_2->item_level_request, 0, 'Request is correctly advertised as biblio-level' );
1342
1343 };
1344
1345 subtest 'Trivial test for UpdateTransportCostMatrix' => sub {
1346     plan tests => 1;
1347     my $recs = [
1348         { frombranch => $library1->{branchcode}, tobranch => $library2->{branchcode}, cost => 1, disable_transfer => 0 },
1349         { frombranch => $library2->{branchcode}, tobranch => $library3->{branchcode}, cost => 0, disable_transfer => 1 },
1350     ];
1351     C4::HoldsQueue::UpdateTransportCostMatrix( $recs );
1352     is( $schema->resultset('TransportCost')->count, 2, 'UpdateTransportCostMatrix added two records' );
1353 };
1354
1355 subtest 'Excludes from local holds priority' => sub {
1356     plan tests => 5;
1357
1358     Koha::Holds->delete;
1359
1360     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
1361     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
1362     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
1363
1364     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
1365     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
1366     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
1367     my $excluded_category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 1} });
1368     my $local_patron_excluded = $builder->build_object(
1369         {
1370             class => "Koha::Patrons",
1371             value => {
1372                 branchcode => $branch->branchcode,
1373                 categorycode => $excluded_category->categorycode
1374             }
1375         }
1376     );
1377
1378     my $local_patron_not_excluded = $builder->build_object(
1379         {
1380             class => "Koha::Patrons",
1381             value => {
1382                 branchcode => $branch->branchcode,
1383                 categorycode => $category->categorycode
1384             }
1385         }
1386     );
1387
1388     my $other_patron = $builder->build_object(
1389         {
1390             class => "Koha::Patrons",
1391             value => {
1392                 branchcode => $branch2->branchcode,
1393                 categorycode => $category->categorycode
1394             }
1395         }
1396     );
1397
1398     my $item1  = $builder->build_sample_item(
1399         {
1400             library      => $branch->branchcode,
1401             exclude_from_local_holds_priority => 0,
1402         }
1403     );
1404
1405     AddReserve(
1406         {
1407             branchcode     => $other_patron->branchcode,
1408             borrowernumber => $other_patron->borrowernumber,
1409             biblionumber   => $item1->biblionumber,
1410             priority       => 1
1411         }
1412     );
1413
1414     AddReserve(
1415         {
1416             branchcode     => $local_patron_excluded->branchcode,
1417             borrowernumber => $local_patron_excluded->borrowernumber,
1418             biblionumber   => $item1->biblionumber,
1419             priority       => 2
1420         }
1421     );
1422
1423     AddReserve(
1424         {
1425             branchcode     => $local_patron_not_excluded->branchcode,
1426             borrowernumber => $local_patron_not_excluded->borrowernumber,
1427             biblionumber   => $item1->biblionumber,
1428             priority       => 3
1429         }
1430     );
1431
1432     C4::HoldsQueue::CreateQueue();
1433
1434     my $queue_rs = $schema->resultset('TmpHoldsqueue');
1435     my $next = $queue_rs->next;
1436     is($next->borrowernumber, $local_patron_not_excluded->borrowernumber, 'Not excluded local patron is queued');
1437
1438     my $item2  = $builder->build_sample_item(
1439         {
1440             biblionumber => $item1->biblionumber,
1441             library      => $branch->branchcode,
1442             exclude_from_local_holds_priority => 1,
1443         }
1444     );
1445     C4::HoldsQueue::CreateQueue();
1446
1447     $queue_rs = $schema->resultset('TmpHoldsqueue');
1448     $next = $queue_rs->next;
1449     is($next->borrowernumber, $local_patron_not_excluded->borrowernumber, 'Not excluded local patron is queued');
1450     $next = $queue_rs->next;
1451     is($next->borrowernumber, $other_patron->borrowernumber, 'Other patron is queued');
1452
1453     $item1->exclude_from_local_holds_priority(1)->store;
1454
1455     C4::HoldsQueue::CreateQueue();
1456
1457     $queue_rs = $schema->resultset('TmpHoldsqueue');
1458     $next = $queue_rs->next;
1459     is($next->borrowernumber, $other_patron->borrowernumber, 'Other patron is queued');
1460     $next = $queue_rs->next;
1461     is($next->borrowernumber, $local_patron_excluded->borrowernumber, 'Excluded local patron is queued');
1462 };
1463 # Cleanup
1464 $schema->storage->txn_rollback;
1465
1466 ### END Test holds queue builder does not violate holds policy ###
1467
1468 sub test_queue {
1469     my ($test_name, $use_cost_matrix, $pick_branch, $hold_branch) = @_;
1470
1471     $test_name = "$test_name (".($use_cost_matrix ? "" : "don't ")."use cost matrix)";
1472
1473     $use_cost_matrix_sth->execute($use_cost_matrix);
1474     C4::Context->clear_syspref_cache();
1475     C4::HoldsQueue::CreateQueue();
1476
1477     my $results = $dbh->selectall_arrayref($test_sth, { Slice => {} }); # should be only one
1478     my $r = $results->[0];
1479
1480     my $ok = is( $r->{pickbranch}, $pick_branch, "$test_name pick up branch");
1481     $ok &&=  is( $r->{holdingbranch}, $hold_branch, "$test_name holding branch")
1482       if $hold_branch;
1483
1484     diag( "Wrong pick-up/hold for first target (pick_branch, hold_branch, reserves, hold_fill_targets, tmp_holdsqueue): "
1485         . Dumper ($pick_branch, $hold_branch, map dump_records($_), qw(reserves hold_fill_targets tmp_holdsqueue)) )
1486       unless $ok;
1487
1488     # Test enforcement of branch transfer limit
1489     if ( $r->{pickbranch} ne $r->{holdingbranch} ) {
1490         t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' );
1491         my $limit = Koha::Item::Transfer::Limit->new(
1492             {
1493                 toBranch   => $r->{pickbranch},
1494                 fromBranch => $r->{holdingbranch},
1495                 itemtype   => $r->{itype},
1496             }
1497         )->store();
1498         C4::Context->clear_syspref_cache();
1499         C4::HoldsQueue::CreateQueue();
1500         $results = $dbh->selectall_arrayref( $test_sth, { Slice => {} } )
1501           ;    # should be only one
1502         my $s = $results->[0];
1503         isnt( $r->{holdingbranch}, $s->{holdingbranch}, 'Hold is not trapped for pickup at a branch that cannot be transferred to');
1504
1505         $limit->delete();
1506         t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' );
1507         C4::Context->clear_syspref_cache();
1508         C4::HoldsQueue::CreateQueue();
1509     }
1510
1511 }
1512
1513 sub dump_records {
1514     my ($tablename) = @_;
1515     return $dbh->selectall_arrayref("SELECT * from $tablename where borrowernumber = ?", { Slice => {} }, $borrowernumber);
1516 }