Bug 22330: Transfer limits should be respected for placing holds in staff interface...
[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 => 48;
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
22 use t::lib::TestBuilder;
23 use t::lib::Mocks;
24
25 BEGIN {
26     use FindBin;
27     use lib $FindBin::Bin;
28     use_ok('C4::Reserves');
29     use_ok('C4::HoldsQueue');
30 }
31
32 my $schema = Koha::Database->schema;
33 $schema->storage->txn_begin;
34 my $dbh = C4::Context->dbh;
35
36 my $builder = t::lib::TestBuilder->new;
37
38 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits',  '0' );
39 t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' );
40
41 my $library1 = $builder->build({
42     source => 'Branch',
43 });
44 my $library2 = $builder->build({
45     source => 'Branch',
46 });
47 my $library3 = $builder->build({
48     source => 'Branch',
49 });
50
51 my $TITLE = "Test Holds Queue XXX";
52
53 my $borrower = $builder->build({
54     source => 'Borrower',
55     value => {
56         branchcode => $library1->{branchcode},
57     }
58 });
59
60 my $borrowernumber = $borrower->{borrowernumber};
61 # Set special (for this test) branches
62 my $borrower_branchcode = $borrower->{branchcode};
63 my @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} );
64 my @other_branches = ( $library2->{branchcode}, $library3->{branchcode} );
65 my $least_cost_branch_code = pop @other_branches;
66 my $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
67
68 #Set up the stage
69 # Sysprefs and cost matrix
70 t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 0);
71 t::lib::Mocks::mock_preference('LocalHoldsPriority', 0);
72 $dbh->do("UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'", undef,
73          join( ',', @other_branches, $borrower_branchcode, $least_cost_branch_code));
74 $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'RandomizeHoldsQueueWeight'");
75
76 $dbh->do("DELETE FROM transport_cost");
77 my $transport_cost_insert_sth = $dbh->prepare("insert into transport_cost (frombranch, tobranch, cost) values (?, ?, ?)");
78 # Favour $least_cost_branch_code
79 $transport_cost_insert_sth->execute($borrower_branchcode, $least_cost_branch_code, 0.2);
80 $transport_cost_insert_sth->execute($least_cost_branch_code, $borrower_branchcode, 0.2);
81 my @b = @other_branches;
82 while ( my $b1 = shift @b ) {
83     foreach my $b2 ($borrower_branchcode, $least_cost_branch_code, @b) {
84         $transport_cost_insert_sth->execute($b1, $b2, 0.5);
85         $transport_cost_insert_sth->execute($b2, $b1, 0.5);
86     }
87 }
88
89
90 # Loanable items - all possible combinations of homebranch and holdingbranch
91 $dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated)
92           VALUES             ('SER', 'Koha test', '$TITLE', '2011-02-01')");
93 my $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
94   or BAIL_OUT("Cannot find newly created biblio record");
95 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype)
96           VALUES                  ($biblionumber, '$itemtype')");
97 my $biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
98   or BAIL_OUT("Cannot find newly created biblioitems record");
99
100 my $items_insert_sth = $dbh->prepare("INSERT INTO items (biblionumber, biblioitemnumber, barcode, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
101                                       VALUES            ($biblionumber, $biblioitemnumber, ?, ?, ?, 0, 0, 0, 0, NULL, '$itemtype')"); # CURRENT_DATE - 3)");
102 my $first_barcode = int(rand(1000000000000)); # XXX
103 my $barcode = $first_barcode;
104 foreach ( $borrower_branchcode, $least_cost_branch_code, @other_branches ) {
105     $items_insert_sth->execute($barcode++, $borrower_branchcode, $_);
106     $items_insert_sth->execute($barcode++, $_, $_);
107     $items_insert_sth->execute($barcode++, $_, $borrower_branchcode);
108 }
109
110 # Remove existing reserves, makes debugging easier
111 $dbh->do("DELETE FROM reserves");
112 my $bibitems = undef;
113 my $priority = 1;
114 # Make a reserve
115 AddReserve ( $borrower_branchcode, $borrowernumber, $biblionumber, $bibitems,  $priority );
116 #                           $resdate, $expdate, $notes, $title, $checkitem, $found
117 $dbh->do("UPDATE reserves SET reservedate = DATE_SUB( reservedate, INTERVAL 1 DAY )");
118
119 # Tests
120 my $use_cost_matrix_sth = $dbh->prepare("UPDATE systempreferences SET value = ? WHERE variable = 'UseTransportCostMatrix'");
121 my $test_sth = $dbh->prepare("SELECT * FROM hold_fill_targets
122                               JOIN tmp_holdsqueue USING (borrowernumber, biblionumber, itemnumber)
123                               JOIN items USING (itemnumber)
124                               WHERE borrowernumber = $borrowernumber");
125
126 # We have a book available homed in borrower branch, no point fiddling with AutomaticItemReturn
127 t::lib::Mocks::mock_preference('AutomaticItemReturn', 0);
128 test_queue ('take from homebranch',  0, $borrower_branchcode, $borrower_branchcode);
129 test_queue ('take from homebranch',  1, $borrower_branchcode, $borrower_branchcode);
130
131 $dbh->do("DELETE FROM tmp_holdsqueue");
132 $dbh->do("DELETE FROM hold_fill_targets");
133 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode')");
134 $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode'");
135 # test_queue will flush
136 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
137 # Not sure how to make this test more difficult - holding branch does not matter
138
139 $dbh->do("DELETE FROM tmp_holdsqueue");
140 $dbh->do("DELETE FROM hold_fill_targets");
141 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode')");
142 $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode'");
143 t::lib::Mocks::mock_preference('AutomaticItemReturn', 0);
144 # We have a book available held in borrower branch
145 test_queue ('take from holdingbranch', 0, $borrower_branchcode, $borrower_branchcode);
146 test_queue ('take from holdingbranch', 1, $borrower_branchcode, $borrower_branchcode);
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 holdingbranch = '$borrower_branchcode')");
151 $dbh->do("DELETE FROM items WHERE holdingbranch = '$borrower_branchcode'");
152 # No book available in borrower branch, pick according to the rules
153 # Frst branch from StaticHoldsQueueWeight
154 test_queue ('take from lowest cost branch', 0, $borrower_branchcode, $other_branches[0]);
155 test_queue ('take from lowest cost branch', 1, $borrower_branchcode, $least_cost_branch_code);
156 my $queue = C4::HoldsQueue::GetHoldsQueueItems($least_cost_branch_code) || [];
157 my $queue_item = $queue->[0];
158 ok( $queue_item
159  && $queue_item->{pickbranch} eq $borrower_branchcode
160  && $queue_item->{holdingbranch} eq $least_cost_branch_code, "GetHoldsQueueItems" )
161   or diag( "Expected item for pick $borrower_branchcode, hold $least_cost_branch_code, got ".Dumper($queue_item) );
162 ok( exists($queue_item->{itype}), 'item type included in queued items list (bug 5825)' );
163
164 ok(
165     C4::HoldsQueue::least_cost_branch( 'B', [ 'A', 'B', 'C' ] ) eq 'B',
166     'C4::HoldsQueue::least_cost_branch returns the local branch if it is in the list of branches to pull from'
167 );
168
169 # XXX All this tests are for borrower branch pick-up.
170 # Maybe needs expanding to homebranch or holdingbranch pick-up.
171
172 $schema->txn_rollback;
173 $schema->txn_begin;
174
175 ### Test holds queue builder does not violate holds policy ###
176
177 # Clear out existing rules relating to holdallowed
178 $dbh->do("DELETE FROM default_branch_circ_rules");
179 $dbh->do("DELETE FROM default_branch_item_rules");
180 $dbh->do("DELETE FROM default_circ_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 default_circ_rules");
294 $dbh->do("INSERT INTO default_circ_rules ( holdallowed ) VALUES ( 1 )");
295 C4::HoldsQueue::CreateQueue();
296 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
297 is( @$holds_queue, 2, "Holds queue filling correct number for default holds policy 'from home library'" );
298 is( $holds_queue->[0]->{cardnumber}, $borrower1->{cardnumber}, "Holds queue filling 1st correct hold for default holds policy 'from home library'");
299 is( $holds_queue->[1]->{cardnumber}, $borrower2->{cardnumber}, "Holds queue filling 2nd correct hold for default holds policy 'from home library'");
300
301 # Test skipping hold picks for closed libraries.
302 # At this point in the test, we have 2 rows in the holds queue
303 # 1 of which is coming from MPL. Let's enable HoldsQueueSkipClosed
304 # and make today a holiday for MPL. When we run it again we should only
305 # have 1 row in the holds queue
306 t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 1);
307 my $today = dt_from_string();
308 C4::Calendar->new( branchcode => $branchcodes[0] )->insert_single_holiday(
309     day         => $today->day(),
310     month       => $today->month(),
311     year        => $today->year(),
312     title       => "$today",
313     description => "$today",
314 );
315 # If the test below is removed, aother tests using the holiday will fail. For some reason if we call is_holiday now
316 # the holiday will get set in cache correctly, but not if we let C4::HoldsQueue call is_holiday instead.
317 is( Koha::Calendar->new( branchcode => $branchcodes[0] )->is_holiday( $today ), 1, 'Is today a holiday for pickup branch' );
318 C4::HoldsQueue::CreateQueue();
319 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
320 is( scalar( @$holds_queue ), 1, "Holds not filled with items from closed libraries" );
321 t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 0);
322
323 $dbh->do("DELETE FROM default_circ_rules");
324 $dbh->do("INSERT INTO default_circ_rules ( holdallowed ) VALUES ( 2 )");
325 C4::HoldsQueue::CreateQueue();
326 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
327 is( @$holds_queue, 3, "Holds queue filling correct number for holds for default holds policy 'from any library'" );
328
329 # Test skipping hold picks for closed libraries without transport cost matrix
330 # At this point in the test, we have 3 rows in the holds queue
331 # one of which is coming from MPL. Let's enable HoldsQueueSkipClosed
332 # and use our previously created holiday for MPL
333 # When we run it again we should only have 2 rows in the holds queue
334 t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 1 );
335 C4::HoldsQueue::CreateQueue();
336 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
337 is( scalar( @$holds_queue ), 2, "Holds not filled with items from closed libraries" );
338 t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 0 );
339
340 ## Test LocalHoldsPriority
341 t::lib::Mocks::mock_preference('LocalHoldsPriority', 1);
342
343 $dbh->do("DELETE FROM default_circ_rules");
344 $dbh->do("INSERT INTO default_circ_rules ( holdallowed ) VALUES ( 2 )");
345 $dbh->do("DELETE FROM issues");
346
347 # Test homebranch = patron branch
348 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary');
349 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'homebranch');
350 C4::Context->clear_syspref_cache();
351 $dbh->do("DELETE FROM reserves");
352 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
353 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
354 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
355
356 $dbh->do("DELETE FROM items");
357 # barcode, homebranch, holdingbranch, itemtype
358 $items_insert_sth->execute( $barcode + 4, $branchcodes[2], $branchcodes[0] );
359
360 C4::HoldsQueue::CreateQueue();
361 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
362 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's home library");
363
364 ### Test branch transfer limits ###
365 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary');
366 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch');
367 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' );
368 C4::Context->clear_syspref_cache();
369 $dbh->do("DELETE FROM reserves");
370 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
371 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[1], 2 );
372
373 $dbh->do("DELETE FROM items");
374 # barcode, homebranch, holdingbranch, itemtype
375 $items_insert_sth->execute( $barcode, $branchcodes[2], $branchcodes[2] );
376 my $item = Koha::Items->find( { barcode => $barcode } );
377
378 my $limit1 = Koha::Item::Transfer::Limit->new(
379     {
380         toBranch   => $branchcodes[0],
381         fromBranch => $branchcodes[2],
382         itemtype   => $item->effective_itemtype,
383     }
384 )->store();
385
386 C4::HoldsQueue::CreateQueue();
387 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
388 is( $holds_queue->[0]->{cardnumber}, $borrower2->{cardnumber}, "Holds queue skips hold transfer that would violate branch transfer limits");
389
390 my $limit2 = Koha::Item::Transfer::Limit->new(
391     {
392         toBranch   => $branchcodes[1],
393         fromBranch => $branchcodes[2],
394         itemtype   => $item->effective_itemtype,
395     }
396 )->store();
397
398 C4::HoldsQueue::CreateQueue();
399 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
400 is( $holds_queue->[0]->{cardnumber}, undef, "Holds queue doesn't fill hold where all available items would violate branch transfer limits");
401
402 $limit1->delete();
403 $limit2->delete();
404 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' );
405 ### END Test branch transfer limits ###
406
407 # Test holdingbranch = patron branch
408 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary');
409 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch');
410 C4::Context->clear_syspref_cache();
411 $dbh->do("DELETE FROM reserves");
412 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
413 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
414 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
415
416 $dbh->do("DELETE FROM items");
417 # barcode, homebranch, holdingbranch, itemtype
418 $items_insert_sth->execute( $barcode + 4, $branchcodes[0], $branchcodes[2] );
419
420 C4::HoldsQueue::CreateQueue();
421 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
422 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library");
423
424 # Test holdingbranch = pickup branch
425 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'PickupLibrary');
426 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch');
427 C4::Context->clear_syspref_cache();
428 $dbh->do("DELETE FROM reserves");
429 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
430 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
431 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[2], 3 );
432
433 $dbh->do("DELETE FROM items");
434 # barcode, homebranch, holdingbranch, itemtype
435 $items_insert_sth->execute( $barcode + 4, $branchcodes[0], $branchcodes[2] );
436
437 C4::HoldsQueue::CreateQueue();
438 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
439 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library");
440
441 # Test homebranch = pickup branch
442 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'PickupLibrary');
443 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'homebranch');
444 C4::Context->clear_syspref_cache();
445 $dbh->do("DELETE FROM reserves");
446 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
447 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
448 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[2], 3 );
449
450 $dbh->do("DELETE FROM items");
451 # barcode, homebranch, holdingbranch, itemtype
452 $items_insert_sth->execute( $barcode + 4, $branchcodes[2], $branchcodes[0] );
453
454 C4::HoldsQueue::CreateQueue();
455 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
456 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library");
457
458 t::lib::Mocks::mock_preference('LocalHoldsPriority', 0);
459 ## End testing of LocalHoldsPriority
460
461
462 # Bug 14297
463 $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
464 $borrowernumber = $borrower3->{borrowernumber};
465 my $library_A = $library1->{branchcode};
466 my $library_B = $library2->{branchcode};
467 my $library_C = $borrower3->{branchcode};
468 $dbh->do("DELETE FROM reserves");
469 $dbh->do("DELETE FROM issues");
470 $dbh->do("DELETE FROM items");
471 $dbh->do("DELETE FROM biblio");
472 $dbh->do("DELETE FROM biblioitems");
473 $dbh->do("DELETE FROM transport_cost");
474 $dbh->do("DELETE FROM tmp_holdsqueue");
475 $dbh->do("DELETE FROM hold_fill_targets");
476 $dbh->do("DELETE FROM default_branch_circ_rules");
477 $dbh->do("DELETE FROM default_branch_item_rules");
478 $dbh->do("DELETE FROM default_circ_rules");
479 $dbh->do("DELETE FROM branch_item_rules");
480
481 $dbh->do("
482     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
483 ");
484
485 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
486   or BAIL_OUT("Cannot find newly created biblio record");
487
488 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
489
490 $biblioitemnumber =
491   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
492   or BAIL_OUT("Cannot find newly created biblioitems record");
493
494 $dbh->do("
495     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
496     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype')
497 ");
498
499 $dbh->do("
500     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
501     VALUES ($biblionumber, $biblioitemnumber, '$library_B', '$library_B', 0, 0, 0, 0, NULL, '$itemtype')
502 ");
503
504 $dbh->do("
505     INSERT INTO branch_item_rules ( branchcode, itemtype, holdallowed, returnbranch ) VALUES
506     ( '$library_A', '$itemtype', 2, 'homebranch' ), ( '$library_B', '$itemtype', 1, 'homebranch' );
507 ");
508
509 $dbh->do( "UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'",
510     undef, join( ',', $library_B, $library_A, $library_C ) );
511 $dbh->do( "UPDATE systempreferences SET value = 0 WHERE variable = 'RandomizeHoldsQueueWeight'" );
512
513 my $reserve_id = AddReserve ( $library_C, $borrowernumber, $biblionumber, '', 1 );
514 C4::HoldsQueue::CreateQueue();
515 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
516 is( @$holds_queue, 1, "Bug 14297 - Holds Queue building ignoring holds where pickup & home branch don't match and item is not from le");
517 # End Bug 14297
518
519 # Bug 15062
520 $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
521 $borrowernumber = $borrower2->{borrowernumber};
522 $library_A = $library1->{branchcode};
523 $library_B = $library2->{branchcode};
524 $dbh->do("DELETE FROM reserves");
525 $dbh->do("DELETE FROM issues");
526 $dbh->do("DELETE FROM items");
527 $dbh->do("DELETE FROM biblio");
528 $dbh->do("DELETE FROM biblioitems");
529 $dbh->do("DELETE FROM transport_cost");
530 $dbh->do("DELETE FROM tmp_holdsqueue");
531 $dbh->do("DELETE FROM hold_fill_targets");
532 $dbh->do("DELETE FROM default_branch_circ_rules");
533 $dbh->do("DELETE FROM default_branch_item_rules");
534 $dbh->do("DELETE FROM default_circ_rules");
535 $dbh->do("DELETE FROM branch_item_rules");
536
537 t::lib::Mocks::mock_preference("UseTransportCostMatrix",1);
538
539 my $tc_rs = $schema->resultset('TransportCost');
540 $tc_rs->create({ frombranch => $library_A, tobranch => $library_B, cost => 0, disable_transfer => 1 });
541 $tc_rs->create({ frombranch => $library_B, tobranch => $library_A, cost => 0, disable_transfer => 1 });
542
543 $dbh->do("
544     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
545 ");
546
547 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
548   or BAIL_OUT("Cannot find newly created biblio record");
549
550 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
551
552 $biblioitemnumber =
553   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
554   or BAIL_OUT("Cannot find newly created biblioitems record");
555
556 $dbh->do("
557     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
558     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype')
559 ");
560
561 $reserve_id = AddReserve ( $library_B, $borrowernumber, $biblionumber, '', 1 );
562 C4::HoldsQueue::CreateQueue();
563 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
564 is( @$holds_queue, 0, "Bug 15062 - Holds queue with Transport Cost Matrix will transfer item even if transfers disabled");
565 # End Bug 15062
566
567 # Test hold_fulfillment_policy
568 t::lib::Mocks::mock_preference( "UseTransportCostMatrix", 0 );
569 $borrowernumber = $borrower3->{borrowernumber};
570 $library_A = $library1->{branchcode};
571 $library_B = $library2->{branchcode};
572 $library_C = $library3->{branchcode};
573 $dbh->do("DELETE FROM reserves");
574 $dbh->do("DELETE FROM issues");
575 $dbh->do("DELETE FROM items");
576 $dbh->do("DELETE FROM biblio");
577 $dbh->do("DELETE FROM biblioitems");
578 $dbh->do("DELETE FROM transport_cost");
579 $dbh->do("DELETE FROM tmp_holdsqueue");
580 $dbh->do("DELETE FROM hold_fill_targets");
581 $dbh->do("DELETE FROM default_branch_circ_rules");
582 $dbh->do("DELETE FROM default_branch_item_rules");
583 $dbh->do("DELETE FROM default_circ_rules");
584 $dbh->do("DELETE FROM branch_item_rules");
585
586 $dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')");
587
588 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
589   or BAIL_OUT("Cannot find newly created biblio record");
590
591 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
592
593 $biblioitemnumber =
594   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
595   or BAIL_OUT("Cannot find newly created biblioitems record");
596
597 $dbh->do("
598     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
599     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_B', 0, 0, 0, 0, NULL, '$itemtype')
600 ");
601
602 # With hold_fulfillment_policy = homebranch, hold should only be picked up if pickup branch = homebranch
603 $dbh->do("DELETE FROM default_circ_rules");
604 $dbh->do("INSERT INTO default_circ_rules ( holdallowed, hold_fulfillment_policy ) VALUES ( 2, 'homebranch' )");
605
606 # Home branch matches pickup branch
607 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1 );
608 C4::HoldsQueue::CreateQueue();
609 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
610 is( @$holds_queue, 1, "Hold where pickup branch matches home branch targeted" );
611 Koha::Holds->find( $reserve_id )->cancel;
612
613 # Holding branch matches pickup branch
614 $reserve_id = AddReserve( $library_B, $borrowernumber, $biblionumber, '', 1 );
615 C4::HoldsQueue::CreateQueue();
616 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
617 is( @$holds_queue, 0, "Hold where pickup ne home, pickup eq home not targeted" );
618 Koha::Holds->find( $reserve_id )->cancel;
619
620 # Neither branch matches pickup branch
621 $reserve_id = AddReserve( $library_C, $borrowernumber, $biblionumber, '', 1 );
622 C4::HoldsQueue::CreateQueue();
623 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
624 is( @$holds_queue, 0, "Hold where pickup ne home, pickup ne holding not targeted" );
625 Koha::Holds->find( $reserve_id )->cancel;
626
627 # With hold_fulfillment_policy = holdingbranch, hold should only be picked up if pickup branch = holdingbranch
628 $dbh->do("DELETE FROM default_circ_rules");
629 $dbh->do("INSERT INTO default_circ_rules ( holdallowed, hold_fulfillment_policy ) VALUES ( 2, 'holdingbranch' )");
630
631 # Home branch matches pickup branch
632 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1 );
633 C4::HoldsQueue::CreateQueue();
634 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
635 is( @$holds_queue, 0, "Hold where pickup eq home, pickup ne holding not targeted" );
636 Koha::Holds->find( $reserve_id )->cancel;
637
638 # Holding branch matches pickup branch
639 $reserve_id = AddReserve( $library_B, $borrowernumber, $biblionumber, '', 1 );
640 C4::HoldsQueue::CreateQueue();
641 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
642 is( @$holds_queue, 1, "Hold where pickup ne home, pickup eq holding targeted" );
643 Koha::Holds->find( $reserve_id )->cancel;
644
645 # Neither branch matches pickup branch
646 $reserve_id = AddReserve( $library_C, $borrowernumber, $biblionumber, '', 1 );
647 C4::HoldsQueue::CreateQueue();
648 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
649 is( @$holds_queue, 0, "Hold where pickup ne home, pickup ne holding not targeted" );
650 Koha::Holds->find( $reserve_id )->cancel;
651
652 # With hold_fulfillment_policy = any, hold should be pikcup up reguardless of matching home or holding branch
653 $dbh->do("DELETE FROM default_circ_rules");
654 $dbh->do("INSERT INTO default_circ_rules ( holdallowed, hold_fulfillment_policy ) VALUES ( 2, 'any' )");
655
656 # Home branch matches pickup branch
657 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1 );
658 C4::HoldsQueue::CreateQueue();
659 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
660 is( @$holds_queue, 1, "Hold where pickup eq home, pickup ne holding targeted" );
661 Koha::Holds->find( $reserve_id )->cancel;
662
663 # Holding branch matches pickup branch
664 $reserve_id = AddReserve( $library_B, $borrowernumber, $biblionumber, '', 1 );
665 C4::HoldsQueue::CreateQueue();
666 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
667 is( @$holds_queue, 1, "Hold where pickup ne home, pickup eq holding targeted" );
668 Koha::Holds->find( $reserve_id )->cancel;
669
670 # Neither branch matches pickup branch
671 $reserve_id = AddReserve( $library_C, $borrowernumber, $biblionumber, '', 1 );
672 C4::HoldsQueue::CreateQueue();
673 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
674 is( @$holds_queue, 1, "Hold where pickup ne home, pickup ne holding targeted" );
675 Koha::Holds->find( $reserve_id )->cancel;
676
677 # End testing hold_fulfillment_policy
678
679 # Test hold itemtype limit
680 t::lib::Mocks::mock_preference( "UseTransportCostMatrix", 0 );
681 my $wrong_itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
682 my $right_itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
683 $borrowernumber = $borrower3->{borrowernumber};
684 my $branchcode = $library1->{branchcode};
685 $dbh->do("DELETE FROM reserves");
686 $dbh->do("DELETE FROM issues");
687 $dbh->do("DELETE FROM items");
688 $dbh->do("DELETE FROM biblio");
689 $dbh->do("DELETE FROM biblioitems");
690 $dbh->do("DELETE FROM transport_cost");
691 $dbh->do("DELETE FROM tmp_holdsqueue");
692 $dbh->do("DELETE FROM hold_fill_targets");
693 $dbh->do("DELETE FROM default_branch_circ_rules");
694 $dbh->do("DELETE FROM default_branch_item_rules");
695 $dbh->do("DELETE FROM default_circ_rules");
696 $dbh->do("DELETE FROM branch_item_rules");
697
698 $dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')");
699
700 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
701   or BAIL_OUT("Cannot find newly created biblio record");
702
703 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
704
705 $biblioitemnumber =
706   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
707   or BAIL_OUT("Cannot find newly created biblioitems record");
708
709 $dbh->do("
710     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
711     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_B', 0, 0, 0, 0, NULL, '$right_itemtype')
712 ");
713
714 # With hold_fulfillment_policy = homebranch, hold should only be picked up if pickup branch = homebranch
715 $dbh->do("DELETE FROM default_circ_rules");
716 $dbh->do("INSERT INTO default_circ_rules ( holdallowed, hold_fulfillment_policy ) VALUES ( 2, 'any' )");
717
718 # Home branch matches pickup branch
719 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1, undef, undef, undef, undef, undef, undef, $wrong_itemtype );
720 C4::HoldsQueue::CreateQueue();
721 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
722 is( @$holds_queue, 0, "Item with incorrect itemtype not targeted" );
723 Koha::Holds->find( $reserve_id )->cancel;
724
725 # Holding branch matches pickup branch
726 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1, undef, undef, undef, undef, undef, undef, $right_itemtype );
727 C4::HoldsQueue::CreateQueue();
728 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
729 is( @$holds_queue, 1, "Item with matching itemtype is targeted" );
730 Koha::Holds->find( $reserve_id )->cancel;
731
732 # Neither branch matches pickup branch
733 $reserve_id = AddReserve( $library_A, $borrowernumber, $biblionumber, '', 1, undef, undef, undef, undef, undef, undef, undef );
734 C4::HoldsQueue::CreateQueue();
735 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
736 is( @$holds_queue, 1, "Item targeted when hold itemtype is not set" );
737 Koha::Holds->find( $reserve_id )->cancel;
738
739 # End testing hold itemtype limit
740
741
742 # Test Local Holds Priority - Bug 18001
743 t::lib::Mocks::mock_preference('LocalHoldsPriority', 1);
744 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'PickupLibrary');
745 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'homebranch');
746
747 $dbh->do("DELETE FROM tmp_holdsqueue");
748 $dbh->do("DELETE FROM hold_fill_targets");
749 $dbh->do("DELETE FROM reserves");
750 $dbh->do("DELETE FROM default_branch_circ_rules");
751 $dbh->do("DELETE FROM default_branch_item_rules");
752 $dbh->do("DELETE FROM default_circ_rules");
753 $dbh->do("DELETE FROM branch_item_rules");
754
755 $item = Koha::Items->find( { biblionumber => $biblionumber } );
756 $item->holdingbranch( $item->homebranch );
757 $item->store();
758
759 my $item2 = Koha::Item->new( $item->unblessed );
760 $item2->itemnumber( undef );
761 $item2->store();
762
763 my $item3 = Koha::Item->new( $item->unblessed );
764 $item3->itemnumber( undef );
765 $item3->store();
766
767 $reserve_id = AddReserve( $item->homebranch, $borrowernumber, $biblionumber, '', 1, undef, undef, undef, undef, undef, undef, undef );
768
769 C4::HoldsQueue::CreateQueue();
770
771 my $queue_rs = $schema->resultset('TmpHoldsqueue');
772 is( $queue_rs->count(), 1, "Hold queue contains one hold from chosen from three possible items" );
773
774 subtest 'Trivial test for UpdateTransportCostMatrix' => sub {
775     plan tests => 1;
776     my $recs = [
777         { frombranch => $library1->{branchcode}, tobranch => $library2->{branchcode}, cost => 1, disable_transfer => 0 },
778         { frombranch => $library2->{branchcode}, tobranch => $library3->{branchcode}, cost => 0, disable_transfer => 1 },
779     ];
780     C4::HoldsQueue::UpdateTransportCostMatrix( $recs );
781     is( $schema->resultset('TransportCost')->count, 2, 'UpdateTransportCostMatrix added two records' );
782 };
783
784 # Cleanup
785 $schema->storage->txn_rollback;
786
787 ### END Test holds queue builder does not violate holds policy ###
788
789 sub test_queue {
790     my ($test_name, $use_cost_matrix, $pick_branch, $hold_branch) = @_;
791
792     $test_name = "$test_name (".($use_cost_matrix ? "" : "don't ")."use cost matrix)";
793
794     $use_cost_matrix_sth->execute($use_cost_matrix);
795     C4::Context->clear_syspref_cache();
796     C4::HoldsQueue::CreateQueue();
797
798     my $results = $dbh->selectall_arrayref($test_sth, { Slice => {} }); # should be only one
799     my $r = $results->[0];
800
801     my $ok = is( $r->{pickbranch}, $pick_branch, "$test_name pick up branch");
802     $ok &&=  is( $r->{holdingbranch}, $hold_branch, "$test_name holding branch")
803       if $hold_branch;
804
805     diag( "Wrong pick-up/hold for first target (pick_branch, hold_branch, reserves, hold_fill_targets, tmp_holdsqueue): "
806         . Dumper ($pick_branch, $hold_branch, map dump_records($_), qw(reserves hold_fill_targets tmp_holdsqueue)) )
807       unless $ok;
808
809     # Test enforcement of branch transfer limit
810     if ( $r->{pickbranch} ne $r->{holdingbranch} ) {
811         t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' );
812         my $limit = Koha::Item::Transfer::Limit->new(
813             {
814                 toBranch   => $r->{pickbranch},
815                 fromBranch => $r->{holdingbranch},
816                 itemtype   => $r->{itype},
817             }
818         )->store();
819         C4::Context->clear_syspref_cache();
820         C4::HoldsQueue::CreateQueue();
821         $results = $dbh->selectall_arrayref( $test_sth, { Slice => {} } )
822           ;    # should be only one
823         my $s = $results->[0];
824         isnt( $r->{holdingbranch}, $s->{holdingbranch}, 'Hold is not trapped for pickup at a branch that cannot be transferred to');
825
826         $limit->delete();
827         t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' );
828         C4::Context->clear_syspref_cache();
829         C4::HoldsQueue::CreateQueue();
830     }
831
832 }
833
834 sub dump_records {
835     my ($tablename) = @_;
836     return $dbh->selectall_arrayref("SELECT * from $tablename where borrowernumber = ?", { Slice => {} }, $borrowernumber);
837 }