]> git.koha-community.org Git - koha.git/blob - t/db_dependent/HoldsQueue.t
Bug 11998: Use t::lib::Mocks::mock_preference in tests
[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::Mocks;
23 use t::lib::TestBuilder;
24
25 use Koha::ItemTypes;
26
27 BEGIN {
28     use FindBin;
29     use lib $FindBin::Bin;
30     use_ok('C4::Reserves');
31     use_ok('C4::HoldsQueue');
32 }
33
34 my $schema = Koha::Database->schema;
35 $schema->storage->txn_begin;
36 my $dbh = C4::Context->dbh;
37
38 my $builder = t::lib::TestBuilder->new;
39
40 my $library1 = $builder->build({
41     source => 'Branch',
42 });
43 my $library2 = $builder->build({
44     source => 'Branch',
45 });
46 my $library3 = $builder->build({
47     source => 'Branch',
48 });
49
50 my $TITLE = "Test Holds Queue XXX";
51
52 my $borrower = $builder->build({
53     source => 'Borrower',
54     value => {
55         categorycode => 'S',
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 = Koha::ItemTypes->search({ notforloan => 1 })->next;
67 $itemtype or BAIL_OUT("No adequate itemtype"); #FIXME Should be $itemtype = $itemtype->itemtype
68
69 #Set up the stage
70 # Sysprefs and cost matrix
71 t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 0);
72 t::lib::Mocks::mock_preference('StaticHoldsQueueWeight', join( ',', @other_branches, $borrower_branchcode, $least_cost_branch_code));
73 t::lib::Mocks::mock_preference('RandomizeHoldsQueueWeight', 0);
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 $test_sth = $dbh->prepare("SELECT * FROM hold_fill_targets
120                               JOIN tmp_holdsqueue USING (borrowernumber, biblionumber, itemnumber)
121                               JOIN items USING (itemnumber)
122                               WHERE borrowernumber = $borrowernumber");
123
124 # We have a book available homed in borrower branch, no point fiddling with AutomaticItemReturn
125 t::lib::Mocks::mock_preference('AutomaticItemReturn', 0);
126 test_queue ('take from homebranch',  0, $borrower_branchcode, $borrower_branchcode);
127 test_queue ('take from homebranch',  1, $borrower_branchcode, $borrower_branchcode);
128
129 $dbh->do("DELETE FROM tmp_holdsqueue");
130 $dbh->do("DELETE FROM hold_fill_targets");
131 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode')");
132 $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode'");
133 # test_queue will flush
134 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
135 # Not sure how to make this test more difficult - holding branch does not matter
136
137 $dbh->do("DELETE FROM tmp_holdsqueue");
138 $dbh->do("DELETE FROM hold_fill_targets");
139 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode')");
140 $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode'");
141 t::lib::Mocks::mock_preference('AutomaticItemReturn', 0);
142 # We have a book available held in borrower branch
143 test_queue ('take from holdingbranch', 0, $borrower_branchcode, $borrower_branchcode);
144 test_queue ('take from holdingbranch', 1, $borrower_branchcode, $borrower_branchcode);
145
146 $dbh->do("DELETE FROM tmp_holdsqueue");
147 $dbh->do("DELETE FROM hold_fill_targets");
148 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE holdingbranch = '$borrower_branchcode')");
149 $dbh->do("DELETE FROM items WHERE holdingbranch = '$borrower_branchcode'");
150 # No book available in borrower branch, pick according to the rules
151 # Frst branch from StaticHoldsQueueWeight
152 test_queue ('take from lowest cost branch', 0, $borrower_branchcode, $other_branches[0]);
153 test_queue ('take from lowest cost branch', 1, $borrower_branchcode, $least_cost_branch_code);
154 my $queue = C4::HoldsQueue::GetHoldsQueueItems($least_cost_branch_code) || [];
155 my $queue_item = $queue->[0];
156 ok( $queue_item
157  && $queue_item->{pickbranch} eq $borrower_branchcode
158  && $queue_item->{holdingbranch} eq $least_cost_branch_code, "GetHoldsQueueItems" )
159   or diag( "Expected item for pick $borrower_branchcode, hold $least_cost_branch_code, got ".Dumper($queue_item) );
160 ok( exists($queue_item->{itype}), 'item type included in queued items list (bug 5825)' );
161
162 ok(
163     C4::HoldsQueue::least_cost_branch( 'B', [ 'A', 'B', 'C' ] ) eq 'B',
164     'C4::HoldsQueue::least_cost_branch returns the local branch if it is in the list of branches to pull from'
165 );
166
167 # XXX All this tests are for borrower branch pick-up.
168 # Maybe needs expanding to homebranch or holdingbranch pick-up.
169
170 $schema->txn_rollback;
171 $schema->txn_begin;
172
173 ### Test holds queue builder does not violate holds policy ###
174
175 # Clear out existing rules relating to holdallowed
176 $dbh->do("DELETE FROM default_branch_circ_rules");
177 $dbh->do("DELETE FROM default_branch_item_rules");
178 $dbh->do("DELETE FROM default_circ_rules");
179
180 t::lib::Mocks::mock_preference('UseTransportCostMatrix', 0);
181
182 $itemtype = Koha::ItemTypes->search->next->itemtype;
183
184 $library1 = $builder->build({
185     source => 'Branch',
186 });
187 $library2 = $builder->build({
188     source => 'Branch',
189 });
190 $library3 = $builder->build({
191     source => 'Branch',
192 });
193 @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} );
194
195 my $borrower1 = $builder->build({
196     source => 'Borrower',
197     value => {
198         categorycode => 'S',
199         branchcode => $branchcodes[0],
200     },
201 });
202 my $borrower2 = $builder->build({
203     source => 'Borrower',
204     value => {
205         categorycode => 'S',
206         branchcode => $branchcodes[1],
207     },
208 });
209 my $borrower3 = $builder->build({
210     source => 'Borrower',
211     value => {
212         categorycode => 'S',
213         branchcode => $branchcodes[2],
214     },
215 });
216
217 $dbh->do(qq{
218     INSERT INTO biblio (
219         frameworkcode, 
220         author, 
221         title, 
222         datecreated
223     ) VALUES (
224         'SER', 
225         'Koha test', 
226         '$TITLE', 
227         '2011-02-01'
228     )
229 });
230 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
231   or BAIL_OUT("Cannot find newly created biblio record");
232
233 $dbh->do(qq{
234     INSERT INTO biblioitems (
235         biblionumber, 
236         marcxml, 
237         itemtype
238     ) VALUES (
239         $biblionumber, 
240         '', 
241         '$itemtype'
242     )
243 });
244 $biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
245   or BAIL_OUT("Cannot find newly created biblioitems record");
246
247 $items_insert_sth = $dbh->prepare(qq{
248     INSERT INTO items (
249         biblionumber, 
250         biblioitemnumber,
251         barcode,
252         homebranch,
253         holdingbranch,
254         notforloan,
255         damaged,
256         itemlost,
257         withdrawn,
258         onloan,
259         itype
260     ) VALUES (
261         $biblionumber,
262         $biblioitemnumber,
263         ?,
264         ?,
265         ?,
266         0,
267         0,
268         0,
269         0,
270         NULL,
271         '$itemtype'
272     )
273 });
274 # Create 3 items from 2 branches ( branches are for borrowers 1 and 2 respectively )
275 $barcode = int( rand(1000000000000) );
276 $items_insert_sth->execute( $barcode + 0, $branchcodes[0], $branchcodes[0] );
277 $items_insert_sth->execute( $barcode + 1, $branchcodes[1], $branchcodes[1] );
278 $items_insert_sth->execute( $barcode + 2, $branchcodes[1], $branchcodes[1] );
279
280 $dbh->do("DELETE FROM reserves");
281 my $sth = $dbh->prepare(q{
282     INSERT INTO reserves ( 
283         borrowernumber,
284         biblionumber,
285         branchcode,
286         priority,
287         reservedate
288     ) VALUES ( ?,?,?,?, CURRENT_DATE() )
289 });
290 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
291 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
292 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
293
294 my $holds_queue;
295
296 $dbh->do("DELETE FROM default_circ_rules");
297 $dbh->do("INSERT INTO default_circ_rules ( holdallowed ) VALUES ( 1 )");
298 C4::HoldsQueue::CreateQueue();
299 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
300 is( @$holds_queue, 2, "Holds queue filling correct number for default holds policy 'from home library'" );
301 is( $holds_queue->[0]->{cardnumber}, $borrower1->{cardnumber}, "Holds queue filling 1st correct hold for default holds policy 'from home library'");
302 is( $holds_queue->[1]->{cardnumber}, $borrower2->{cardnumber}, "Holds queue filling 2nd correct hold for default holds policy 'from home library'");
303
304 # Test skipping hold picks for closed libraries.
305 # At this point in the test, we have 2 rows in the holds queue
306 # 1 of which is coming from MPL. Let's enable HoldsQueueSkipClosed
307 # and make today a holiday for MPL. When we run it again we should only
308 # have 1 row in the holds queue
309 t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 1);
310 my $today = dt_from_string();
311 C4::Calendar->new( branchcode => $branchcodes[0] )->insert_single_holiday(
312     day         => $today->day(),
313     month       => $today->month(),
314     year        => $today->year(),
315     title       => "$today",
316     description => "$today",
317 );
318 # If the test below is removed, aother tests using the holiday will fail. For some reason if we call is_holiday now
319 # the holiday will get set in cache correctly, but not if we let C4::HoldsQueue call is_holiday instead.
320 is( Koha::Calendar->new( branchcode => $branchcodes[0] )->is_holiday( $today ), 1, 'Is today a holiday for pickup branch' );
321 C4::HoldsQueue::CreateQueue();
322 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
323 is( scalar( @$holds_queue ), 1, "Holds not filled with items from closed libraries" );
324 t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 0);
325
326 $dbh->do("DELETE FROM default_circ_rules");
327 $dbh->do("INSERT INTO default_circ_rules ( holdallowed ) VALUES ( 2 )");
328 C4::HoldsQueue::CreateQueue();
329 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
330 is( @$holds_queue, 3, "Holds queue filling correct number for holds for default holds policy 'from any library'" );
331
332 # Test skipping hold picks for closed libraries without transport cost matrix
333 # At this point in the test, we have 3 rows in the holds queue
334 # one of which is coming from MPL. Let's enable HoldsQueueSkipClosed
335 # and use our previously created holiday for MPL
336 # When we run it again we should only have 2 rows in the holds queue
337 t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 1 );
338 C4::HoldsQueue::CreateQueue();
339 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
340 is( scalar( @$holds_queue ), 2, "Holds not filled with items from closed libraries" );
341 t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 0 );
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 t::lib::Mocks::mock_preference('StaticHoldsQueueWeight', join( ',', $library_B, $library_A, $library_C ) );
391 t::lib::Mocks::mock_preference('RandomizeHoldsQueueWeight', 0 );
392
393 my $reserve_id = AddReserve ( $library_C, $borrowernumber, $biblionumber, '', 1 );
394 C4::HoldsQueue::CreateQueue();
395 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
396 is( @$holds_queue, 1, "Bug 14297 - Holds Queue building ignoring holds where pickup & home branch don't match and item is not from le");
397 # End Bug 14297
398
399 # Bug 15062
400 $itemtype = Koha::ItemTypes->search->next->itemtype;
401 $borrowernumber = $borrower2->{borrowernumber};
402 $library_A = $library1->{branchcode};
403 $library_B = $library2->{branchcode};
404 $dbh->do("DELETE FROM reserves");
405 $dbh->do("DELETE FROM issues");
406 $dbh->do("DELETE FROM items");
407 $dbh->do("DELETE FROM biblio");
408 $dbh->do("DELETE FROM biblioitems");
409 $dbh->do("DELETE FROM transport_cost");
410 $dbh->do("DELETE FROM tmp_holdsqueue");
411 $dbh->do("DELETE FROM hold_fill_targets");
412 $dbh->do("DELETE FROM default_branch_circ_rules");
413 $dbh->do("DELETE FROM default_branch_item_rules");
414 $dbh->do("DELETE FROM default_circ_rules");
415 $dbh->do("DELETE FROM branch_item_rules");
416
417 t::lib::Mocks::mock_preference("UseTransportCostMatrix",1);
418
419 my $tc_rs = $schema->resultset('TransportCost');
420 $tc_rs->create({ frombranch => $library_A, tobranch => $library_B, cost => 0, disable_transfer => 1 });
421 $tc_rs->create({ frombranch => $library_B, tobranch => $library_A, cost => 0, disable_transfer => 1 });
422
423 $dbh->do("
424     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
425 ");
426
427 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
428   or BAIL_OUT("Cannot find newly created biblio record");
429
430 $dbh->do("INSERT INTO biblioitems (biblionumber, marcxml, itemtype) VALUES ($biblionumber, '', '$itemtype')");
431
432 $biblioitemnumber =
433   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
434   or BAIL_OUT("Cannot find newly created biblioitems record");
435
436 $dbh->do("
437     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
438     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype')
439 ");
440
441 $reserve_id = AddReserve ( $library_B, $borrowernumber, $biblionumber, '', 1 );
442 C4::HoldsQueue::CreateQueue();
443 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
444 is( @$holds_queue, 0, "Bug 15062 - Holds queue with Transport Cost Matrix will transfer item even if transfers disabled");
445 # End Bug 15062
446
447 # Cleanup
448 $schema->storage->txn_rollback;
449
450 ### END Test holds queue builder does not violate holds policy ###
451
452 sub test_queue {
453     my ($test_name, $use_cost_matrix, $pick_branch, $hold_branch) = @_;
454
455     $test_name = "$test_name (".($use_cost_matrix ? "" : "don't ")."use cost matrix)";
456
457     t::lib::Mocks::mock_preference('UseTransportCostMatrix', $use_cost_matrix);
458     C4::HoldsQueue::CreateQueue();
459
460     my $results = $dbh->selectall_arrayref($test_sth, { Slice => {} }); # should be only one
461     my $r = $results->[0];
462
463     my $ok = is( $r->{pickbranch}, $pick_branch, "$test_name pick up branch");
464     $ok &&=  is( $r->{holdingbranch}, $hold_branch, "$test_name holding branch")
465       if $hold_branch;
466
467     diag( "Wrong pick-up/hold for first target (pick_branch, hold_branch, reserves, hold_fill_targets, tmp_holdsqueue): "
468         . Dumper ($pick_branch, $hold_branch, map dump_records($_), qw(reserves hold_fill_targets tmp_holdsqueue)) )
469       unless $ok;
470 }
471
472 sub dump_records {
473     my ($tablename) = @_;
474     return $dbh->selectall_arrayref("SELECT * from $tablename where borrowernumber = ?", { Slice => {} }, $borrowernumber);
475 }