Bug 18936: (follow-up) Add foreign key and scope enhancement to circ rules
[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 => 51;
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 ( $borrower_branchcode, $borrowernumber, $biblionumber, $bibitems,  $priority );
118 #                           $resdate, $expdate, $notes, $title, $checkitem, $found
119 $dbh->do("UPDATE reserves SET reservedate = DATE_SUB( reservedate, INTERVAL 1 DAY )");
120
121 # Tests
122 my $use_cost_matrix_sth = $dbh->prepare("UPDATE systempreferences SET value = ? WHERE variable = 'UseTransportCostMatrix'");
123 my $test_sth = $dbh->prepare("SELECT * FROM hold_fill_targets
124                               JOIN tmp_holdsqueue USING (borrowernumber, biblionumber, itemnumber)
125                               JOIN items USING (itemnumber)
126                               WHERE borrowernumber = $borrowernumber");
127
128 # We have a book available homed in borrower branch, no point fiddling with AutomaticItemReturn
129 t::lib::Mocks::mock_preference('AutomaticItemReturn', 0);
130 test_queue ('take from homebranch',  0, $borrower_branchcode, $borrower_branchcode);
131 test_queue ('take from homebranch',  1, $borrower_branchcode, $borrower_branchcode);
132
133 $dbh->do("DELETE FROM tmp_holdsqueue");
134 $dbh->do("DELETE FROM hold_fill_targets");
135 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode')");
136 $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode'");
137 # test_queue will flush
138 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
139 # Not sure how to make this test more difficult - holding branch does not matter
140
141 $dbh->do("DELETE FROM tmp_holdsqueue");
142 $dbh->do("DELETE FROM hold_fill_targets");
143 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode')");
144 $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode'");
145 t::lib::Mocks::mock_preference('AutomaticItemReturn', 0);
146 # We have a book available held in borrower branch
147 test_queue ('take from holdingbranch', 0, $borrower_branchcode, $borrower_branchcode);
148 test_queue ('take from holdingbranch', 1, $borrower_branchcode, $borrower_branchcode);
149
150 $dbh->do("DELETE FROM tmp_holdsqueue");
151 $dbh->do("DELETE FROM hold_fill_targets");
152 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE holdingbranch = '$borrower_branchcode')");
153 $dbh->do("DELETE FROM items WHERE holdingbranch = '$borrower_branchcode'");
154 # No book available in borrower branch, pick according to the rules
155 # Frst branch from StaticHoldsQueueWeight
156 test_queue ('take from lowest cost branch', 0, $borrower_branchcode, $other_branches[0]);
157 test_queue ('take from lowest cost branch', 1, $borrower_branchcode, $least_cost_branch_code);
158 my $queue = C4::HoldsQueue::GetHoldsQueueItems($least_cost_branch_code) || [];
159 my $queue_item = $queue->[0];
160 ok( $queue_item
161  && $queue_item->{pickbranch} eq $borrower_branchcode
162  && $queue_item->{holdingbranch} eq $least_cost_branch_code, "GetHoldsQueueItems" )
163   or diag( "Expected item for pick $borrower_branchcode, hold $least_cost_branch_code, got ".Dumper($queue_item) );
164 ok( exists($queue_item->{itype}), 'item type included in queued items list (bug 5825)' );
165
166 ok(
167     C4::HoldsQueue::least_cost_branch( 'B', [ 'A', 'B', 'C' ] ) eq 'B',
168     'C4::HoldsQueue::least_cost_branch returns the local branch if it is in the list of branches to pull from'
169 );
170
171 # XXX All this tests are for borrower branch pick-up.
172 # Maybe needs expanding to homebranch or holdingbranch pick-up.
173
174 $schema->txn_rollback;
175 $schema->txn_begin;
176
177 ### Test holds queue builder does not violate holds policy ###
178
179 # Clear out existing rules relating to holdallowed
180 $dbh->do("DELETE FROM circulation_rules");
181
182 t::lib::Mocks::mock_preference('UseTransportCostMatrix', 0);
183
184 $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
185
186 $library1 = $builder->build({
187     source => 'Branch',
188 });
189 $library2 = $builder->build({
190     source => 'Branch',
191 });
192 $library3 = $builder->build({
193     source => 'Branch',
194 });
195 @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} );
196
197 my $borrower1 = $builder->build({
198     source => 'Borrower',
199     value => {
200         branchcode => $branchcodes[0],
201     },
202 });
203 my $borrower2 = $builder->build({
204     source => 'Borrower',
205     value => {
206         branchcode => $branchcodes[1],
207     },
208 });
209 my $borrower3 = $builder->build({
210     source => 'Borrower',
211     value => {
212         branchcode => $branchcodes[2],
213     },
214 });
215
216 $dbh->do(qq{
217     INSERT INTO biblio (
218         frameworkcode, 
219         author, 
220         title, 
221         datecreated
222     ) VALUES (
223         'SER', 
224         'Koha test', 
225         '$TITLE', 
226         '2011-02-01'
227     )
228 });
229 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
230   or BAIL_OUT("Cannot find newly created biblio record");
231
232 $dbh->do(qq{
233     INSERT INTO biblioitems (
234         biblionumber, 
235         itemtype
236     ) VALUES (
237         $biblionumber, 
238         '$itemtype'
239     )
240 });
241 $biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
242   or BAIL_OUT("Cannot find newly created biblioitems record");
243
244 $items_insert_sth = $dbh->prepare(qq{
245     INSERT INTO items (
246         biblionumber, 
247         biblioitemnumber,
248         barcode,
249         homebranch,
250         holdingbranch,
251         notforloan,
252         damaged,
253         itemlost,
254         withdrawn,
255         onloan,
256         itype
257     ) VALUES (
258         $biblionumber,
259         $biblioitemnumber,
260         ?,
261         ?,
262         ?,
263         0,
264         0,
265         0,
266         0,
267         NULL,
268         '$itemtype'
269     )
270 });
271 # Create 3 items from 2 branches ( branches are for borrowers 1 and 2 respectively )
272 $barcode = int( rand(1000000000000) );
273 $items_insert_sth->execute( $barcode + 0, $branchcodes[0], $branchcodes[0] );
274 $items_insert_sth->execute( $barcode + 1, $branchcodes[1], $branchcodes[1] );
275 $items_insert_sth->execute( $barcode + 2, $branchcodes[1], $branchcodes[1] );
276
277 $dbh->do("DELETE FROM reserves");
278 my $sth = $dbh->prepare(q{
279     INSERT INTO reserves ( 
280         borrowernumber,
281         biblionumber,
282         branchcode,
283         priority,
284         reservedate
285     ) VALUES ( ?,?,?,?, CURRENT_DATE() )
286 });
287 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
288 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
289 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
290
291 my $holds_queue;
292
293 $dbh->do("DELETE FROM circulation_rules");
294 Koha::CirculationRules->set_rule(
295     {
296         rule_name    => 'holdallowed',
297         rule_value   => 1,
298         branchcode   => undef,
299         itemtype     => undef,
300     }
301 );
302 C4::HoldsQueue::CreateQueue();
303 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
304 is( @$holds_queue, 2, "Holds queue filling correct number for default holds policy 'from home library'" );
305 is( $holds_queue->[0]->{cardnumber}, $borrower1->{cardnumber}, "Holds queue filling 1st correct hold for default holds policy 'from home library'");
306 is( $holds_queue->[1]->{cardnumber}, $borrower2->{cardnumber}, "Holds queue filling 2nd correct hold for default holds policy 'from home library'");
307
308 # Test skipping hold picks for closed libraries.
309 # At this point in the test, we have 2 rows in the holds queue
310 # 1 of which is coming from MPL. Let's enable HoldsQueueSkipClosed
311 # and make today a holiday for MPL. When we run it again we should only
312 # have 1 row in the holds queue
313 t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 1);
314 my $today = dt_from_string();
315 C4::Calendar->new( branchcode => $branchcodes[0] )->insert_single_holiday(
316     day         => $today->day(),
317     month       => $today->month(),
318     year        => $today->year(),
319     title       => "$today",
320     description => "$today",
321 );
322 # If the test below is removed, aother tests using the holiday will fail. For some reason if we call is_holiday now
323 # the holiday will get set in cache correctly, but not if we let C4::HoldsQueue call is_holiday instead.
324 is( Koha::Calendar->new( branchcode => $branchcodes[0] )->is_holiday( $today ), 1, 'Is today a holiday for pickup branch' );
325 C4::HoldsQueue::CreateQueue();
326 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
327 is( scalar( @$holds_queue ), 1, "Holds not filled with items from closed libraries" );
328 t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 0);
329
330 $dbh->do("DELETE FROM circulation_rules");
331 Koha::CirculationRules->set_rule(
332     {
333         rule_name    => 'holdallowed',
334         rule_value   => 2,
335         branchcode   => undef,
336         itemtype     => undef,
337     }
338 );
339 C4::HoldsQueue::CreateQueue();
340 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
341 is( @$holds_queue, 3, "Holds queue filling correct number for holds for default holds policy 'from any library'" );
342
343 # Test skipping hold picks for closed libraries without transport cost matrix
344 # At this point in the test, we have 3 rows in the holds queue
345 # one of which is coming from MPL. Let's enable HoldsQueueSkipClosed
346 # and use our previously created holiday for MPL
347 # When we run it again we should only have 2 rows in the holds queue
348 t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 1 );
349 C4::HoldsQueue::CreateQueue();
350 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
351 is( scalar( @$holds_queue ), 2, "Holds not filled with items from closed libraries" );
352 t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 0 );
353
354 ## Test LocalHoldsPriority
355 t::lib::Mocks::mock_preference('LocalHoldsPriority', 1);
356
357 $dbh->do("DELETE FROM circulation_rules");
358 Koha::CirculationRules->set_rule(
359     {
360         rule_name    => 'holdallowed',
361         rule_value   => 2,
362         branchcode   => undef,
363         itemtype     => undef,
364     }
365 );
366 $dbh->do("DELETE FROM issues");
367
368 # Test homebranch = patron branch
369 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary');
370 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'homebranch');
371 C4::Context->clear_syspref_cache();
372 $dbh->do("DELETE FROM reserves");
373 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
374 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
375 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
376
377 $dbh->do("DELETE FROM items");
378 # barcode, homebranch, holdingbranch, itemtype
379 $items_insert_sth->execute( $barcode + 4, $branchcodes[2], $branchcodes[0] );
380
381 C4::HoldsQueue::CreateQueue();
382 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
383 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's home library");
384
385 ### Test branch transfer limits ###
386 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary');
387 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch');
388 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' );
389 C4::Context->clear_syspref_cache();
390 $dbh->do("DELETE FROM reserves");
391 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
392 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[1], 2 );
393
394 $dbh->do("DELETE FROM items");
395 # barcode, homebranch, holdingbranch, itemtype
396 $items_insert_sth->execute( $barcode, $branchcodes[2], $branchcodes[2] );
397 my $item = Koha::Items->find( { barcode => $barcode } );
398
399 my $limit1 = Koha::Item::Transfer::Limit->new(
400     {
401         toBranch   => $branchcodes[0],
402         fromBranch => $branchcodes[2],
403         itemtype   => $item->effective_itemtype,
404     }
405 )->store();
406
407 C4::HoldsQueue::CreateQueue();
408 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
409 is( $holds_queue->[0]->{cardnumber}, $borrower2->{cardnumber}, "Holds queue skips hold transfer that would violate branch transfer limits");
410
411 my $limit2 = Koha::Item::Transfer::Limit->new(
412     {
413         toBranch   => $branchcodes[1],
414         fromBranch => $branchcodes[2],
415         itemtype   => $item->effective_itemtype,
416     }
417 )->store();
418
419 C4::HoldsQueue::CreateQueue();
420 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
421 is( $holds_queue->[0]->{cardnumber}, undef, "Holds queue doesn't fill hold where all available items would violate branch transfer limits");
422
423 $limit1->delete();
424 $limit2->delete();
425 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' );
426 ### END Test branch transfer limits ###
427
428 # Test holdingbranch = patron branch
429 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary');
430 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch');
431 C4::Context->clear_syspref_cache();
432 $dbh->do("DELETE FROM reserves");
433 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
434 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
435 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
436
437 $dbh->do("DELETE FROM items");
438 # barcode, homebranch, holdingbranch, itemtype
439 $items_insert_sth->execute( $barcode + 4, $branchcodes[0], $branchcodes[2] );
440
441 C4::HoldsQueue::CreateQueue();
442 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
443 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library");
444
445 # Test holdingbranch = pickup branch
446 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'PickupLibrary');
447 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch');
448 C4::Context->clear_syspref_cache();
449 $dbh->do("DELETE FROM reserves");
450 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
451 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
452 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[2], 3 );
453
454 $dbh->do("DELETE FROM items");
455 # barcode, homebranch, holdingbranch, itemtype
456 $items_insert_sth->execute( $barcode + 4, $branchcodes[0], $branchcodes[2] );
457
458 C4::HoldsQueue::CreateQueue();
459 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
460 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library");
461
462 # Test homebranch = pickup branch
463 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'PickupLibrary');
464 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'homebranch');
465 C4::Context->clear_syspref_cache();
466 $dbh->do("DELETE FROM reserves");
467 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
468 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
469 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[2], 3 );
470
471 $dbh->do("DELETE FROM items");
472 # barcode, homebranch, holdingbranch, itemtype
473 $items_insert_sth->execute( $barcode + 4, $branchcodes[2], $branchcodes[0] );
474
475 C4::HoldsQueue::CreateQueue();
476 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
477 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library");
478
479 t::lib::Mocks::mock_preference('LocalHoldsPriority', 0);
480 ## End testing of LocalHoldsPriority
481
482
483 # Bug 14297
484 $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
485 $borrowernumber = $borrower3->{borrowernumber};
486 my $library_A = $library1->{branchcode};
487 my $library_B = $library2->{branchcode};
488 my $library_C = $borrower3->{branchcode};
489 $dbh->do("DELETE FROM reserves");
490 $dbh->do("DELETE FROM issues");
491 $dbh->do("DELETE FROM items");
492 $dbh->do("DELETE FROM biblio");
493 $dbh->do("DELETE FROM biblioitems");
494 $dbh->do("DELETE FROM transport_cost");
495 $dbh->do("DELETE FROM tmp_holdsqueue");
496 $dbh->do("DELETE FROM hold_fill_targets");
497
498 $dbh->do("
499     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
500 ");
501
502 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
503   or BAIL_OUT("Cannot find newly created biblio record");
504
505 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
506
507 $biblioitemnumber =
508   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
509   or BAIL_OUT("Cannot find newly created biblioitems record");
510
511 $dbh->do("
512     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
513     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype')
514 ");
515
516 $dbh->do("
517     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
518     VALUES ($biblionumber, $biblioitemnumber, '$library_B', '$library_B', 0, 0, 0, 0, NULL, '$itemtype')
519 ");
520
521 Koha::CirculationRules->set_rules(
522     {
523         branchcode   => $library_A,
524         itemtype     => $itemtype,
525         rules        => {
526             holdallowed  => 2,
527             returnbranch => 'homebranch',
528         }
529     }
530 );
531
532 $dbh->do( "UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'",
533     undef, join( ',', $library_B, $library_A, $library_C ) );
534 $dbh->do( "UPDATE systempreferences SET value = 0 WHERE variable = 'RandomizeHoldsQueueWeight'" );
535
536 my $reserve_id = AddReserve ( $library_C, $borrowernumber, $biblionumber, '', 1 );
537 C4::HoldsQueue::CreateQueue();
538 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
539 is( @$holds_queue, 1, "Bug 14297 - Holds Queue building ignoring holds where pickup & home branch don't match and item is not from le");
540 # End Bug 14297
541
542 # Bug 15062
543 $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
544 $borrowernumber = $borrower2->{borrowernumber};
545 $library_A = $library1->{branchcode};
546 $library_B = $library2->{branchcode};
547 $dbh->do("DELETE FROM reserves");
548 $dbh->do("DELETE FROM issues");
549 $dbh->do("DELETE FROM items");
550 $dbh->do("DELETE FROM biblio");
551 $dbh->do("DELETE FROM biblioitems");
552 $dbh->do("DELETE FROM transport_cost");
553 $dbh->do("DELETE FROM tmp_holdsqueue");
554 $dbh->do("DELETE FROM hold_fill_targets");
555
556 t::lib::Mocks::mock_preference("UseTransportCostMatrix",1);
557
558 my $tc_rs = $schema->resultset('TransportCost');
559 $tc_rs->create({ frombranch => $library_A, tobranch => $library_B, cost => 0, disable_transfer => 1 });
560 $tc_rs->create({ frombranch => $library_B, tobranch => $library_A, cost => 0, disable_transfer => 1 });
561
562 $dbh->do("
563     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
564 ");
565
566 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
567   or BAIL_OUT("Cannot find newly created biblio record");
568
569 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
570
571 $biblioitemnumber =
572   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
573   or BAIL_OUT("Cannot find newly created biblioitems record");
574
575 $dbh->do("
576     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
577     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype')
578 ");
579
580 $reserve_id = AddReserve ( $library_B, $borrowernumber, $biblionumber, '', 1 );
581 C4::HoldsQueue::CreateQueue();
582 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
583 is( @$holds_queue, 0, "Bug 15062 - Holds queue with Transport Cost Matrix will transfer item even if transfers disabled");
584 # End Bug 15062
585
586 # Test hold_fulfillment_policy
587 t::lib::Mocks::mock_preference( "UseTransportCostMatrix", 0 );
588 $borrowernumber = $borrower3->{borrowernumber};
589 $library_A = $library1->{branchcode};
590 $library_B = $library2->{branchcode};
591 $library_C = $library3->{branchcode};
592 $dbh->do("DELETE FROM reserves");
593 $dbh->do("DELETE FROM issues");
594 $dbh->do("DELETE FROM items");
595 $dbh->do("DELETE FROM biblio");
596 $dbh->do("DELETE FROM biblioitems");
597 $dbh->do("DELETE FROM transport_cost");
598 $dbh->do("DELETE FROM tmp_holdsqueue");
599 $dbh->do("DELETE FROM hold_fill_targets");
600
601 $dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')");
602
603 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
604   or BAIL_OUT("Cannot find newly created biblio record");
605
606 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
607
608 $biblioitemnumber =
609   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
610   or BAIL_OUT("Cannot find newly created biblioitems record");
611
612 $dbh->do("
613     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
614     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_B', 0, 0, 0, 0, NULL, '$itemtype')
615 ");
616
617 # With hold_fulfillment_policy = homebranch, hold should only be picked up if pickup branch = homebranch
618 $dbh->do("DELETE FROM circulation_rules");
619 Koha::CirculationRules->set_rules(
620     {
621         branchcode   => undef,
622         itemtype     => undef,
623         rules        => {
624             holdallowed             => 2,
625             hold_fulfillment_policy => 'homebranch',
626         }
627     }
628 );
629
630 # Home branch matches pickup branch
631 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1 );
632 C4::HoldsQueue::CreateQueue();
633 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
634 is( @$holds_queue, 1, "Hold where pickup branch matches home branch targeted" );
635 Koha::Holds->find( $reserve_id )->cancel;
636
637 # Holding branch matches pickup branch
638 $reserve_id = AddReserve( $library_B, $borrowernumber, $biblionumber, '', 1 );
639 C4::HoldsQueue::CreateQueue();
640 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
641 is( @$holds_queue, 0, "Hold where pickup ne home, pickup eq home not targeted" );
642 Koha::Holds->find( $reserve_id )->cancel;
643
644 # Neither branch matches pickup branch
645 $reserve_id = AddReserve( $library_C, $borrowernumber, $biblionumber, '', 1 );
646 C4::HoldsQueue::CreateQueue();
647 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
648 is( @$holds_queue, 0, "Hold where pickup ne home, pickup ne holding not targeted" );
649 Koha::Holds->find( $reserve_id )->cancel;
650
651 # With hold_fulfillment_policy = holdingbranch, hold should only be picked up if pickup branch = holdingbranch
652 $dbh->do("DELETE FROM circulation_rules");
653 Koha::CirculationRules->set_rules(
654     {
655         branchcode   => undef,
656         itemtype     => undef,
657         rules        => {
658             holdallowed             => 2,
659             hold_fulfillment_policy => 'holdingbranch',
660         }
661     }
662 );
663
664 # Home branch matches pickup branch
665 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1 );
666 C4::HoldsQueue::CreateQueue();
667 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
668 is( @$holds_queue, 0, "Hold where pickup eq home, pickup ne holding not targeted" );
669 Koha::Holds->find( $reserve_id )->cancel;
670
671 # Holding branch matches pickup branch
672 $reserve_id = AddReserve( $library_B, $borrowernumber, $biblionumber, '', 1 );
673 C4::HoldsQueue::CreateQueue();
674 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
675 is( @$holds_queue, 1, "Hold where pickup ne home, pickup eq holding targeted" );
676 Koha::Holds->find( $reserve_id )->cancel;
677
678 # Neither branch matches pickup branch
679 $reserve_id = AddReserve( $library_C, $borrowernumber, $biblionumber, '', 1 );
680 C4::HoldsQueue::CreateQueue();
681 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
682 is( @$holds_queue, 0, "Hold where pickup ne home, pickup ne holding not targeted" );
683 Koha::Holds->find( $reserve_id )->cancel;
684
685 # With hold_fulfillment_policy = any, hold should be pikcup up reguardless of matching home or holding branch
686 $dbh->do("DELETE FROM circulation_rules");
687 Koha::CirculationRules->set_rules(
688     {
689         branchcode   => undef,
690         itemtype     => undef,
691         rules        => {
692             holdallowed             => 2,
693             hold_fulfillment_policy => 'any',
694         }
695     }
696 );
697
698 # Home branch matches pickup branch
699 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1 );
700 C4::HoldsQueue::CreateQueue();
701 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
702 is( @$holds_queue, 1, "Hold where pickup eq home, pickup ne holding targeted" );
703 Koha::Holds->find( $reserve_id )->cancel;
704
705 # Holding branch matches pickup branch
706 $reserve_id = AddReserve( $library_B, $borrowernumber, $biblionumber, '', 1 );
707 C4::HoldsQueue::CreateQueue();
708 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
709 is( @$holds_queue, 1, "Hold where pickup ne home, pickup eq holding targeted" );
710 Koha::Holds->find( $reserve_id )->cancel;
711
712 # Neither branch matches pickup branch
713 $reserve_id = AddReserve( $library_C, $borrowernumber, $biblionumber, '', 1 );
714 C4::HoldsQueue::CreateQueue();
715 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
716 is( @$holds_queue, 1, "Hold where pickup ne home, pickup ne holding targeted" );
717 Koha::Holds->find( $reserve_id )->cancel;
718
719 # End testing hold_fulfillment_policy
720
721 # Test hold itemtype limit
722 t::lib::Mocks::mock_preference( "UseTransportCostMatrix", 0 );
723 my $wrong_itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
724 my $right_itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
725 $borrowernumber = $borrower3->{borrowernumber};
726 my $branchcode = $library1->{branchcode};
727 $dbh->do("DELETE FROM reserves");
728 $dbh->do("DELETE FROM issues");
729 $dbh->do("DELETE FROM items");
730 $dbh->do("DELETE FROM biblio");
731 $dbh->do("DELETE FROM biblioitems");
732 $dbh->do("DELETE FROM transport_cost");
733 $dbh->do("DELETE FROM tmp_holdsqueue");
734 $dbh->do("DELETE FROM hold_fill_targets");
735
736 $dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')");
737
738 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
739   or BAIL_OUT("Cannot find newly created biblio record");
740
741 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
742
743 $biblioitemnumber =
744   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
745   or BAIL_OUT("Cannot find newly created biblioitems record");
746
747 $dbh->do("
748     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
749     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_B', 0, 0, 0, 0, NULL, '$right_itemtype')
750 ");
751
752 # With hold_fulfillment_policy = homebranch, hold should only be picked up if pickup branch = homebranch
753 $dbh->do("DELETE FROM circulation_rules");
754 Koha::CirculationRules->set_rules(
755     {
756         branchcode   => undef,
757         itemtype     => undef,
758         rules        => {
759             holdallowed             => 2,
760             hold_fulfillment_policy => 'any',
761         }
762     }
763 );
764
765 # Home branch matches pickup branch
766 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1, undef, undef, undef, undef, undef, undef, $wrong_itemtype );
767 C4::HoldsQueue::CreateQueue();
768 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
769 is( @$holds_queue, 0, "Item with incorrect itemtype not targeted" );
770 Koha::Holds->find( $reserve_id )->cancel;
771
772 # Holding branch matches pickup branch
773 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1, undef, undef, undef, undef, undef, undef, $right_itemtype );
774 C4::HoldsQueue::CreateQueue();
775 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
776 is( @$holds_queue, 1, "Item with matching itemtype is targeted" );
777 Koha::Holds->find( $reserve_id )->cancel;
778
779 # Neither branch matches pickup branch
780 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1, undef, undef, undef, undef, undef, undef, undef );
781 C4::HoldsQueue::CreateQueue();
782 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
783 is( @$holds_queue, 1, "Item targeted when hold itemtype is not set" );
784 Koha::Holds->find( $reserve_id )->cancel;
785
786 # End testing hold itemtype limit
787
788
789 subtest "Test Local Holds Priority - Bib level" => sub {
790     plan tests => 2;
791
792     Koha::Biblios->delete();
793     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
794     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
795     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
796     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
797     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
798     my $local_patron = $builder->build_object(
799         {
800             class => "Koha::Patrons",
801             value => {
802                 branchcode => $branch->branchcode
803             }
804         }
805     );
806     my $other_patron = $builder->build_object(
807         {
808             class => "Koha::Patrons",
809             value => {
810                 branchcode => $branch2->branchcode
811             }
812         }
813     );
814     my $biblio = $builder->build_sample_biblio();
815     my $item   = $builder->build_sample_item(
816         {
817             biblionumber  => $biblio->biblionumber,
818             library    => $branch->branchcode,
819         }
820     );
821
822     my $reserve_id =
823       AddReserve( $branch2->branchcode, $other_patron->borrowernumber,
824         $biblio->biblionumber, '', 1, undef, undef, undef, undef, undef, undef, undef );
825     my $reserve_id2 =
826       AddReserve( $item->homebranch, $local_patron->borrowernumber,
827         $biblio->biblionumber, '', 2, undef, undef, undef, undef, undef, undef, undef );
828
829     C4::HoldsQueue::CreateQueue();
830
831     my $queue_rs = $schema->resultset('TmpHoldsqueue');
832     is( $queue_rs->count(), 1,
833         "Hold queue contains one hold" );
834     is(
835         $queue_rs->next->borrowernumber,
836         $local_patron->borrowernumber,
837         "We should pick the local hold over the next available"
838     );
839 };
840
841 subtest "Test Local Holds Priority - Item level" => sub {
842     plan tests => 2;
843
844     Koha::Biblios->delete();
845     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
846     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
847     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
848     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
849     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
850     my $local_patron = $builder->build_object(
851         {
852             class => "Koha::Patrons",
853             value => {
854                 branchcode => $branch->branchcode
855             }
856         }
857     );
858     my $other_patron = $builder->build_object(
859         {
860             class => "Koha::Patrons",
861             value => {
862                 branchcode => $branch2->branchcode
863             }
864         }
865     );
866     my $biblio = $builder->build_sample_biblio();
867     my $item   = $builder->build_sample_item(
868         {
869             biblionumber  => $biblio->biblionumber,
870             library    => $branch->branchcode,
871         }
872     );
873
874     my $reserve_id =
875       AddReserve( $branch2->branchcode, $other_patron->borrowernumber,
876         $biblio->biblionumber, '', 1, undef, undef, undef, undef, $item->id, undef, undef );
877     my $reserve_id2 =
878       AddReserve( $item->homebranch, $local_patron->borrowernumber,
879         $biblio->biblionumber, '', 2, undef, undef, undef, undef, $item->id, undef, undef );
880
881     C4::HoldsQueue::CreateQueue();
882
883     my $queue_rs = $schema->resultset('TmpHoldsqueue');
884     my $q = $queue_rs->next;
885     is( $queue_rs->count(), 1,
886         "Hold queue contains one hold" );
887     is(
888         $q->borrowernumber,
889         $local_patron->borrowernumber,
890         "We should pick the local hold over the next available"
891     );
892 };
893
894 subtest "Test Local Holds Priority - Item level hold over Record level hold (Bug 23934)" => sub {
895     plan tests => 2;
896
897     Koha::Biblios->delete();
898     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
899     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
900     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
901     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
902     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
903     my $local_patron = $builder->build_object(
904         {
905             class => "Koha::Patrons",
906             value => {
907                 branchcode => $branch->branchcode
908             }
909         }
910     );
911     my $other_patron = $builder->build_object(
912         {
913             class => "Koha::Patrons",
914             value => {
915                 branchcode => $branch2->branchcode
916             }
917         }
918     );
919     my $biblio = $builder->build_sample_biblio();
920     my $item   = $builder->build_sample_item(
921         {
922             biblionumber  => $biblio->biblionumber,
923             library    => $branch->branchcode,
924         }
925     );
926
927     my $reserve_id =
928       AddReserve( $branch2->branchcode, $other_patron->borrowernumber,
929         $biblio->biblionumber, '', 1, undef, undef, undef, undef, undef, undef, undef );
930     my $reserve_id2 =
931       AddReserve( $item->homebranch, $local_patron->borrowernumber,
932         $biblio->biblionumber, '', 2, undef, undef, undef, undef, $item->id, undef, undef );
933
934     C4::HoldsQueue::CreateQueue();
935
936     my $queue_rs = $schema->resultset('TmpHoldsqueue');
937     my $q = $queue_rs->next;
938     is( $queue_rs->count(), 1,
939         "Hold queue contains one hold" );
940     is(
941         $q->borrowernumber,
942         $local_patron->borrowernumber,
943         "We should pick the local hold over the next available"
944     );
945 };
946
947 subtest "Test Local Holds Priority - Ensure no duplicate requests in holds queue (Bug 18001)" => sub {
948     plan tests => 1;
949
950     $dbh->do("DELETE FROM tmp_holdsqueue");
951     $dbh->do("DELETE FROM hold_fill_targets");
952     $dbh->do("DELETE FROM reserves");
953     $dbh->do("DELETE FROM issuingrules");
954     $dbh->do("DELETE FROM circulation_rules");
955     Koha::Biblios->delete();
956
957     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
958     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
959     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
960     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
961     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
962     my $patron  = $builder->build_object(
963         {
964             class => "Koha::Patrons",
965             value => {
966                 branchcode => $branch->branchcode
967             }
968         }
969     );
970     my $biblio = $builder->build_sample_biblio();
971     my $item1  = $builder->build_sample_item(
972         {
973             biblionumber => $biblio->biblionumber,
974             library      => $branch->branchcode,
975         }
976     );
977     my $item2 = $builder->build_sample_item(
978         {
979             biblionumber => $biblio->biblionumber,
980             library      => $branch->branchcode,
981         }
982     );
983
984     my $item3 = $builder->build_sample_item(
985         {
986             biblionumber => $biblio->biblionumber,
987             library      => $branch->branchcode,
988         }
989     );
990
991     $reserve_id =
992       AddReserve( $item1->homebranch, $patron->borrowernumber, $biblio->id, '',
993         1, undef, undef, undef, undef, undef, undef, undef );
994
995     C4::HoldsQueue::CreateQueue();
996
997     my $queue_rs = $schema->resultset('TmpHoldsqueue');
998
999     is( $queue_rs->count(), 1,
1000         "Hold queue contains one hold from chosen from three possible items" );
1001 };
1002
1003
1004 subtest 'Trivial test for UpdateTransportCostMatrix' => sub {
1005     plan tests => 1;
1006     my $recs = [
1007         { frombranch => $library1->{branchcode}, tobranch => $library2->{branchcode}, cost => 1, disable_transfer => 0 },
1008         { frombranch => $library2->{branchcode}, tobranch => $library3->{branchcode}, cost => 0, disable_transfer => 1 },
1009     ];
1010     C4::HoldsQueue::UpdateTransportCostMatrix( $recs );
1011     is( $schema->resultset('TransportCost')->count, 2, 'UpdateTransportCostMatrix added two records' );
1012 };
1013
1014 # Cleanup
1015 $schema->storage->txn_rollback;
1016
1017 ### END Test holds queue builder does not violate holds policy ###
1018
1019 sub test_queue {
1020     my ($test_name, $use_cost_matrix, $pick_branch, $hold_branch) = @_;
1021
1022     $test_name = "$test_name (".($use_cost_matrix ? "" : "don't ")."use cost matrix)";
1023
1024     $use_cost_matrix_sth->execute($use_cost_matrix);
1025     C4::Context->clear_syspref_cache();
1026     C4::HoldsQueue::CreateQueue();
1027
1028     my $results = $dbh->selectall_arrayref($test_sth, { Slice => {} }); # should be only one
1029     my $r = $results->[0];
1030
1031     my $ok = is( $r->{pickbranch}, $pick_branch, "$test_name pick up branch");
1032     $ok &&=  is( $r->{holdingbranch}, $hold_branch, "$test_name holding branch")
1033       if $hold_branch;
1034
1035     diag( "Wrong pick-up/hold for first target (pick_branch, hold_branch, reserves, hold_fill_targets, tmp_holdsqueue): "
1036         . Dumper ($pick_branch, $hold_branch, map dump_records($_), qw(reserves hold_fill_targets tmp_holdsqueue)) )
1037       unless $ok;
1038
1039     # Test enforcement of branch transfer limit
1040     if ( $r->{pickbranch} ne $r->{holdingbranch} ) {
1041         t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' );
1042         my $limit = Koha::Item::Transfer::Limit->new(
1043             {
1044                 toBranch   => $r->{pickbranch},
1045                 fromBranch => $r->{holdingbranch},
1046                 itemtype   => $r->{itype},
1047             }
1048         )->store();
1049         C4::Context->clear_syspref_cache();
1050         C4::HoldsQueue::CreateQueue();
1051         $results = $dbh->selectall_arrayref( $test_sth, { Slice => {} } )
1052           ;    # should be only one
1053         my $s = $results->[0];
1054         isnt( $r->{holdingbranch}, $s->{holdingbranch}, 'Hold is not trapped for pickup at a branch that cannot be transferred to');
1055
1056         $limit->delete();
1057         t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' );
1058         C4::Context->clear_syspref_cache();
1059         C4::HoldsQueue::CreateQueue();
1060     }
1061
1062 }
1063
1064 sub dump_records {
1065     my ($tablename) = @_;
1066     return $dbh->selectall_arrayref("SELECT * from $tablename where borrowernumber = ?", { Slice => {} }, $borrowernumber);
1067 }