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