Bug 12803 - Add ability to skip closed libraries when generating the holds queue
[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 => 24;
12 use Data::Dumper;
13
14 use C4::Branch;
15 use C4::Members;
16 use Koha::Database;
17
18 use C4::Calendar;
19 use C4::Context;
20 use C4::Branch;
21 use C4::ItemType;
22 use C4::Members;
23 use Koha::DateUtils;
24
25 use t::lib::TestBuilder;
26
27 use Koha::ItemTypes;
28
29 BEGIN {
30     use FindBin;
31     use lib $FindBin::Bin;
32     use_ok('C4::Reserves');
33     use_ok('C4::HoldsQueue');
34 }
35
36 my $schema = Koha::Database->schema;
37 $schema->storage->txn_begin;
38 my $dbh = C4::Context->dbh;
39
40 my $builder = t::lib::TestBuilder->new;
41
42 my $library1 = $builder->build({
43     source => 'Branch',
44 });
45 my $library2 = $builder->build({
46     source => 'Branch',
47 });
48 my $library3 = $builder->build({
49     source => 'Branch',
50 });
51
52 my $TITLE = "Test Holds Queue XXX";
53
54 my $borrower = $builder->build({
55     source => 'Borrower',
56     value => {
57         categorycode => 'S',
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 = Koha::ItemTypes->search({ notforloan => 1 })->next;
69 $itemtype or BAIL_OUT("No adequate itemtype"); #FIXME Should be $itemtype = $itemtype->itemtype
70
71 #Set up the stage
72 # Sysprefs and cost matrix
73 C4::Context->set_preference('HoldsQueueSkipClosed', 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, marcxml, 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 C4::Context->set_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 C4::Context->set_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 C4::Context->set_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 default_branch_circ_rules");
181 $dbh->do("DELETE FROM default_branch_item_rules");
182 $dbh->do("DELETE FROM default_circ_rules");
183
184 C4::Context->set_preference('UseTransportCostMatrix', 0);
185
186 $itemtype = Koha::ItemTypes->search->next->itemtype;
187
188 $library1 = $builder->build({
189     source => 'Branch',
190 });
191 $library2 = $builder->build({
192     source => 'Branch',
193 });
194 $library3 = $builder->build({
195     source => 'Branch',
196 });
197 @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} );
198
199 my $borrower1 = $builder->build({
200     source => 'Borrower',
201     value => {
202         categorycode => 'S',
203         branchcode => $branchcodes[0],
204     },
205 });
206 my $borrower2 = $builder->build({
207     source => 'Borrower',
208     value => {
209         categorycode => 'S',
210         branchcode => $branchcodes[1],
211     },
212 });
213 my $borrower3 = $builder->build({
214     source => 'Borrower',
215     value => {
216         categorycode => 'S',
217         branchcode => $branchcodes[2],
218     },
219 });
220
221 $dbh->do(qq{
222     INSERT INTO biblio (
223         frameworkcode, 
224         author, 
225         title, 
226         datecreated
227     ) VALUES (
228         'SER', 
229         'Koha test', 
230         '$TITLE', 
231         '2011-02-01'
232     )
233 });
234 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
235   or BAIL_OUT("Cannot find newly created biblio record");
236
237 $dbh->do(qq{
238     INSERT INTO biblioitems (
239         biblionumber, 
240         marcxml, 
241         itemtype
242     ) VALUES (
243         $biblionumber, 
244         '', 
245         '$itemtype'
246     )
247 });
248 $biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
249   or BAIL_OUT("Cannot find newly created biblioitems record");
250
251 $items_insert_sth = $dbh->prepare(qq{
252     INSERT INTO items (
253         biblionumber, 
254         biblioitemnumber,
255         barcode,
256         homebranch,
257         holdingbranch,
258         notforloan,
259         damaged,
260         itemlost,
261         withdrawn,
262         onloan,
263         itype
264     ) VALUES (
265         $biblionumber,
266         $biblioitemnumber,
267         ?,
268         ?,
269         ?,
270         0,
271         0,
272         0,
273         0,
274         NULL,
275         '$itemtype'
276     )
277 });
278 # Create 3 items from 2 branches ( branches are for borrowers 1 and 2 respectively )
279 $barcode = int( rand(1000000000000) );
280 $items_insert_sth->execute( $barcode + 0, $branchcodes[0], $branchcodes[0] );
281 $items_insert_sth->execute( $barcode + 1, $branchcodes[1], $branchcodes[1] );
282 $items_insert_sth->execute( $barcode + 2, $branchcodes[1], $branchcodes[1] );
283
284 $dbh->do("DELETE FROM reserves");
285 my $sth = $dbh->prepare(q{
286     INSERT INTO reserves ( 
287         borrowernumber,
288         biblionumber,
289         branchcode,
290         priority,
291         reservedate
292     ) VALUES ( ?,?,?,?, CURRENT_DATE() )
293 });
294 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
295 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
296 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
297
298 my $holds_queue;
299
300 $dbh->do("DELETE FROM default_circ_rules");
301 $dbh->do("INSERT INTO default_circ_rules ( holdallowed ) VALUES ( 1 )");
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 C4::Context->set_preference('HoldsQueueSkipClosed', 1);
314 my $today = dt_from_string();
315 C4::Calendar->new( branchcode => 'MPL' )->insert_single_holiday(
316     day         => $today->day(),
317     month       => $today->month(),
318     year        => $today->year(),
319     title       => "$today",
320     description => "$today",
321 );
322 C4::HoldsQueue::CreateQueue();
323 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
324 is( scalar( @$holds_queue ), 1, "Holds not filled with items from closed libraries" );
325 C4::Context->set_preference('HoldsQueueSkipClosed', 0);
326
327 $dbh->do("DELETE FROM default_circ_rules");
328 $dbh->do("INSERT INTO default_circ_rules ( holdallowed ) VALUES ( 2 )");
329 C4::HoldsQueue::CreateQueue();
330 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
331 is( @$holds_queue, 3, "Holds queue filling correct number for holds for default holds policy 'from any library'" );
332
333 # Test skipping hold picks for closed libraries without transport cost matrix
334 # At this point in the test, we have 3 rows in the holds queue
335 # one of which is coming from MPL. Let's enable HoldsQueueSkipClosed
336 # and use our previously created holiday for MPL.
337 # When we run it again we should only have 2 rows in the holds queue
338 C4::Context->set_preference( 'HoldsQueueSkipClosed', 1 );
339 C4::HoldsQueue::CreateQueue();
340 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
341 is( scalar( @$holds_queue ), 2, "Holds not filled with items from closed libraries" );
342
343 # Bug 14297
344 $itemtype = Koha::ItemTypes->search->next->itemtype;
345 $borrowernumber = $borrower3->{borrowernumber};
346 my $library_A = $library1->{branchcode};
347 my $library_B = $library2->{branchcode};
348 my $library_C = $borrower3->{branchcode};
349 $dbh->do("DELETE FROM reserves");
350 $dbh->do("DELETE FROM issues");
351 $dbh->do("DELETE FROM items");
352 $dbh->do("DELETE FROM biblio");
353 $dbh->do("DELETE FROM biblioitems");
354 $dbh->do("DELETE FROM transport_cost");
355 $dbh->do("DELETE FROM tmp_holdsqueue");
356 $dbh->do("DELETE FROM hold_fill_targets");
357 $dbh->do("DELETE FROM default_branch_circ_rules");
358 $dbh->do("DELETE FROM default_branch_item_rules");
359 $dbh->do("DELETE FROM default_circ_rules");
360 $dbh->do("DELETE FROM branch_item_rules");
361
362 $dbh->do("
363     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
364 ");
365
366 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
367   or BAIL_OUT("Cannot find newly created biblio record");
368
369 $dbh->do("INSERT INTO biblioitems (biblionumber, marcxml, itemtype) VALUES ($biblionumber, '', '$itemtype')");
370
371 $biblioitemnumber =
372   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
373   or BAIL_OUT("Cannot find newly created biblioitems record");
374
375 $dbh->do("
376     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
377     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype')
378 ");
379
380 $dbh->do("
381     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
382     VALUES ($biblionumber, $biblioitemnumber, '$library_B', '$library_B', 0, 0, 0, 0, NULL, '$itemtype')
383 ");
384
385 $dbh->do("
386     INSERT INTO branch_item_rules ( branchcode, itemtype, holdallowed, returnbranch ) VALUES
387     ( '$library_A', '$itemtype', 2, 'homebranch' ), ( '$library_B', '$itemtype', 1, 'homebranch' );
388 ");
389
390 $dbh->do( "UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'",
391     undef, join( ',', $library_B, $library_A, $library_C ) );
392 $dbh->do( "UPDATE systempreferences SET value = 0 WHERE variable = 'RandomizeHoldsQueueWeight'" );
393
394 my $reserve_id = AddReserve ( $library_C, $borrowernumber, $biblionumber, '', 1 );
395 C4::HoldsQueue::CreateQueue();
396 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
397 is( @$holds_queue, 1, "Bug 14297 - Holds Queue building ignoring holds where pickup & home branch don't match and item is not from le");
398 # End Bug 14297
399
400 # Bug 15062
401 $itemtype = Koha::ItemTypes->search->next->itemtype;
402 $borrowernumber = $borrower2->{borrowernumber};
403 $library_A = $library1->{branchcode};
404 $library_B = $library2->{branchcode};
405 $dbh->do("DELETE FROM reserves");
406 $dbh->do("DELETE FROM issues");
407 $dbh->do("DELETE FROM items");
408 $dbh->do("DELETE FROM biblio");
409 $dbh->do("DELETE FROM biblioitems");
410 $dbh->do("DELETE FROM transport_cost");
411 $dbh->do("DELETE FROM tmp_holdsqueue");
412 $dbh->do("DELETE FROM hold_fill_targets");
413 $dbh->do("DELETE FROM default_branch_circ_rules");
414 $dbh->do("DELETE FROM default_branch_item_rules");
415 $dbh->do("DELETE FROM default_circ_rules");
416 $dbh->do("DELETE FROM branch_item_rules");
417
418 C4::Context->set_preference("UseTransportCostMatrix",1);
419
420 my $tc_rs = $schema->resultset('TransportCost');
421 $tc_rs->create({ frombranch => $library_A, tobranch => $library_B, cost => 0, disable_transfer => 1 });
422 $tc_rs->create({ frombranch => $library_B, tobranch => $library_A, cost => 0, disable_transfer => 1 });
423
424 $dbh->do("
425     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
426 ");
427
428 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
429   or BAIL_OUT("Cannot find newly created biblio record");
430
431 $dbh->do("INSERT INTO biblioitems (biblionumber, marcxml, itemtype) VALUES ($biblionumber, '', '$itemtype')");
432
433 $biblioitemnumber =
434   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
435   or BAIL_OUT("Cannot find newly created biblioitems record");
436
437 $dbh->do("
438     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
439     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype')
440 ");
441
442 $reserve_id = AddReserve ( $library_B, $borrowernumber, $biblionumber, '', 1 );
443 C4::HoldsQueue::CreateQueue();
444 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
445 is( @$holds_queue, 0, "Bug 15062 - Holds queue with Transport Cost Matrix will transfer item even if transfers disabled");
446 # End Bug 15062
447
448 # Cleanup
449 $schema->storage->txn_rollback;
450
451 ### END Test holds queue builder does not violate holds policy ###
452
453 sub test_queue {
454     my ($test_name, $use_cost_matrix, $pick_branch, $hold_branch) = @_;
455
456     $test_name = "$test_name (".($use_cost_matrix ? "" : "don't ")."use cost matrix)";
457
458     $use_cost_matrix_sth->execute($use_cost_matrix);
459     C4::Context->clear_syspref_cache();
460     C4::HoldsQueue::CreateQueue();
461
462     my $results = $dbh->selectall_arrayref($test_sth, { Slice => {} }); # should be only one
463     my $r = $results->[0];
464
465     my $ok = is( $r->{pickbranch}, $pick_branch, "$test_name pick up branch");
466     $ok &&=  is( $r->{holdingbranch}, $hold_branch, "$test_name holding branch")
467       if $hold_branch;
468
469     diag( "Wrong pick-up/hold for first target (pick_branch, hold_branch, reserves, hold_fill_targets, tmp_holdsqueue): "
470         . Dumper ($pick_branch, $hold_branch, map dump_records($_), qw(reserves hold_fill_targets tmp_holdsqueue)) )
471       unless $ok;
472 }
473
474 sub dump_records {
475     my ($tablename) = @_;
476     return $dbh->selectall_arrayref("SELECT * from $tablename where borrowernumber = ?", { Slice => {} }, $borrowernumber);
477 }