Bug 14097 : Changing AddReserve prototype call
[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 C4::Context;
12
13 use Data::Dumper;
14
15 use Test::More tests => 23;
16
17 use C4::Branch;
18 use C4::Members;
19 use Koha::Database;
20
21 use t::lib::TestBuilder;
22
23 use Koha::ItemTypes;
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 my $library1 = $builder->build({
39     source => 'Branch',
40 });
41 my $library2 = $builder->build({
42     source => 'Branch',
43 });
44 my $library3 = $builder->build({
45     source => 'Branch',
46 });
47
48 my $TITLE = "Test Holds Queue XXX";
49
50 my $borrower = $builder->build({
51     source => 'Borrower',
52     value => {
53         categorycode => 'S',
54         branchcode => $library1->{branchcode},
55     }
56 });
57
58 my $borrowernumber = $borrower->{borrowernumber};
59 # Set special (for this test) branches
60 my $borrower_branchcode = $borrower->{branchcode};
61 my @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} );
62 my @other_branches = ( $library2->{branchcode}, $library3->{branchcode} );
63 my $least_cost_branch_code = pop @other_branches;
64 my $itemtype = Koha::ItemTypes->search({ notforloan => 1 })->next;
65 $itemtype or BAIL_OUT("No adequate itemtype"); #FIXME Should be $itemtype = $itemtype->itemtype
66
67 #Set up the stage
68 # Sysprefs and cost matrix
69 $dbh->do("UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'", undef,
70          join( ',', @other_branches, $borrower_branchcode, $least_cost_branch_code));
71 $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'RandomizeHoldsQueueWeight'");
72
73 $dbh->do("DELETE FROM transport_cost");
74 my $transport_cost_insert_sth = $dbh->prepare("insert into transport_cost (frombranch, tobranch, cost) values (?, ?, ?)");
75 # Favour $least_cost_branch_code
76 $transport_cost_insert_sth->execute($borrower_branchcode, $least_cost_branch_code, 0.2);
77 $transport_cost_insert_sth->execute($least_cost_branch_code, $borrower_branchcode, 0.2);
78 my @b = @other_branches;
79 while ( my $b1 = shift @b ) {
80     foreach my $b2 ($borrower_branchcode, $least_cost_branch_code, @b) {
81         $transport_cost_insert_sth->execute($b1, $b2, 0.5);
82         $transport_cost_insert_sth->execute($b2, $b1, 0.5);
83     }
84 }
85
86
87 # Loanable items - all possible combinations of homebranch and holdingbranch
88 $dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated)
89           VALUES             ('SER', 'Koha test', '$TITLE', '2011-02-01')");
90 my $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
91   or BAIL_OUT("Cannot find newly created biblio record");
92 $dbh->do("INSERT INTO biblioitems (biblionumber, marcxml, itemtype)
93           VALUES                  ($biblionumber, '', '$itemtype')");
94 my $biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
95   or BAIL_OUT("Cannot find newly created biblioitems record");
96
97 my $items_insert_sth = $dbh->prepare("INSERT INTO items (biblionumber, biblioitemnumber, barcode, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
98                                       VALUES            ($biblionumber, $biblioitemnumber, ?, ?, ?, 0, 0, 0, 0, NULL, '$itemtype')"); # CURRENT_DATE - 3)");
99 my $first_barcode = int(rand(1000000000000)); # XXX
100 my $barcode = $first_barcode;
101 foreach ( $borrower_branchcode, $least_cost_branch_code, @other_branches ) {
102     $items_insert_sth->execute($barcode++, $borrower_branchcode, $_);
103     $items_insert_sth->execute($barcode++, $_, $_);
104     $items_insert_sth->execute($barcode++, $_, $borrower_branchcode);
105 }
106
107 # Remove existing reserves, makes debugging easier
108 $dbh->do("DELETE FROM reserves");
109 my $bibitems = undef;
110 my $priority = 1;
111 # Make a reserve
112 AddReserve ( $borrower_branchcode, $borrowernumber, $biblionumber, $bibitems,  $priority );
113 #                           $resdate, $expdate, $notes, $title, $checkitem, $found
114 $dbh->do("UPDATE reserves SET reservedate = DATE_SUB( reservedate, INTERVAL 1 DAY )");
115
116 # Tests
117 my $use_cost_matrix_sth = $dbh->prepare("UPDATE systempreferences SET value = ? WHERE variable = 'UseTransportCostMatrix'");
118 my $test_sth = $dbh->prepare("SELECT * FROM hold_fill_targets
119                               JOIN tmp_holdsqueue USING (borrowernumber, biblionumber, itemnumber)
120                               JOIN items USING (itemnumber)
121                               WHERE borrowernumber = $borrowernumber");
122
123 # We have a book available homed in borrower branch, no point fiddling with AutomaticItemReturn
124 C4::Context->set_preference('AutomaticItemReturn', 0);
125 test_queue ('take from homebranch',  0, $borrower_branchcode, $borrower_branchcode);
126 test_queue ('take from homebranch',  1, $borrower_branchcode, $borrower_branchcode);
127
128 $dbh->do("DELETE FROM tmp_holdsqueue");
129 $dbh->do("DELETE FROM hold_fill_targets");
130 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode')");
131 $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode'");
132 # test_queue will flush
133 C4::Context->set_preference('AutomaticItemReturn', 1);
134 # Not sure how to make this test more difficult - holding branch does not matter
135
136 $dbh->do("DELETE FROM tmp_holdsqueue");
137 $dbh->do("DELETE FROM hold_fill_targets");
138 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode')");
139 $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode'");
140 C4::Context->set_preference('AutomaticItemReturn', 0);
141 # We have a book available held in borrower branch
142 test_queue ('take from holdingbranch', 0, $borrower_branchcode, $borrower_branchcode);
143 test_queue ('take from holdingbranch', 1, $borrower_branchcode, $borrower_branchcode);
144
145 $dbh->do("DELETE FROM tmp_holdsqueue");
146 $dbh->do("DELETE FROM hold_fill_targets");
147 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE holdingbranch = '$borrower_branchcode')");
148 $dbh->do("DELETE FROM items WHERE holdingbranch = '$borrower_branchcode'");
149 # No book available in borrower branch, pick according to the rules
150 # Frst branch from StaticHoldsQueueWeight
151 test_queue ('take from lowest cost branch', 0, $borrower_branchcode, $other_branches[0]);
152 test_queue ('take from lowest cost branch', 1, $borrower_branchcode, $least_cost_branch_code);
153 my $queue = C4::HoldsQueue::GetHoldsQueueItems($least_cost_branch_code) || [];
154 my $queue_item = $queue->[0];
155 ok( $queue_item
156  && $queue_item->{pickbranch} eq $borrower_branchcode
157  && $queue_item->{holdingbranch} eq $least_cost_branch_code, "GetHoldsQueueItems" )
158   or diag( "Expected item for pick $borrower_branchcode, hold $least_cost_branch_code, got ".Dumper($queue_item) );
159 ok( exists($queue_item->{itype}), 'item type included in queued items list (bug 5825)' );
160
161 ok(
162     C4::HoldsQueue::least_cost_branch( 'B', [ 'A', 'B', 'C' ] ) eq 'B',
163     'C4::HoldsQueue::least_cost_branch returns the local branch if it is in the list of branches to pull from'
164 );
165
166 # XXX All this tests are for borrower branch pick-up.
167 # Maybe needs expanding to homebranch or holdingbranch pick-up.
168
169 $schema->txn_rollback;
170 $schema->txn_begin;
171
172 ### Test holds queue builder does not violate holds policy ###
173
174 # Clear out existing rules relating to holdallowed
175 $dbh->do("DELETE FROM default_branch_circ_rules");
176 $dbh->do("DELETE FROM default_branch_item_rules");
177 $dbh->do("DELETE FROM default_circ_rules");
178
179 C4::Context->set_preference('UseTransportCostMatrix', 0);
180
181 $itemtype = Koha::ItemTypes->search->next->itemtype;
182
183 $library1 = $builder->build({
184     source => 'Branch',
185 });
186 $library2 = $builder->build({
187     source => 'Branch',
188 });
189 $library3 = $builder->build({
190     source => 'Branch',
191 });
192 @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} );
193
194 my $borrower1 = $builder->build({
195     source => 'Borrower',
196     value => {
197         categorycode => 'S',
198         branchcode => $branchcodes[0],
199     },
200 });
201 my $borrower2 = $builder->build({
202     source => 'Borrower',
203     value => {
204         categorycode => 'S',
205         branchcode => $branchcodes[1],
206     },
207 });
208 my $borrower3 = $builder->build({
209     source => 'Borrower',
210     value => {
211         categorycode => 'S',
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         marcxml, 
236         itemtype
237     ) VALUES (
238         $biblionumber, 
239         '', 
240         '$itemtype'
241     )
242 });
243 $biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
244   or BAIL_OUT("Cannot find newly created biblioitems record");
245
246 $items_insert_sth = $dbh->prepare(qq{
247     INSERT INTO items (
248         biblionumber, 
249         biblioitemnumber,
250         barcode,
251         homebranch,
252         holdingbranch,
253         notforloan,
254         damaged,
255         itemlost,
256         withdrawn,
257         onloan,
258         itype
259     ) VALUES (
260         $biblionumber,
261         $biblioitemnumber,
262         ?,
263         ?,
264         ?,
265         0,
266         0,
267         0,
268         0,
269         NULL,
270         '$itemtype'
271     )
272 });
273 # Create 3 items from 2 branches ( branches are for borrowers 1 and 2 respectively )
274 $barcode = int( rand(1000000000000) );
275 $items_insert_sth->execute( $barcode + 0, $branchcodes[0], $branchcodes[0] );
276 $items_insert_sth->execute( $barcode + 1, $branchcodes[1], $branchcodes[1] );
277 $items_insert_sth->execute( $barcode + 2, $branchcodes[1], $branchcodes[1] );
278
279 $dbh->do("DELETE FROM reserves");
280 my $sth = $dbh->prepare(q{
281     INSERT INTO reserves ( 
282         borrowernumber,
283         biblionumber,
284         branchcode,
285         priority,
286         reservedate
287     ) VALUES ( ?,?,?,?, CURRENT_DATE() )
288 });
289 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
290 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
291 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
292
293 my $holds_queue;
294
295 $dbh->do("DELETE FROM default_circ_rules");
296 $dbh->do("INSERT INTO default_circ_rules ( holdallowed ) VALUES ( 1 )");
297 C4::HoldsQueue::CreateQueue();
298 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
299 is( @$holds_queue, 2, "Holds queue filling correct number for default holds policy 'from home library'" );
300 is( $holds_queue->[0]->{cardnumber}, $borrower1->{cardnumber}, "Holds queue filling 1st correct hold for default holds policy 'from home library'");
301 is( $holds_queue->[1]->{cardnumber}, $borrower2->{cardnumber}, "Holds queue filling 2nd correct hold for default holds policy 'from home library'");
302
303 $dbh->do("DELETE FROM default_circ_rules");
304 $dbh->do("INSERT INTO default_circ_rules ( holdallowed ) VALUES ( 2 )");
305 C4::HoldsQueue::CreateQueue();
306 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
307 is( @$holds_queue, 3, "Holds queue filling correct number for holds for default holds policy 'from any library'" );
308 #warn "HOLDS QUEUE: " . Data::Dumper::Dumper( $holds_queue );
309
310 # Bug 14297
311 $itemtype = Koha::ItemTypes->search->next->itemtype;
312 $borrowernumber = $borrower3->{borrowernumber};
313 my $library_A = $library1->{branchcode};
314 my $library_B = $library2->{branchcode};
315 my $library_C = $borrower3->{branchcode};
316 $dbh->do("DELETE FROM reserves");
317 $dbh->do("DELETE FROM issues");
318 $dbh->do("DELETE FROM items");
319 $dbh->do("DELETE FROM biblio");
320 $dbh->do("DELETE FROM biblioitems");
321 $dbh->do("DELETE FROM transport_cost");
322 $dbh->do("DELETE FROM tmp_holdsqueue");
323 $dbh->do("DELETE FROM hold_fill_targets");
324 $dbh->do("DELETE FROM default_branch_circ_rules");
325 $dbh->do("DELETE FROM default_branch_item_rules");
326 $dbh->do("DELETE FROM default_circ_rules");
327 $dbh->do("DELETE FROM branch_item_rules");
328
329 $dbh->do("
330     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
331 ");
332
333 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
334   or BAIL_OUT("Cannot find newly created biblio record");
335
336 $dbh->do("INSERT INTO biblioitems (biblionumber, marcxml, itemtype) VALUES ($biblionumber, '', '$itemtype')");
337
338 $biblioitemnumber =
339   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
340   or BAIL_OUT("Cannot find newly created biblioitems record");
341
342 $dbh->do("
343     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
344     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype')
345 ");
346
347 $dbh->do("
348     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
349     VALUES ($biblionumber, $biblioitemnumber, '$library_B', '$library_B', 0, 0, 0, 0, NULL, '$itemtype')
350 ");
351
352 $dbh->do("
353     INSERT INTO branch_item_rules ( branchcode, itemtype, holdallowed, returnbranch ) VALUES
354     ( '$library_A', '$itemtype', 2, 'homebranch' ), ( '$library_B', '$itemtype', 1, 'homebranch' );
355 ");
356
357 $dbh->do( "UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'",
358     undef, join( ',', $library_B, $library_A, $library_C ) );
359 $dbh->do( "UPDATE systempreferences SET value = 0 WHERE variable = 'RandomizeHoldsQueueWeight'" );
360
361 my $reserve_id = AddReserve ( $library_C, $borrowernumber, $biblionumber, '', 1 );
362 C4::HoldsQueue::CreateQueue();
363 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
364 is( @$holds_queue, 1, "Bug 14297 - Holds Queue building ignoring holds where pickup & home branch don't match and item is not from le");
365 # End Bug 14297
366
367 # Bug 15062
368 $itemtype = Koha::ItemTypes->search->next->itemtype;
369 $borrowernumber = $borrower2->{borrowernumber};
370 $library_A = $library1->{branchcode};
371 $library_B = $library2->{branchcode};
372 $dbh->do("DELETE FROM reserves");
373 $dbh->do("DELETE FROM issues");
374 $dbh->do("DELETE FROM items");
375 $dbh->do("DELETE FROM biblio");
376 $dbh->do("DELETE FROM biblioitems");
377 $dbh->do("DELETE FROM transport_cost");
378 $dbh->do("DELETE FROM tmp_holdsqueue");
379 $dbh->do("DELETE FROM hold_fill_targets");
380 $dbh->do("DELETE FROM default_branch_circ_rules");
381 $dbh->do("DELETE FROM default_branch_item_rules");
382 $dbh->do("DELETE FROM default_circ_rules");
383 $dbh->do("DELETE FROM branch_item_rules");
384
385 C4::Context->set_preference("UseTransportCostMatrix",1);
386
387 my $tc_rs = $schema->resultset('TransportCost');
388 $tc_rs->create({ frombranch => $library_A, tobranch => $library_B, cost => 0, disable_transfer => 1 });
389 $tc_rs->create({ frombranch => $library_B, tobranch => $library_A, cost => 0, disable_transfer => 1 });
390
391 $dbh->do("
392     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
393 ");
394
395 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
396   or BAIL_OUT("Cannot find newly created biblio record");
397
398 $dbh->do("INSERT INTO biblioitems (biblionumber, marcxml, itemtype) VALUES ($biblionumber, '', '$itemtype')");
399
400 $biblioitemnumber =
401   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
402   or BAIL_OUT("Cannot find newly created biblioitems record");
403
404 $dbh->do("
405     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
406     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype')
407 ");
408
409 $reserve_id = AddReserve ( $library_B, $borrowernumber, $biblionumber, '', 1 );
410 C4::HoldsQueue::CreateQueue();
411 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
412 is( @$holds_queue, 0, "Bug 15062 - Holds queue with Transport Cost Matrix will transfer item even if transfers disabled");
413 # End Bug 15062
414
415 # Cleanup
416 $schema->storage->txn_rollback;
417
418 ### END Test holds queue builder does not violate holds policy ###
419
420 sub test_queue {
421     my ($test_name, $use_cost_matrix, $pick_branch, $hold_branch) = @_;
422
423     $test_name = "$test_name (".($use_cost_matrix ? "" : "don't ")."use cost matrix)";
424
425     $use_cost_matrix_sth->execute($use_cost_matrix);
426     C4::Context->clear_syspref_cache();
427     C4::HoldsQueue::CreateQueue();
428
429     my $results = $dbh->selectall_arrayref($test_sth, { Slice => {} }); # should be only one
430     my $r = $results->[0];
431
432     my $ok = is( $r->{pickbranch}, $pick_branch, "$test_name pick up branch");
433     $ok &&=  is( $r->{holdingbranch}, $hold_branch, "$test_name holding branch")
434       if $hold_branch;
435
436     diag( "Wrong pick-up/hold for first target (pick_branch, hold_branch, reserves, hold_fill_targets, tmp_holdsqueue): "
437         . Dumper ($pick_branch, $hold_branch, map dump_records($_), qw(reserves hold_fill_targets tmp_holdsqueue)) )
438       unless $ok;
439 }
440
441 sub dump_records {
442     my ($tablename) = @_;
443     return $dbh->selectall_arrayref("SELECT * from $tablename where borrowernumber = ?", { Slice => {} }, $borrowernumber);
444 }