Bug 15532: Add ability to allow only items whose home/holding branch matches the...
[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 => 35;
12 use Data::Dumper;
13
14
15 use C4::Branch;
16 use C4::Calendar;
17 use C4::Context;
18 use C4::Members;
19 use Koha::Database;
20 use Koha::DateUtils;
21 use Koha::ItemType;
22
23 use t::lib::TestBuilder;
24
25 use Koha::ItemTypes;
26
27 BEGIN {
28     use FindBin;
29     use lib $FindBin::Bin;
30     use_ok('C4::Reserves');
31     use_ok('C4::HoldsQueue');
32 }
33
34 my $schema = Koha::Database->schema;
35 $schema->storage->txn_begin;
36 my $dbh = C4::Context->dbh;
37
38 my $builder = t::lib::TestBuilder->new;
39
40 my $library1 = $builder->build({
41     source => 'Branch',
42 });
43 my $library2 = $builder->build({
44     source => 'Branch',
45 });
46 my $library3 = $builder->build({
47     source => 'Branch',
48 });
49
50 my $TITLE = "Test Holds Queue XXX";
51
52 my $borrower = $builder->build({
53     source => 'Borrower',
54     value => {
55         branchcode => $library1->{branchcode},
56     }
57 });
58
59 my $borrowernumber = $borrower->{borrowernumber};
60 # Set special (for this test) branches
61 my $borrower_branchcode = $borrower->{branchcode};
62 my @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} );
63 my @other_branches = ( $library2->{branchcode}, $library3->{branchcode} );
64 my $least_cost_branch_code = pop @other_branches;
65 my $itemtype = Koha::ItemTypes->search({ notforloan => 1 })->next;
66 $itemtype or BAIL_OUT("No adequate itemtype"); #FIXME Should be $itemtype = $itemtype->itemtype
67
68 #Set up the stage
69 # Sysprefs and cost matrix
70 C4::Context->set_preference('HoldsQueueSkipClosed', 0);
71 $dbh->do("UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'", undef,
72          join( ',', @other_branches, $borrower_branchcode, $least_cost_branch_code));
73 $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'RandomizeHoldsQueueWeight'");
74
75 $dbh->do("DELETE FROM transport_cost");
76 my $transport_cost_insert_sth = $dbh->prepare("insert into transport_cost (frombranch, tobranch, cost) values (?, ?, ?)");
77 # Favour $least_cost_branch_code
78 $transport_cost_insert_sth->execute($borrower_branchcode, $least_cost_branch_code, 0.2);
79 $transport_cost_insert_sth->execute($least_cost_branch_code, $borrower_branchcode, 0.2);
80 my @b = @other_branches;
81 while ( my $b1 = shift @b ) {
82     foreach my $b2 ($borrower_branchcode, $least_cost_branch_code, @b) {
83         $transport_cost_insert_sth->execute($b1, $b2, 0.5);
84         $transport_cost_insert_sth->execute($b2, $b1, 0.5);
85     }
86 }
87
88
89 # Loanable items - all possible combinations of homebranch and holdingbranch
90 $dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated)
91           VALUES             ('SER', 'Koha test', '$TITLE', '2011-02-01')");
92 my $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
93   or BAIL_OUT("Cannot find newly created biblio record");
94 $dbh->do("INSERT INTO biblioitems (biblionumber, marcxml, itemtype)
95           VALUES                  ($biblionumber, '', '$itemtype')");
96 my $biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
97   or BAIL_OUT("Cannot find newly created biblioitems record");
98
99 my $items_insert_sth = $dbh->prepare("INSERT INTO items (biblionumber, biblioitemnumber, barcode, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
100                                       VALUES            ($biblionumber, $biblioitemnumber, ?, ?, ?, 0, 0, 0, 0, NULL, '$itemtype')"); # CURRENT_DATE - 3)");
101 my $first_barcode = int(rand(1000000000000)); # XXX
102 my $barcode = $first_barcode;
103 foreach ( $borrower_branchcode, $least_cost_branch_code, @other_branches ) {
104     $items_insert_sth->execute($barcode++, $borrower_branchcode, $_);
105     $items_insert_sth->execute($barcode++, $_, $_);
106     $items_insert_sth->execute($barcode++, $_, $borrower_branchcode);
107 }
108
109 # Remove existing reserves, makes debugging easier
110 $dbh->do("DELETE FROM reserves");
111 my $bibitems = undef;
112 my $priority = 1;
113 # Make a reserve
114 AddReserve ( $borrower_branchcode, $borrowernumber, $biblionumber, $bibitems,  $priority );
115 #                           $resdate, $expdate, $notes, $title, $checkitem, $found
116 $dbh->do("UPDATE reserves SET reservedate = DATE_SUB( reservedate, INTERVAL 1 DAY )");
117
118 # Tests
119 my $use_cost_matrix_sth = $dbh->prepare("UPDATE systempreferences SET value = ? WHERE variable = 'UseTransportCostMatrix'");
120 my $test_sth = $dbh->prepare("SELECT * FROM hold_fill_targets
121                               JOIN tmp_holdsqueue USING (borrowernumber, biblionumber, itemnumber)
122                               JOIN items USING (itemnumber)
123                               WHERE borrowernumber = $borrowernumber");
124
125 # We have a book available homed in borrower branch, no point fiddling with AutomaticItemReturn
126 C4::Context->set_preference('AutomaticItemReturn', 0);
127 test_queue ('take from homebranch',  0, $borrower_branchcode, $borrower_branchcode);
128 test_queue ('take from homebranch',  1, $borrower_branchcode, $borrower_branchcode);
129
130 $dbh->do("DELETE FROM tmp_holdsqueue");
131 $dbh->do("DELETE FROM hold_fill_targets");
132 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode')");
133 $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode'");
134 # test_queue will flush
135 C4::Context->set_preference('AutomaticItemReturn', 1);
136 # Not sure how to make this test more difficult - holding branch does not matter
137
138 $dbh->do("DELETE FROM tmp_holdsqueue");
139 $dbh->do("DELETE FROM hold_fill_targets");
140 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode')");
141 $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode'");
142 C4::Context->set_preference('AutomaticItemReturn', 0);
143 # We have a book available held in borrower branch
144 test_queue ('take from holdingbranch', 0, $borrower_branchcode, $borrower_branchcode);
145 test_queue ('take from holdingbranch', 1, $borrower_branchcode, $borrower_branchcode);
146
147 $dbh->do("DELETE FROM tmp_holdsqueue");
148 $dbh->do("DELETE FROM hold_fill_targets");
149 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE holdingbranch = '$borrower_branchcode')");
150 $dbh->do("DELETE FROM items WHERE holdingbranch = '$borrower_branchcode'");
151 # No book available in borrower branch, pick according to the rules
152 # Frst branch from StaticHoldsQueueWeight
153 test_queue ('take from lowest cost branch', 0, $borrower_branchcode, $other_branches[0]);
154 test_queue ('take from lowest cost branch', 1, $borrower_branchcode, $least_cost_branch_code);
155 my $queue = C4::HoldsQueue::GetHoldsQueueItems($least_cost_branch_code) || [];
156 my $queue_item = $queue->[0];
157 ok( $queue_item
158  && $queue_item->{pickbranch} eq $borrower_branchcode
159  && $queue_item->{holdingbranch} eq $least_cost_branch_code, "GetHoldsQueueItems" )
160   or diag( "Expected item for pick $borrower_branchcode, hold $least_cost_branch_code, got ".Dumper($queue_item) );
161 ok( exists($queue_item->{itype}), 'item type included in queued items list (bug 5825)' );
162
163 ok(
164     C4::HoldsQueue::least_cost_branch( 'B', [ 'A', 'B', 'C' ] ) eq 'B',
165     'C4::HoldsQueue::least_cost_branch returns the local branch if it is in the list of branches to pull from'
166 );
167
168 # XXX All this tests are for borrower branch pick-up.
169 # Maybe needs expanding to homebranch or holdingbranch pick-up.
170
171 $schema->txn_rollback;
172 $schema->txn_begin;
173
174 ### Test holds queue builder does not violate holds policy ###
175
176 # Clear out existing rules relating to holdallowed
177 $dbh->do("DELETE FROM default_branch_circ_rules");
178 $dbh->do("DELETE FROM default_branch_item_rules");
179 $dbh->do("DELETE FROM default_circ_rules");
180
181 C4::Context->set_preference('UseTransportCostMatrix', 0);
182
183 $itemtype = Koha::ItemTypes->search->next->itemtype;
184
185 $library1 = $builder->build({
186     source => 'Branch',
187 });
188 $library2 = $builder->build({
189     source => 'Branch',
190 });
191 $library3 = $builder->build({
192     source => 'Branch',
193 });
194 @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} );
195
196 my $borrower1 = $builder->build({
197     source => 'Borrower',
198     value => {
199         branchcode => $branchcodes[0],
200     },
201 });
202 my $borrower2 = $builder->build({
203     source => 'Borrower',
204     value => {
205         branchcode => $branchcodes[1],
206     },
207 });
208 my $borrower3 = $builder->build({
209     source => 'Borrower',
210     value => {
211         branchcode => $branchcodes[2],
212     },
213 });
214
215 $dbh->do(qq{
216     INSERT INTO biblio (
217         frameworkcode, 
218         author, 
219         title, 
220         datecreated
221     ) VALUES (
222         'SER', 
223         'Koha test', 
224         '$TITLE', 
225         '2011-02-01'
226     )
227 });
228 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
229   or BAIL_OUT("Cannot find newly created biblio record");
230
231 $dbh->do(qq{
232     INSERT INTO biblioitems (
233         biblionumber, 
234         marcxml, 
235         itemtype
236     ) VALUES (
237         $biblionumber, 
238         '', 
239         '$itemtype'
240     )
241 });
242 $biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
243   or BAIL_OUT("Cannot find newly created biblioitems record");
244
245 $items_insert_sth = $dbh->prepare(qq{
246     INSERT INTO items (
247         biblionumber, 
248         biblioitemnumber,
249         barcode,
250         homebranch,
251         holdingbranch,
252         notforloan,
253         damaged,
254         itemlost,
255         withdrawn,
256         onloan,
257         itype
258     ) VALUES (
259         $biblionumber,
260         $biblioitemnumber,
261         ?,
262         ?,
263         ?,
264         0,
265         0,
266         0,
267         0,
268         NULL,
269         '$itemtype'
270     )
271 });
272 # Create 3 items from 2 branches ( branches are for borrowers 1 and 2 respectively )
273 $barcode = int( rand(1000000000000) );
274 $items_insert_sth->execute( $barcode + 0, $branchcodes[0], $branchcodes[0] );
275 $items_insert_sth->execute( $barcode + 1, $branchcodes[1], $branchcodes[1] );
276 $items_insert_sth->execute( $barcode + 2, $branchcodes[1], $branchcodes[1] );
277
278 $dbh->do("DELETE FROM reserves");
279 my $sth = $dbh->prepare(q{
280     INSERT INTO reserves ( 
281         borrowernumber,
282         biblionumber,
283         branchcode,
284         priority,
285         reservedate
286     ) VALUES ( ?,?,?,?, CURRENT_DATE() )
287 });
288 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
289 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
290 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
291
292 my $holds_queue;
293
294 $dbh->do("DELETE FROM default_circ_rules");
295 $dbh->do("INSERT INTO default_circ_rules ( holdallowed ) VALUES ( 1 )");
296 C4::HoldsQueue::CreateQueue();
297 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
298 is( @$holds_queue, 2, "Holds queue filling correct number for default holds policy 'from home library'" );
299 is( $holds_queue->[0]->{cardnumber}, $borrower1->{cardnumber}, "Holds queue filling 1st correct hold for default holds policy 'from home library'");
300 is( $holds_queue->[1]->{cardnumber}, $borrower2->{cardnumber}, "Holds queue filling 2nd correct hold for default holds policy 'from home library'");
301
302 # Test skipping hold picks for closed libraries.
303 # At this point in the test, we have 2 rows in the holds queue
304 # 1 of which is coming from MPL. Let's enable HoldsQueueSkipClosed
305 # and make today a holiday for MPL. When we run it again we should only
306 # have 1 row in the holds queue
307 C4::Context->set_preference('HoldsQueueSkipClosed', 1);
308 my $today = dt_from_string();
309 C4::Calendar->new( branchcode => $branchcodes[0] )->insert_single_holiday(
310     day         => $today->day(),
311     month       => $today->month(),
312     year        => $today->year(),
313     title       => "$today",
314     description => "$today",
315 );
316 # If the test below is removed, aother tests using the holiday will fail. For some reason if we call is_holiday now
317 # the holiday will get set in cache correctly, but not if we let C4::HoldsQueue call is_holiday instead.
318 is( Koha::Calendar->new( branchcode => $branchcodes[0] )->is_holiday( $today ), 1, 'Is today a holiday for pickup branch' );
319 C4::HoldsQueue::CreateQueue();
320 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
321 is( scalar( @$holds_queue ), 1, "Holds not filled with items from closed libraries" );
322 C4::Context->set_preference('HoldsQueueSkipClosed', 0);
323
324 $dbh->do("DELETE FROM default_circ_rules");
325 $dbh->do("INSERT INTO default_circ_rules ( holdallowed ) VALUES ( 2 )");
326 C4::HoldsQueue::CreateQueue();
327 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
328 is( @$holds_queue, 3, "Holds queue filling correct number for holds for default holds policy 'from any library'" );
329
330 # Test skipping hold picks for closed libraries without transport cost matrix
331 # At this point in the test, we have 3 rows in the holds queue
332 # one of which is coming from MPL. Let's enable HoldsQueueSkipClosed
333 # and use our previously created holiday for MPL
334 # When we run it again we should only have 2 rows in the holds queue
335 C4::Context->set_preference( 'HoldsQueueSkipClosed', 1 );
336 C4::HoldsQueue::CreateQueue();
337 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
338 is( scalar( @$holds_queue ), 2, "Holds not filled with items from closed libraries" );
339 C4::Context->set_preference( 'HoldsQueueSkipClosed', 0 );
340
341 # Bug 14297
342 $itemtype = Koha::ItemTypes->search->next->itemtype;
343 $borrowernumber = $borrower3->{borrowernumber};
344 my $library_A = $library1->{branchcode};
345 my $library_B = $library2->{branchcode};
346 my $library_C = $borrower3->{branchcode};
347 $dbh->do("DELETE FROM reserves");
348 $dbh->do("DELETE FROM issues");
349 $dbh->do("DELETE FROM items");
350 $dbh->do("DELETE FROM biblio");
351 $dbh->do("DELETE FROM biblioitems");
352 $dbh->do("DELETE FROM transport_cost");
353 $dbh->do("DELETE FROM tmp_holdsqueue");
354 $dbh->do("DELETE FROM hold_fill_targets");
355 $dbh->do("DELETE FROM default_branch_circ_rules");
356 $dbh->do("DELETE FROM default_branch_item_rules");
357 $dbh->do("DELETE FROM default_circ_rules");
358 $dbh->do("DELETE FROM branch_item_rules");
359
360 $dbh->do("
361     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
362 ");
363
364 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
365   or BAIL_OUT("Cannot find newly created biblio record");
366
367 $dbh->do("INSERT INTO biblioitems (biblionumber, marcxml, itemtype) VALUES ($biblionumber, '', '$itemtype')");
368
369 $biblioitemnumber =
370   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
371   or BAIL_OUT("Cannot find newly created biblioitems record");
372
373 $dbh->do("
374     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
375     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype')
376 ");
377
378 $dbh->do("
379     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
380     VALUES ($biblionumber, $biblioitemnumber, '$library_B', '$library_B', 0, 0, 0, 0, NULL, '$itemtype')
381 ");
382
383 $dbh->do("
384     INSERT INTO branch_item_rules ( branchcode, itemtype, holdallowed, returnbranch ) VALUES
385     ( '$library_A', '$itemtype', 2, 'homebranch' ), ( '$library_B', '$itemtype', 1, 'homebranch' );
386 ");
387
388 $dbh->do( "UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'",
389     undef, join( ',', $library_B, $library_A, $library_C ) );
390 $dbh->do( "UPDATE systempreferences SET value = 0 WHERE variable = 'RandomizeHoldsQueueWeight'" );
391
392 my $reserve_id = AddReserve ( $library_C, $borrowernumber, $biblionumber, '', 1 );
393 C4::HoldsQueue::CreateQueue();
394 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
395 is( @$holds_queue, 1, "Bug 14297 - Holds Queue building ignoring holds where pickup & home branch don't match and item is not from le");
396 # End Bug 14297
397
398 # Bug 15062
399 $itemtype = Koha::ItemTypes->search->next->itemtype;
400 $borrowernumber = $borrower2->{borrowernumber};
401 $library_A = $library1->{branchcode};
402 $library_B = $library2->{branchcode};
403 $dbh->do("DELETE FROM reserves");
404 $dbh->do("DELETE FROM issues");
405 $dbh->do("DELETE FROM items");
406 $dbh->do("DELETE FROM biblio");
407 $dbh->do("DELETE FROM biblioitems");
408 $dbh->do("DELETE FROM transport_cost");
409 $dbh->do("DELETE FROM tmp_holdsqueue");
410 $dbh->do("DELETE FROM hold_fill_targets");
411 $dbh->do("DELETE FROM default_branch_circ_rules");
412 $dbh->do("DELETE FROM default_branch_item_rules");
413 $dbh->do("DELETE FROM default_circ_rules");
414 $dbh->do("DELETE FROM branch_item_rules");
415
416 C4::Context->set_preference("UseTransportCostMatrix",1);
417
418 my $tc_rs = $schema->resultset('TransportCost');
419 $tc_rs->create({ frombranch => $library_A, tobranch => $library_B, cost => 0, disable_transfer => 1 });
420 $tc_rs->create({ frombranch => $library_B, tobranch => $library_A, cost => 0, disable_transfer => 1 });
421
422 $dbh->do("
423     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
424 ");
425
426 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
427   or BAIL_OUT("Cannot find newly created biblio record");
428
429 $dbh->do("INSERT INTO biblioitems (biblionumber, marcxml, itemtype) VALUES ($biblionumber, '', '$itemtype')");
430
431 $biblioitemnumber =
432   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
433   or BAIL_OUT("Cannot find newly created biblioitems record");
434
435 $dbh->do("
436     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
437     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype')
438 ");
439
440 $reserve_id = AddReserve ( $library_B, $borrowernumber, $biblionumber, '', 1 );
441 C4::HoldsQueue::CreateQueue();
442 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
443 is( @$holds_queue, 0, "Bug 15062 - Holds queue with Transport Cost Matrix will transfer item even if transfers disabled");
444 # End Bug 15062
445
446 # Test hold_fulfillment_policy
447 C4::Context->set_preference( "UseTransportCostMatrix", 0 );
448 $borrowernumber = $borrower3->{borrowernumber};
449 $library_A = $library1->{branchcode};
450 $library_B = $library2->{branchcode};
451 $library_C = $library3->{branchcode};
452 $dbh->do("DELETE FROM reserves");
453 $dbh->do("DELETE FROM issues");
454 $dbh->do("DELETE FROM items");
455 $dbh->do("DELETE FROM biblio");
456 $dbh->do("DELETE FROM biblioitems");
457 $dbh->do("DELETE FROM transport_cost");
458 $dbh->do("DELETE FROM tmp_holdsqueue");
459 $dbh->do("DELETE FROM hold_fill_targets");
460 $dbh->do("DELETE FROM default_branch_circ_rules");
461 $dbh->do("DELETE FROM default_branch_item_rules");
462 $dbh->do("DELETE FROM default_circ_rules");
463 $dbh->do("DELETE FROM branch_item_rules");
464
465 $dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')");
466
467 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
468   or BAIL_OUT("Cannot find newly created biblio record");
469
470 $dbh->do("INSERT INTO biblioitems (biblionumber, marcxml, itemtype) VALUES ($biblionumber, '', '$itemtype')");
471
472 $biblioitemnumber =
473   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
474   or BAIL_OUT("Cannot find newly created biblioitems record");
475
476 $dbh->do("
477     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
478     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_B', 0, 0, 0, 0, NULL, '$itemtype')
479 ");
480
481 # With hold_fulfillment_policy = homebranch, hold should only be picked up if pickup branch = homebranch
482 $dbh->do("DELETE FROM default_circ_rules");
483 $dbh->do("INSERT INTO default_circ_rules ( holdallowed, hold_fulfillment_policy ) VALUES ( 2, 'homebranch' )");
484
485 # Home branch matches pickup branch
486 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1 );
487 C4::HoldsQueue::CreateQueue();
488 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
489 is( @$holds_queue, 1, "Hold where pickup branch matches home branch targeted" );
490 CancelReserve( { reserve_id => $reserve_id } );
491
492 # Holding branch matches pickup branch
493 $reserve_id = AddReserve( $library_B, $borrowernumber, $biblionumber, '', 1 );
494 C4::HoldsQueue::CreateQueue();
495 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
496 is( @$holds_queue, 0, "Hold where pickup ne home, pickup eq home not targeted" );
497 CancelReserve( { reserve_id => $reserve_id } );
498
499 # Neither branch matches pickup branch
500 $reserve_id = AddReserve( $library_C, $borrowernumber, $biblionumber, '', 1 );
501 C4::HoldsQueue::CreateQueue();
502 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
503 is( @$holds_queue, 0, "Hold where pickup ne home, pickup ne holding not targeted" );
504 CancelReserve( { reserve_id => $reserve_id } );
505
506 # With hold_fulfillment_policy = holdingbranch, hold should only be picked up if pickup branch = holdingbranch
507 $dbh->do("DELETE FROM default_circ_rules");
508 $dbh->do("INSERT INTO default_circ_rules ( holdallowed, hold_fulfillment_policy ) VALUES ( 2, 'holdingbranch' )");
509
510 # Home branch matches pickup branch
511 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1 );
512 C4::HoldsQueue::CreateQueue();
513 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
514 is( @$holds_queue, 0, "Hold where pickup eq home, pickup ne holding not targeted" );
515 CancelReserve( { reserve_id => $reserve_id } );
516
517 # Holding branch matches pickup branch
518 $reserve_id = AddReserve( $library_B, $borrowernumber, $biblionumber, '', 1 );
519 C4::HoldsQueue::CreateQueue();
520 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
521 is( @$holds_queue, 1, "Hold where pickup ne home, pickup eq holding targeted" );
522 CancelReserve( { reserve_id => $reserve_id } );
523
524 # Neither branch matches pickup branch
525 $reserve_id = AddReserve( $library_C, $borrowernumber, $biblionumber, '', 1 );
526 C4::HoldsQueue::CreateQueue();
527 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
528 is( @$holds_queue, 0, "Hold where pickup ne home, pickup ne holding not targeted" );
529 CancelReserve( { reserve_id => $reserve_id } );
530
531 # With hold_fulfillment_policy = any, hold should be pikcup up reguardless of matching home or holding branch
532 $dbh->do("DELETE FROM default_circ_rules");
533 $dbh->do("INSERT INTO default_circ_rules ( holdallowed, hold_fulfillment_policy ) VALUES ( 2, 'any' )");
534
535 # Home branch matches pickup branch
536 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1 );
537 C4::HoldsQueue::CreateQueue();
538 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
539 is( @$holds_queue, 1, "Hold where pickup eq home, pickup ne holding targeted" );
540 CancelReserve( { reserve_id => $reserve_id } );
541
542 # Holding branch matches pickup branch
543 $reserve_id = AddReserve( $library_B, $borrowernumber, $biblionumber, '', 1 );
544 C4::HoldsQueue::CreateQueue();
545 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
546 is( @$holds_queue, 1, "Hold where pickup ne home, pickup eq holding targeted" );
547 CancelReserve( { reserve_id => $reserve_id } );
548
549 # Neither branch matches pickup branch
550 $reserve_id = AddReserve( $library_C, $borrowernumber, $biblionumber, '', 1 );
551 C4::HoldsQueue::CreateQueue();
552 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
553 is( @$holds_queue, 1, "Hold where pickup ne home, pickup ne holding targeted" );
554 CancelReserve( { reserve_id => $reserve_id } );
555
556 # End testing hold_fulfillment_policy
557
558 # Cleanup
559 $schema->storage->txn_rollback;
560
561 ### END Test holds queue builder does not violate holds policy ###
562
563 sub test_queue {
564     my ($test_name, $use_cost_matrix, $pick_branch, $hold_branch) = @_;
565
566     $test_name = "$test_name (".($use_cost_matrix ? "" : "don't ")."use cost matrix)";
567
568     $use_cost_matrix_sth->execute($use_cost_matrix);
569     C4::Context->clear_syspref_cache();
570     C4::HoldsQueue::CreateQueue();
571
572     my $results = $dbh->selectall_arrayref($test_sth, { Slice => {} }); # should be only one
573     my $r = $results->[0];
574
575     my $ok = is( $r->{pickbranch}, $pick_branch, "$test_name pick up branch");
576     $ok &&=  is( $r->{holdingbranch}, $hold_branch, "$test_name holding branch")
577       if $hold_branch;
578
579     diag( "Wrong pick-up/hold for first target (pick_branch, hold_branch, reserves, hold_fill_targets, tmp_holdsqueue): "
580         . Dumper ($pick_branch, $hold_branch, map dump_records($_), qw(reserves hold_fill_targets tmp_holdsqueue)) )
581       unless $ok;
582 }
583
584 sub dump_records {
585     my ($tablename) = @_;
586     return $dbh->selectall_arrayref("SELECT * from $tablename where borrowernumber = ?", { Slice => {} }, $borrowernumber);
587 }