Bug 29234: Further clean Z3950 Tests
[srvgit] / 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 => 59;
12 use Data::Dumper;
13
14 use C4::Calendar qw( new insert_single_holiday );
15 use C4::Context;
16 use C4::Members;
17 use C4::Circulation qw( AddIssue AddReturn );
18 use Koha::Database;
19 use Koha::DateUtils qw( dt_from_string );
20 use Koha::Items;
21 use Koha::Holds;
22 use Koha::CirculationRules;
23
24 use t::lib::TestBuilder;
25 use t::lib::Mocks;
26
27 BEGIN {
28     use FindBin;
29     use lib $FindBin::Bin;
30     use_ok('C4::Reserves', qw( AddReserve ModReserve ModReserveAffect ));
31     use_ok('C4::HoldsQueue', qw( TransportCostMatrix GetHoldsQueueItems CreateQueue UpdateTransportCostMatrix GetPendingHoldRequestsForBib ));
32 }
33
34 my $schema = Koha::Database->schema;
35 $schema->storage->txn_begin;
36 my $dbh = C4::Context->dbh;
37 $dbh->do("DELETE FROM circulation_rules");
38
39 my $builder = t::lib::TestBuilder->new;
40
41 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits',  '0' );
42 t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' );
43
44 my $library1 = $builder->build({
45     source => 'Branch',
46 });
47 my $library2 = $builder->build({
48     source => 'Branch',
49 });
50 my $library3 = $builder->build({
51     source => 'Branch',
52 });
53
54 my $TITLE = "Test Holds Queue XXX";
55
56 my $borrower = $builder->build({
57     source => 'Borrower',
58     value => {
59         branchcode => $library1->{branchcode},
60     }
61 });
62
63 my $borrowernumber = $borrower->{borrowernumber};
64 # Set special (for this test) branches
65 my $borrower_branchcode = $borrower->{branchcode};
66 my @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} );
67 my @other_branches = ( $library2->{branchcode}, $library3->{branchcode} );
68 my $least_cost_branch_code = pop @other_branches;
69 my $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
70
71 #Set up the stage
72 # Sysprefs and cost matrix
73 t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 0);
74 t::lib::Mocks::mock_preference('LocalHoldsPriority', 0);
75 $dbh->do("UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'", undef,
76          join( ',', @other_branches, $borrower_branchcode, $least_cost_branch_code));
77 $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'RandomizeHoldsQueueWeight'");
78
79 $dbh->do("DELETE FROM transport_cost");
80 my $transport_cost_insert_sth = $dbh->prepare("insert into transport_cost (frombranch, tobranch, cost) values (?, ?, ?)");
81 # Favour $least_cost_branch_code
82 $transport_cost_insert_sth->execute($borrower_branchcode, $least_cost_branch_code, 0.2);
83 $transport_cost_insert_sth->execute($least_cost_branch_code, $borrower_branchcode, 0.2);
84 my @b = @other_branches;
85 while ( my $b1 = shift @b ) {
86     foreach my $b2 ($borrower_branchcode, $least_cost_branch_code, @b) {
87         $transport_cost_insert_sth->execute($b1, $b2, 0.5);
88         $transport_cost_insert_sth->execute($b2, $b1, 0.5);
89     }
90 }
91
92
93 # Loanable items - all possible combinations of homebranch and holdingbranch
94 $dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated)
95           VALUES             ('SER', 'Koha test', '$TITLE', '2011-02-01')");
96 my $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
97   or BAIL_OUT("Cannot find newly created biblio record");
98 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype)
99           VALUES                  ($biblionumber, '$itemtype')");
100 my $biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
101   or BAIL_OUT("Cannot find newly created biblioitems record");
102
103 my $items_insert_sth = $dbh->prepare("INSERT INTO items (biblionumber, biblioitemnumber, barcode, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype)
104                                       VALUES            ($biblionumber, $biblioitemnumber, ?, ?, ?, 0, 0, 0, 0, NULL, '$itemtype')"); # CURRENT_DATE - 3)");
105 my $first_barcode = int(rand(1000000000000)); # XXX
106 my $barcode = $first_barcode;
107 foreach ( $borrower_branchcode, $least_cost_branch_code, @other_branches ) {
108     $items_insert_sth->execute($barcode++, $borrower_branchcode, $_);
109     $items_insert_sth->execute($barcode++, $_, $_);
110     $items_insert_sth->execute($barcode++, $_, $borrower_branchcode);
111 }
112
113 # Remove existing reserves, makes debugging easier
114 $dbh->do("DELETE FROM reserves");
115 my $bibitems = undef;
116 my $priority = 1;
117 # Make a reserve
118 AddReserve(
119     {
120         branchcode     => $borrower_branchcode,
121         borrowernumber => $borrowernumber,
122         biblionumber   => $biblionumber,
123         priority       => $priority,
124     }
125 );
126 #                           $resdate, $expdate, $notes, $title, $checkitem, $found
127 $dbh->do("UPDATE reserves SET reservedate = DATE_SUB( reservedate, INTERVAL 1 DAY )");
128
129 # Tests
130 my $use_cost_matrix_sth = $dbh->prepare("UPDATE systempreferences SET value = ? WHERE variable = 'UseTransportCostMatrix'");
131 my $test_sth = $dbh->prepare("SELECT * FROM hold_fill_targets
132                               JOIN tmp_holdsqueue USING (borrowernumber, biblionumber, itemnumber)
133                               JOIN items USING (itemnumber)
134                               WHERE borrowernumber = $borrowernumber");
135
136 # We have a book available homed in borrower branch, no point fiddling with AutomaticItemReturn
137 t::lib::Mocks::mock_preference('AutomaticItemReturn', 0);
138 test_queue ('take from homebranch',  0, $borrower_branchcode, $borrower_branchcode);
139 test_queue ('take from homebranch',  1, $borrower_branchcode, $borrower_branchcode);
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' AND holdingbranch = '$borrower_branchcode')");
144 $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode'");
145 # test_queue will flush
146 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
147 # Not sure how to make this test more difficult - holding branch does not matter
148
149 $dbh->do("DELETE FROM tmp_holdsqueue");
150 $dbh->do("DELETE FROM hold_fill_targets");
151 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode')");
152 $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode'");
153 t::lib::Mocks::mock_preference('AutomaticItemReturn', 0);
154 # We have a book available held in borrower branch
155 test_queue ('take from holdingbranch', 0, $borrower_branchcode, $borrower_branchcode);
156 test_queue ('take from holdingbranch', 1, $borrower_branchcode, $borrower_branchcode);
157
158 $dbh->do("DELETE FROM tmp_holdsqueue");
159 $dbh->do("DELETE FROM hold_fill_targets");
160 $dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE holdingbranch = '$borrower_branchcode')");
161 $dbh->do("DELETE FROM items WHERE holdingbranch = '$borrower_branchcode'");
162 # No book available in borrower branch, pick according to the rules
163 # Frst branch from StaticHoldsQueueWeight
164 test_queue ('take from lowest cost branch', 0, $borrower_branchcode, $other_branches[0]);
165 test_queue ('take from lowest cost branch', 1, $borrower_branchcode, $least_cost_branch_code);
166 my $queue = C4::HoldsQueue::GetHoldsQueueItems({ branchlmit => $least_cost_branch_code}) || [];
167 my $queue_item = $queue->[0];
168 ok( $queue_item
169  && $queue_item->{pickbranch} eq $borrower_branchcode
170  && $queue_item->{holdingbranch} eq $least_cost_branch_code, "GetHoldsQueueItems" )
171   or diag( "Expected item for pick $borrower_branchcode, hold $least_cost_branch_code, got ".Dumper($queue_item) );
172 ok( exists($queue_item->{itype}), 'item type included in queued items list (bug 5825)' );
173
174 ok(
175     C4::HoldsQueue::least_cost_branch( 'B', [ 'A', 'B', 'C' ] ) eq 'B',
176     'C4::HoldsQueue::least_cost_branch returns the local branch if it is in the list of branches to pull from'
177 );
178
179 # XXX All this tests are for borrower branch pick-up.
180 # Maybe needs expanding to homebranch or holdingbranch pick-up.
181
182 $schema->txn_rollback;
183 $schema->txn_begin;
184
185 ### Test holds queue builder does not violate holds policy ###
186
187 # Clear out existing rules relating to holdallowed
188 $dbh->do("DELETE FROM circulation_rules");
189
190 t::lib::Mocks::mock_preference('UseTransportCostMatrix', 0);
191
192 $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
193
194 $library1 = $builder->build({
195     source => 'Branch',
196 });
197 $library2 = $builder->build({
198     source => 'Branch',
199 });
200 $library3 = $builder->build({
201     source => 'Branch',
202 });
203 @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} );
204
205 my $category = $builder->build({ source => 'Category', value => {exclude_from_local_holds_priority => 0} } );
206
207 my $borrower1 = $builder->build({
208     source => 'Borrower',
209     value => {
210         branchcode => $branchcodes[0],
211         categorycode => $category->{categorycode},
212     },
213 });
214 my $borrower2 = $builder->build({
215     source => 'Borrower',
216     value => {
217         branchcode => $branchcodes[1],
218         categorycode => $category->{categorycode},
219     },
220 });
221 my $borrower3 = $builder->build({
222     source => 'Borrower',
223     value => {
224         branchcode => $branchcodes[2],
225         categorycode => $category->{categorycode},
226     },
227 });
228
229 $dbh->do(qq{
230     INSERT INTO biblio (
231         frameworkcode,
232         author,
233         title,
234         datecreated
235     ) VALUES (
236         'SER',
237         'Koha test',
238         '$TITLE',
239         '2011-02-01'
240     )
241 });
242 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
243   or BAIL_OUT("Cannot find newly created biblio record");
244
245 $dbh->do(qq{
246     INSERT INTO biblioitems (
247         biblionumber,
248         itemtype
249     ) VALUES (
250         $biblionumber,
251         '$itemtype'
252     )
253 });
254 $biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
255   or BAIL_OUT("Cannot find newly created biblioitems record");
256
257 $items_insert_sth = $dbh->prepare(qq{
258     INSERT INTO items (
259         biblionumber,
260         biblioitemnumber,
261         barcode,
262         homebranch,
263         holdingbranch,
264         notforloan,
265         damaged,
266         itemlost,
267         withdrawn,
268         onloan,
269         itype,
270         exclude_from_local_holds_priority
271     ) VALUES (
272         $biblionumber,
273         $biblioitemnumber,
274         ?,
275         ?,
276         ?,
277         0,
278         0,
279         0,
280         0,
281         NULL,
282         '$itemtype',
283         0
284     )
285 });
286 # Create 3 items from 2 branches ( branches are for borrowers 1 and 2 respectively )
287 $barcode = int( rand(1000000000000) );
288 $items_insert_sth->execute( $barcode + 0, $branchcodes[0], $branchcodes[0] );
289 $items_insert_sth->execute( $barcode + 1, $branchcodes[1], $branchcodes[1] );
290 $items_insert_sth->execute( $barcode + 2, $branchcodes[1], $branchcodes[1] );
291
292 $dbh->do("DELETE FROM reserves");
293 my $sth = $dbh->prepare(q{
294     INSERT INTO reserves (
295         borrowernumber,
296         biblionumber,
297         branchcode,
298         priority,
299         reservedate
300     ) VALUES ( ?,?,?,?, CURRENT_DATE() )
301 });
302 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
303 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
304 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
305
306 my $holds_queue;
307
308 $dbh->do("DELETE FROM circulation_rules");
309 Koha::CirculationRules->set_rule(
310     {
311         rule_name    => 'holdallowed',
312         rule_value   => 'from_home_library',
313         branchcode   => undef,
314         itemtype     => undef,
315     }
316 );
317 C4::HoldsQueue::CreateQueue();
318 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
319 is( @$holds_queue, 2, "Holds queue filling correct number for default holds policy 'from home library'" );
320 is( $holds_queue->[0]->{cardnumber}, $borrower1->{cardnumber}, "Holds queue filling 1st correct hold for default holds policy 'from home library'");
321 is( $holds_queue->[1]->{cardnumber}, $borrower2->{cardnumber}, "Holds queue filling 2nd correct hold for default holds policy 'from home library'");
322
323 # Test skipping hold picks for closed libraries.
324 # At this point in the test, we have 2 rows in the holds queue
325 # 1 of which is coming from MPL. Let's enable HoldsQueueSkipClosed
326 # and make today a holiday for MPL. When we run it again we should only
327 # have 1 row in the holds queue
328 t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 1);
329 my $today = dt_from_string();
330 C4::Calendar->new( branchcode => $branchcodes[0] )->insert_single_holiday(
331     day         => $today->day(),
332     month       => $today->month(),
333     year        => $today->year(),
334     title       => "$today",
335     description => "$today",
336 );
337 # If the test below is removed, aother tests using the holiday will fail. For some reason if we call is_holiday now
338 # the holiday will get set in cache correctly, but not if we let C4::HoldsQueue call is_holiday instead.
339 is( Koha::Calendar->new( branchcode => $branchcodes[0] )->is_holiday( $today ), 1, 'Is today a holiday for pickup branch' );
340 C4::HoldsQueue::CreateQueue();
341 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
342 is( scalar( @$holds_queue ), 1, "Holds not filled with items from closed libraries" );
343 t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 0);
344
345 $dbh->do("DELETE FROM circulation_rules");
346 Koha::CirculationRules->set_rule(
347     {
348         rule_name    => 'holdallowed',
349         rule_value   => 'from_any_library',
350         branchcode   => undef,
351         itemtype     => undef,
352     }
353 );
354 C4::HoldsQueue::CreateQueue();
355 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
356 is( @$holds_queue, 3, "Holds queue filling correct number for holds for default holds policy 'from any library'" );
357
358 # Test skipping hold picks for closed libraries without transport cost matrix
359 # At this point in the test, we have 3 rows in the holds queue
360 # one of which is coming from MPL. Let's enable HoldsQueueSkipClosed
361 # and use our previously created holiday for MPL
362 # When we run it again we should only have 2 rows in the holds queue
363 t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 1 );
364 C4::HoldsQueue::CreateQueue();
365 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
366 is( scalar( @$holds_queue ), 2, "Holds not filled with items from closed libraries" );
367 t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 0 );
368
369 ## Test LocalHoldsPriority
370 t::lib::Mocks::mock_preference('LocalHoldsPriority', 1);
371
372 $dbh->do("DELETE FROM circulation_rules");
373 Koha::CirculationRules->set_rule(
374     {
375         rule_name    => 'holdallowed',
376         rule_value   => 'from_any_library',
377         branchcode   => undef,
378         itemtype     => undef,
379     }
380 );
381 $dbh->do("DELETE FROM issues");
382
383 # Test homebranch = patron branch
384 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary');
385 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'homebranch');
386 C4::Context->clear_syspref_cache();
387 $dbh->do("DELETE FROM reserves");
388 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
389 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
390 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
391
392 $dbh->do("DELETE FROM items");
393 # barcode, homebranch, holdingbranch, itemtype
394 $items_insert_sth->execute( $barcode + 4, $branchcodes[2], $branchcodes[0] );
395
396 C4::HoldsQueue::CreateQueue();
397 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
398 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's home library");
399
400 ### Test branch transfer limits ###
401 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary');
402 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch');
403 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' );
404 C4::Context->clear_syspref_cache();
405 $dbh->do("DELETE FROM reserves");
406 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
407 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[1], 2 );
408
409 $dbh->do("DELETE FROM items");
410 # barcode, homebranch, holdingbranch, itemtype
411 $items_insert_sth->execute( $barcode, $branchcodes[2], $branchcodes[2] );
412 my $item = Koha::Items->find( { barcode => $barcode } );
413
414 my $limit1 = Koha::Item::Transfer::Limit->new(
415     {
416         toBranch   => $branchcodes[0],
417         fromBranch => $branchcodes[2],
418         itemtype   => $item->effective_itemtype,
419     }
420 )->store();
421
422 C4::HoldsQueue::CreateQueue();
423 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
424 is( $holds_queue->[0]->{cardnumber}, $borrower2->{cardnumber}, "Holds queue skips hold transfer that would violate branch transfer limits");
425
426 my $limit2 = Koha::Item::Transfer::Limit->new(
427     {
428         toBranch   => $branchcodes[1],
429         fromBranch => $branchcodes[2],
430         itemtype   => $item->effective_itemtype,
431     }
432 )->store();
433
434 C4::HoldsQueue::CreateQueue();
435 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
436 is( $holds_queue->[0]->{cardnumber}, undef, "Holds queue doesn't fill hold where all available items would violate branch transfer limits");
437
438 $limit1->delete();
439 $limit2->delete();
440 t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' );
441 ### END Test branch transfer limits ###
442
443 # Test holdingbranch = patron branch
444 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary');
445 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch');
446 C4::Context->clear_syspref_cache();
447 $dbh->do("DELETE FROM reserves");
448 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
449 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
450 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 );
451
452 $dbh->do("DELETE FROM items");
453 # barcode, homebranch, holdingbranch, itemtype
454 $items_insert_sth->execute( $barcode + 4, $branchcodes[0], $branchcodes[2] );
455
456 C4::HoldsQueue::CreateQueue();
457 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
458 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library");
459
460 # Test holdingbranch = pickup branch
461 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'PickupLibrary');
462 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch');
463 C4::Context->clear_syspref_cache();
464 $dbh->do("DELETE FROM reserves");
465 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
466 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
467 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[2], 3 );
468
469 $dbh->do("DELETE FROM items");
470 # barcode, homebranch, holdingbranch, itemtype
471 $items_insert_sth->execute( $barcode + 4, $branchcodes[0], $branchcodes[2] );
472
473 C4::HoldsQueue::CreateQueue();
474 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
475 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library");
476
477 # Test homebranch = pickup branch
478 t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'PickupLibrary');
479 t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'homebranch');
480 C4::Context->clear_syspref_cache();
481 $dbh->do("DELETE FROM reserves");
482 $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 );
483 $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 );
484 $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[2], 3 );
485
486 $dbh->do("DELETE FROM items");
487 # barcode, homebranch, holdingbranch, itemtype
488 $items_insert_sth->execute( $barcode + 4, $branchcodes[2], $branchcodes[0] );
489
490 C4::HoldsQueue::CreateQueue();
491 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
492 is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library");
493
494 t::lib::Mocks::mock_preference('LocalHoldsPriority', 0);
495 ## End testing of LocalHoldsPriority
496
497
498 # Bug 14297
499 $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
500 $borrowernumber = $borrower3->{borrowernumber};
501 my $library_A = $library1->{branchcode};
502 my $library_B = $library2->{branchcode};
503 my $library_C = $borrower3->{branchcode};
504 $dbh->do("DELETE FROM reserves");
505 $dbh->do("DELETE FROM issues");
506 $dbh->do("DELETE FROM items");
507 $dbh->do("DELETE FROM biblio");
508 $dbh->do("DELETE FROM biblioitems");
509 $dbh->do("DELETE FROM transport_cost");
510 $dbh->do("DELETE FROM tmp_holdsqueue");
511 $dbh->do("DELETE FROM hold_fill_targets");
512
513 $dbh->do("
514     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
515 ");
516
517 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
518   or BAIL_OUT("Cannot find newly created biblio record");
519
520 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
521
522 $biblioitemnumber =
523   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
524   or BAIL_OUT("Cannot find newly created biblioitems record");
525
526 $dbh->do("
527     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype, exclude_from_local_holds_priority)
528     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype', 0)
529 ");
530
531 $dbh->do("
532     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype, exclude_from_local_holds_priority)
533     VALUES ($biblionumber, $biblioitemnumber, '$library_B', '$library_B', 0, 0, 0, 0, NULL, '$itemtype', 0)
534 ");
535
536 Koha::CirculationRules->set_rules(
537     {
538         branchcode   => $library_A,
539         itemtype     => $itemtype,
540         rules        => {
541             holdallowed  => 'from_any_library',
542             returnbranch => 'homebranch',
543         }
544     }
545 );
546
547 $dbh->do( "UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'",
548     undef, join( ',', $library_B, $library_A, $library_C ) );
549 $dbh->do( "UPDATE systempreferences SET value = 0 WHERE variable = 'RandomizeHoldsQueueWeight'" );
550
551 my $reserve_id = AddReserve(
552     {
553         branchcode     => $library_C,
554         borrowernumber => $borrowernumber,
555         biblionumber   => $biblionumber,
556         priority       => 1,
557     }
558 );
559 C4::HoldsQueue::CreateQueue();
560 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
561 is( @$holds_queue, 1, "Bug 14297 - Holds Queue building ignoring holds where pickup & home branch don't match and item is not from le");
562 # End Bug 14297
563
564 # Bug 15062
565 $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
566 $borrowernumber = $borrower2->{borrowernumber};
567 $library_A = $library1->{branchcode};
568 $library_B = $library2->{branchcode};
569 $dbh->do("DELETE FROM reserves");
570 $dbh->do("DELETE FROM issues");
571 $dbh->do("DELETE FROM items");
572 $dbh->do("DELETE FROM biblio");
573 $dbh->do("DELETE FROM biblioitems");
574 $dbh->do("DELETE FROM transport_cost");
575 $dbh->do("DELETE FROM tmp_holdsqueue");
576 $dbh->do("DELETE FROM hold_fill_targets");
577
578 t::lib::Mocks::mock_preference("UseTransportCostMatrix",1);
579
580 my $tc_rs = $schema->resultset('TransportCost');
581 $tc_rs->create({ frombranch => $library_A, tobranch => $library_B, cost => 0, disable_transfer => 1 });
582 $tc_rs->create({ frombranch => $library_B, tobranch => $library_A, cost => 0, disable_transfer => 1 });
583
584 $dbh->do("
585     INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')
586 ");
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, exclude_from_local_holds_priority)
599     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype', 0)
600 ");
601
602 $reserve_id = AddReserve(
603     {
604         branchcode     => $library_B,
605         borrowernumber => $borrowernumber,
606         biblionumber   => $biblionumber,
607         priority       => 1,
608     }
609 );
610
611 C4::HoldsQueue::CreateQueue();
612 $holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} });
613 is( @$holds_queue, 0, "Bug 15062 - Holds queue with Transport Cost Matrix will transfer item even if transfers disabled");
614 # End Bug 15062
615
616 # Test hold_fulfillment_policy
617 t::lib::Mocks::mock_preference( "UseTransportCostMatrix", 0 );
618 $borrowernumber = $borrower3->{borrowernumber};
619 $library_A = $library1->{branchcode};
620 $library_B = $library2->{branchcode};
621 $library_C = $library3->{branchcode};
622 $dbh->do("DELETE FROM reserves");
623 $dbh->do("DELETE FROM issues");
624 $dbh->do("DELETE FROM items");
625 $dbh->do("DELETE FROM biblio");
626 $dbh->do("DELETE FROM biblioitems");
627 $dbh->do("DELETE FROM transport_cost");
628 $dbh->do("DELETE FROM tmp_holdsqueue");
629 $dbh->do("DELETE FROM hold_fill_targets");
630
631 $dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')");
632
633 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
634   or BAIL_OUT("Cannot find newly created biblio record");
635
636 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
637
638 $biblioitemnumber =
639   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
640   or BAIL_OUT("Cannot find newly created biblioitems record");
641
642 $dbh->do("
643     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype, exclude_from_local_holds_priority)
644     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_B', 0, 0, 0, 0, NULL, '$itemtype', 0)
645 ");
646
647 # With hold_fulfillment_policy = homebranch, hold should only be picked up if pickup branch = homebranch
648 $dbh->do("DELETE FROM circulation_rules");
649 Koha::CirculationRules->set_rules(
650     {
651         branchcode   => undef,
652         itemtype     => undef,
653         rules        => {
654             holdallowed             => 'from_any_library',
655             hold_fulfillment_policy => 'homebranch',
656         }
657     }
658 );
659
660 # Home branch matches pickup branch
661 $reserve_id = AddReserve(
662     {
663         branchcode     => $library_A,
664         borrowernumber => $borrowernumber,
665         biblionumber   => $biblionumber,
666         priority       => 1,
667     }
668 );
669
670 C4::HoldsQueue::CreateQueue();
671 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
672 is( @$holds_queue, 1, "Hold where pickup branch matches home branch targeted" );
673 my $target_rs = $schema->resultset('HoldFillTarget');
674 is( $target_rs->next->reserve_id, $reserve_id, "Reserve id correctly set in hold fill target for title level hold" );
675 Koha::Holds->find( $reserve_id )->cancel;
676
677 # Holding branch matches pickup branch
678 $reserve_id = AddReserve(
679     {
680         branchcode     => $library_B,
681         borrowernumber => $borrowernumber,
682         biblionumber   => $biblionumber,
683         priority       => 1,
684     }
685 );
686
687
688 C4::HoldsQueue::CreateQueue();
689 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
690 is( @$holds_queue, 0, "Hold where pickup ne home, pickup eq home not targeted" );
691 Koha::Holds->find( $reserve_id )->cancel;
692
693 # Neither branch matches pickup branch
694 $reserve_id = AddReserve(
695     {
696         branchcode     => $library_C,
697         borrowernumber => $borrowernumber,
698         biblionumber   => $biblionumber,
699         priority       => 1,
700     }
701 );
702
703 C4::HoldsQueue::CreateQueue();
704 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
705 is( @$holds_queue, 0, "Hold where pickup ne home, pickup ne holding not targeted" );
706 Koha::Holds->find( $reserve_id )->cancel;
707
708 # With hold_fulfillment_policy = holdingbranch, hold should only be picked up if pickup branch = holdingbranch
709 $dbh->do("DELETE FROM circulation_rules");
710 Koha::CirculationRules->set_rules(
711     {
712         branchcode   => undef,
713         itemtype     => undef,
714         rules        => {
715             holdallowed             => 'from_any_library',
716             hold_fulfillment_policy => 'holdingbranch',
717         }
718     }
719 );
720
721 # Home branch matches pickup branch
722 $reserve_id = AddReserve(
723     {
724         branchcode     => $library_A,
725         borrowernumber => $borrowernumber,
726         biblionumber   => $biblionumber,
727         priority       => 1,
728     }
729 );
730
731 C4::HoldsQueue::CreateQueue();
732 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
733 is( @$holds_queue, 0, "Hold where pickup eq home, pickup ne holding not targeted" );
734 Koha::Holds->find( $reserve_id )->cancel;
735
736 # Holding branch matches pickup branch
737 $reserve_id = AddReserve(
738     {
739         branchcode     => $library_B,
740         borrowernumber => $borrowernumber,
741         biblionumber   => $biblionumber,
742         priority       => 1,
743     }
744 );
745
746 C4::HoldsQueue::CreateQueue();
747 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
748 is( @$holds_queue, 1, "Hold where pickup ne home, pickup eq holding targeted" );
749 Koha::Holds->find( $reserve_id )->cancel;
750
751 # Neither branch matches pickup branch
752 $reserve_id = AddReserve(
753     {
754         branchcode     => $library_C,
755         borrowernumber => $borrowernumber,
756         biblionumber   => $biblionumber,
757         priority       => 1,
758     }
759 );
760
761 C4::HoldsQueue::CreateQueue();
762 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
763 is( @$holds_queue, 0, "Hold where pickup ne home, pickup ne holding not targeted" );
764 Koha::Holds->find( $reserve_id )->cancel;
765
766 # With hold_fulfillment_policy = any, hold should be pikcup up reguardless of matching home or holding branch
767 $dbh->do("DELETE FROM circulation_rules");
768 Koha::CirculationRules->set_rules(
769     {
770         branchcode   => undef,
771         itemtype     => undef,
772         rules        => {
773             holdallowed             => 'from_any_library',
774             hold_fulfillment_policy => 'any',
775         }
776     }
777 );
778
779 # Home branch matches pickup branch
780 $reserve_id = AddReserve(
781     {
782         branchcode     => $library_A,
783         borrowernumber => $borrowernumber,
784         biblionumber   => $biblionumber,
785         priority       => 1,
786     }
787 );
788
789 C4::HoldsQueue::CreateQueue();
790 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
791 is( @$holds_queue, 1, "Hold where pickup eq home, pickup ne holding targeted" );
792 Koha::Holds->find( $reserve_id )->cancel;
793
794 # Holding branch matches pickup branch
795 $reserve_id = AddReserve(
796     {
797         branchcode     => $library_B,
798         borrowernumber => $borrowernumber,
799         biblionumber   => $biblionumber,
800         priority       => 1,
801     }
802 );
803
804 C4::HoldsQueue::CreateQueue();
805 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
806 is( @$holds_queue, 1, "Hold where pickup ne home, pickup eq holding targeted" );
807 Koha::Holds->find( $reserve_id )->cancel;
808
809 # Neither branch matches pickup branch
810 $reserve_id = AddReserve(
811     {
812         branchcode     => $library_C,
813         borrowernumber => $borrowernumber,
814         biblionumber   => $biblionumber,
815         priority       => 1,
816     }
817 );
818
819 C4::HoldsQueue::CreateQueue();
820 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
821 is( @$holds_queue, 1, "Hold where pickup ne home, pickup ne holding targeted" );
822 Koha::Holds->find( $reserve_id )->cancel;
823
824 # End testing hold_fulfillment_policy
825
826 # Test hold itemtype limit
827 t::lib::Mocks::mock_preference( "UseTransportCostMatrix", 0 );
828 my $wrong_itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
829 my $right_itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype};
830 $borrowernumber = $borrower3->{borrowernumber};
831 my $branchcode = $library1->{branchcode};
832 $dbh->do("DELETE FROM reserves");
833 $dbh->do("DELETE FROM issues");
834 $dbh->do("DELETE FROM items");
835 $dbh->do("DELETE FROM biblio");
836 $dbh->do("DELETE FROM biblioitems");
837 $dbh->do("DELETE FROM transport_cost");
838 $dbh->do("DELETE FROM tmp_holdsqueue");
839 $dbh->do("DELETE FROM hold_fill_targets");
840
841 $dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')");
842
843 $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'")
844   or BAIL_OUT("Cannot find newly created biblio record");
845
846 $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')");
847
848 $biblioitemnumber =
849   $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber")
850   or BAIL_OUT("Cannot find newly created biblioitems record");
851
852 $dbh->do("
853     INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype, exclude_from_local_holds_priority)
854     VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_B', 0, 0, 0, 0, NULL, '$right_itemtype', 0)
855 ");
856
857 # With hold_fulfillment_policy = homebranch, hold should only be picked up if pickup branch = homebranch
858 $dbh->do("DELETE FROM circulation_rules");
859 Koha::CirculationRules->set_rules(
860     {
861         branchcode   => undef,
862         itemtype     => undef,
863         rules        => {
864             holdallowed             => 'from_any_library',
865             hold_fulfillment_policy => 'any',
866         }
867     }
868 );
869
870 # Home branch matches pickup branch
871 $reserve_id = AddReserve(
872     {
873         branchcode     => $library_A,
874         borrowernumber => $borrowernumber,
875         biblionumber   => $biblionumber,
876         priority       => 1,
877         itemtype       => $wrong_itemtype,
878     }
879 );
880
881 C4::HoldsQueue::CreateQueue();
882 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
883 is( @$holds_queue, 0, "Item with incorrect itemtype not targeted" );
884 Koha::Holds->find( $reserve_id )->cancel;
885
886 # Holding branch matches pickup branch
887 $reserve_id = AddReserve(
888     {
889         branchcode     => $library_A,
890         borrowernumber => $borrowernumber,
891         biblionumber   => $biblionumber,
892         priority       => 1,
893         itemtype       => $right_itemtype,
894     }
895 );
896
897 C4::HoldsQueue::CreateQueue();
898 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
899 is( @$holds_queue, 1, "Item with matching itemtype is targeted" );
900 Koha::Holds->find( $reserve_id )->cancel;
901
902 # Neither branch matches pickup branch
903 $reserve_id = AddReserve(
904     {
905         branchcode     => $library_A,
906         borrowernumber => $borrowernumber,
907         biblionumber   => $biblionumber,
908         priority       => 1,
909     }
910 );
911
912 C4::HoldsQueue::CreateQueue();
913 $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } );
914 is( @$holds_queue, 1, "Item targeted when hold itemtype is not set" );
915 Koha::Holds->find( $reserve_id )->cancel;
916
917 # End testing hold itemtype limit
918
919
920 subtest "Test Local Holds Priority - Bib level" => sub {
921     plan tests => 3;
922
923     Koha::Biblios->delete();
924     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
925     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
926     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
927     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
928     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
929     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
930     my $local_patron = $builder->build_object(
931         {
932             class => "Koha::Patrons",
933             value => {
934                 branchcode => $branch->branchcode,
935                 categorycode => $category->categorycode
936             }
937         }
938     );
939     my $other_patron = $builder->build_object(
940         {
941             class => "Koha::Patrons",
942             value => {
943                 branchcode => $branch2->branchcode,
944                 categorycode => $category->categorycode
945             }
946         }
947     );
948     my $biblio = $builder->build_sample_biblio();
949     my $item   = $builder->build_sample_item(
950         {
951             biblionumber  => $biblio->biblionumber,
952             library    => $branch->branchcode,
953             exclude_from_local_holds_priority => 0,
954         }
955     );
956
957     my $reserve_id = AddReserve(
958         {
959             branchcode     => $branch2->branchcode,
960             borrowernumber => $other_patron->borrowernumber,
961             biblionumber   => $biblio->biblionumber,
962             priority       => 1,
963         }
964     );
965     my $reserve_id2 = AddReserve(
966         {
967             branchcode     => $item->homebranch,
968             borrowernumber => $local_patron->borrowernumber,
969             biblionumber   => $biblio->biblionumber,
970             priority       => 2,
971         }
972     );
973
974     C4::HoldsQueue::CreateQueue();
975
976     my $queue_rs = $schema->resultset('TmpHoldsqueue');
977     my $target_rs = $schema->resultset('HoldFillTarget');
978     is( $queue_rs->count(), 1,
979         "Hold queue contains one hold" );
980     is(
981         $queue_rs->next->borrowernumber->borrowernumber,
982         $local_patron->borrowernumber,
983         "We should pick the local hold over the next available"
984     );
985     is( $target_rs->next->reserve_id, $reserve_id2, "Reserve id correctly set in hold fill target" );
986 };
987
988 subtest "Test Local Holds Priority - Item level" => sub {
989     plan tests => 2;
990
991     Koha::Biblios->delete();
992     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
993     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
994     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
995     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
996     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
997     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
998     my $local_patron = $builder->build_object(
999         {
1000             class => "Koha::Patrons",
1001             value => {
1002                 branchcode => $branch->branchcode,
1003                 categorycode => $category->categorycode
1004             }
1005         }
1006     );
1007     my $other_patron = $builder->build_object(
1008         {
1009             class => "Koha::Patrons",
1010             value => {
1011                 branchcode => $branch2->branchcode,
1012                 categorycode => $category->categorycode
1013             }
1014         }
1015     );
1016     my $biblio = $builder->build_sample_biblio();
1017     my $item   = $builder->build_sample_item(
1018         {
1019             biblionumber  => $biblio->biblionumber,
1020             library    => $branch->branchcode,
1021             exclude_from_local_holds_priority => 0,
1022         }
1023     );
1024
1025     my $reserve_id = AddReserve(
1026         {
1027             branchcode     => $branch2->branchcode,
1028             borrowernumber => $other_patron->borrowernumber,
1029             biblionumber   => $biblio->biblionumber,
1030             priority       => 1,
1031             itemnumber     => $item->id,
1032         }
1033     );
1034     my $reserve_id2 = AddReserve(
1035         {
1036             branchcode     => $item->homebranch,
1037             borrowernumber => $local_patron->borrowernumber,
1038             biblionumber   => $biblio->biblionumber,
1039             priority       => 2,
1040             itemnumber     => $item->id,
1041         }
1042     );
1043
1044     C4::HoldsQueue::CreateQueue();
1045
1046     my $queue_rs = $schema->resultset('TmpHoldsqueue');
1047     my $q = $queue_rs->next;
1048     is( $queue_rs->count(), 1,
1049         "Hold queue contains one hold" );
1050     is(
1051         $q->borrowernumber->borrowernumber,
1052         $local_patron->borrowernumber,
1053         "We should pick the local hold over the next available"
1054     );
1055 };
1056
1057 subtest "Test Local Holds Priority - Item level hold over Record level hold (Bug 23934)" => sub {
1058     plan tests => 2;
1059
1060     Koha::Biblios->delete();
1061     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
1062     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
1063     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
1064     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
1065     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
1066     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
1067     my $local_patron = $builder->build_object(
1068         {
1069             class => "Koha::Patrons",
1070             value => {
1071                 branchcode => $branch->branchcode,
1072                 categorycode => $category->categorycode,
1073             }
1074         }
1075     );
1076     my $other_patron = $builder->build_object(
1077         {
1078             class => "Koha::Patrons",
1079             value => {
1080                 branchcode => $branch2->branchcode,
1081                 categorycode => $category->categorycode,
1082             }
1083         }
1084     );
1085     my $biblio = $builder->build_sample_biblio();
1086     my $item   = $builder->build_sample_item(
1087         {
1088             biblionumber  => $biblio->biblionumber,
1089             library    => $branch->branchcode,
1090             exclude_from_local_holds_priority => 0,
1091         }
1092     );
1093
1094     my $reserve_id = AddReserve(
1095         {
1096             branchcode     => $branch2->branchcode,
1097             borrowernumber => $other_patron->borrowernumber,
1098             biblionumber   => $biblio->biblionumber,
1099             priority       => 1,
1100         }
1101     );
1102     my $reserve_id2 = AddReserve(
1103         {
1104             branchcode     => $item->homebranch,
1105             borrowernumber => $local_patron->borrowernumber,
1106             biblionumber   => $biblio->biblionumber,
1107             priority       => 2,
1108             itemnumber     => $item->id,
1109         }
1110     );
1111
1112     C4::HoldsQueue::CreateQueue();
1113
1114     my $queue_rs = $schema->resultset('TmpHoldsqueue');
1115     my $q = $queue_rs->next;
1116     is( $queue_rs->count(), 1,
1117         "Hold queue contains one hold" );
1118     is(
1119         $q->borrowernumber->borrowernumber,
1120         $local_patron->borrowernumber,
1121         "We should pick the local hold over the next available"
1122     );
1123 };
1124
1125 subtest "Test Local Holds Priority - Get correct item for item level hold" => sub {
1126     plan tests => 3;
1127
1128     Koha::Biblios->delete();
1129     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
1130     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
1131     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
1132     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
1133     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
1134     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
1135     my $local_patron = $builder->build_object(
1136         {
1137             class => "Koha::Patrons",
1138             value => {
1139                 branchcode => $branch->branchcode,
1140                 categorycode => $category->categorycode,
1141             }
1142         }
1143     );
1144     my $other_patron = $builder->build_object(
1145         {
1146             class => "Koha::Patrons",
1147             value => {
1148                 branchcode => $branch2->branchcode,
1149                 categorycode => $category->categorycode,
1150             }
1151         }
1152     );
1153     my $biblio = $builder->build_sample_biblio();
1154
1155     my $item1 = $builder->build_sample_item(
1156         {
1157             biblionumber  => $biblio->biblionumber,
1158             library    => $branch->branchcode,
1159             exclude_from_local_holds_priority => 0,
1160         }
1161     );
1162     my $item2 = $builder->build_sample_item(
1163         {
1164             biblionumber  => $biblio->biblionumber,
1165             library    => $branch->branchcode,
1166             exclude_from_local_holds_priority => 0,
1167         }
1168     );
1169     my $item3 = $builder->build_sample_item(
1170         {
1171             biblionumber  => $biblio->biblionumber,
1172             library    => $branch->branchcode,
1173             exclude_from_local_holds_priority => 0,
1174         }
1175     );
1176
1177     my $reserve_id2 =
1178         AddReserve(
1179             {
1180                 branchcode     => $item2->homebranch,
1181                 borrowernumber => $local_patron->borrowernumber,
1182                 biblionumber   => $biblio->biblionumber,
1183                 priority       => 2,
1184                 itemnumber     => $item2->id,
1185             }
1186         );
1187
1188
1189     C4::HoldsQueue::CreateQueue();
1190
1191     my $queue_rs = $schema->resultset('TmpHoldsqueue');
1192     my $q = $queue_rs->next;
1193     is( $queue_rs->count(), 1,
1194         "Hold queue contains one hold" );
1195     is(
1196         $q->borrowernumber->borrowernumber,
1197         $local_patron->borrowernumber,
1198         "We should pick the local hold over the next available"
1199     );
1200     is( $q->itemnumber->id, $item2->id, "Got the correct item for item level local holds priority" );
1201 };
1202
1203 subtest "Test Local Holds Priority - Ensure no duplicate requests in holds queue (Bug 18001)" => sub {
1204     plan tests => 1;
1205
1206     $dbh->do("DELETE FROM tmp_holdsqueue");
1207     $dbh->do("DELETE FROM hold_fill_targets");
1208     $dbh->do("DELETE FROM reserves");
1209     $dbh->do("DELETE FROM circulation_rules");
1210     Koha::Biblios->delete();
1211
1212     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
1213     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
1214     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
1215     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
1216     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
1217     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
1218     my $patron  = $builder->build_object(
1219         {
1220             class => "Koha::Patrons",
1221             value => {
1222                 branchcode => $branch->branchcode,
1223                 categorycode => $category->categorycode,
1224             }
1225         }
1226     );
1227     my $biblio = $builder->build_sample_biblio();
1228     my $item1  = $builder->build_sample_item(
1229         {
1230             biblionumber => $biblio->biblionumber,
1231             library      => $branch->branchcode,
1232             exclude_from_local_holds_priority => 0,
1233         }
1234     );
1235     my $item2 = $builder->build_sample_item(
1236         {
1237             biblionumber => $biblio->biblionumber,
1238             library      => $branch->branchcode,
1239             exclude_from_local_holds_priority => 0,
1240         }
1241     );
1242
1243     my $item3 = $builder->build_sample_item(
1244         {
1245             biblionumber => $biblio->biblionumber,
1246             library      => $branch->branchcode,
1247             exclude_from_local_holds_priority => 0,
1248         }
1249     );
1250
1251     $reserve_id = AddReserve(
1252         {
1253             branchcode     => $item1->homebranch,
1254             borrowernumber => $patron->borrowernumber,
1255             biblionumber   => $biblio->id,
1256             priority       => 1
1257         }
1258     );
1259
1260     C4::HoldsQueue::CreateQueue();
1261
1262     my $queue_rs = $schema->resultset('TmpHoldsqueue');
1263
1264     is( $queue_rs->count(), 1,
1265         "Hold queue contains one hold from chosen from three possible items" );
1266 };
1267
1268
1269 subtest "Item level holds info is preserved (Bug 25738)" => sub {
1270
1271     plan tests => 4;
1272
1273     $dbh->do("DELETE FROM tmp_holdsqueue");
1274     $dbh->do("DELETE FROM hold_fill_targets");
1275     $dbh->do("DELETE FROM reserves");
1276     $dbh->do("DELETE FROM circulation_rules");
1277
1278     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
1279     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
1280     my $patron_1 = $builder->build_object(
1281         {
1282             class => "Koha::Patrons",
1283             value => {
1284                 branchcode => $library->branchcode,
1285                 categorycode => $category->categorycode
1286             }
1287         }
1288     );
1289
1290     my $patron_2 = $builder->build_object(
1291         {
1292             class => "Koha::Patrons",
1293             value => {
1294                 branchcode => $library->branchcode,
1295                 categorycode => $category->categorycode
1296             }
1297         }
1298     );
1299
1300     my $biblio = $builder->build_sample_biblio();
1301     my $item_1 = $builder->build_sample_item(
1302         {
1303             biblionumber => $biblio->biblionumber,
1304             library      => $library->branchcode,
1305             exclude_from_local_holds_priority => 0,
1306         }
1307     );
1308     my $item_2 = $builder->build_sample_item(
1309         {
1310             biblionumber => $biblio->biblionumber,
1311             library      => $library->branchcode,
1312             exclude_from_local_holds_priority => 0,
1313         }
1314     );
1315
1316     # Add item-level hold for patron_1
1317     my $reserve_id_1 = AddReserve(
1318         {
1319             branchcode     => $library->branchcode,
1320             borrowernumber => $patron_1->borrowernumber,
1321             biblionumber   => $biblio->id,
1322             itemnumber     => $item_1->itemnumber,
1323             priority       => 1
1324         }
1325     );
1326
1327     my $reserve_id_2 = AddReserve(
1328         {
1329             branchcode     => $library->branchcode,
1330             borrowernumber => $patron_2->borrowernumber,
1331             biblionumber   => $biblio->id,
1332             priority       => 2
1333         }
1334     );
1335
1336     C4::HoldsQueue::CreateQueue();
1337
1338     my $queue_rs = $schema->resultset('TmpHoldsqueue');
1339
1340     is( $queue_rs->count(), 2, "Hold queue contains two holds" );
1341
1342     my $queue_line_1 = $queue_rs->next;
1343     is( $queue_line_1->item_level_request, 1, 'Request is correctly advertised as item-level' );
1344     my $target_rs = $schema->resultset('HoldFillTarget')->search({borrowernumber=>$patron_1->borrowernumber});;
1345     is( $target_rs->next->reserve_id, $reserve_id_1, "Reserve id correctly set in hold fill target for item level hold" );
1346
1347     my $queue_line_2 = $queue_rs->next;
1348     is( $queue_line_2->item_level_request, 0, 'Request is correctly advertised as biblio-level' );
1349
1350 };
1351
1352 subtest 'Trivial test for UpdateTransportCostMatrix' => sub {
1353     plan tests => 1;
1354     my $recs = [
1355         { frombranch => $library1->{branchcode}, tobranch => $library2->{branchcode}, cost => 1, disable_transfer => 0 },
1356         { frombranch => $library2->{branchcode}, tobranch => $library3->{branchcode}, cost => 0, disable_transfer => 1 },
1357     ];
1358     C4::HoldsQueue::UpdateTransportCostMatrix( $recs );
1359     is( $schema->resultset('TransportCost')->count, 2, 'UpdateTransportCostMatrix added two records' );
1360 };
1361
1362 subtest 'Excludes from local holds priority' => sub {
1363     plan tests => 8;
1364
1365     Koha::Holds->delete;
1366
1367     t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 );
1368     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' );
1369     t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' );
1370
1371     my $branch  = $builder->build_object( { class => 'Koha::Libraries' } );
1372     my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } );
1373     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
1374     my $excluded_category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 1} });
1375     my $local_patron_excluded = $builder->build_object(
1376         {
1377             class => "Koha::Patrons",
1378             value => {
1379                 branchcode => $branch->branchcode,
1380                 categorycode => $excluded_category->categorycode
1381             }
1382         }
1383     );
1384
1385     my $local_patron_not_excluded = $builder->build_object(
1386         {
1387             class => "Koha::Patrons",
1388             value => {
1389                 branchcode => $branch->branchcode,
1390                 categorycode => $category->categorycode
1391             }
1392         }
1393     );
1394
1395     my $other_patron = $builder->build_object(
1396         {
1397             class => "Koha::Patrons",
1398             value => {
1399                 branchcode => $branch2->branchcode,
1400                 categorycode => $category->categorycode
1401             }
1402         }
1403     );
1404
1405     my $item1  = $builder->build_sample_item(
1406         {
1407             library      => $branch->branchcode,
1408             exclude_from_local_holds_priority => 0,
1409         }
1410     );
1411
1412     AddReserve(
1413         {
1414             branchcode     => $other_patron->branchcode,
1415             borrowernumber => $other_patron->borrowernumber,
1416             biblionumber   => $item1->biblionumber,
1417             priority       => 1,
1418             itemtype       => $item1->effective_itemtype
1419         }
1420     );
1421
1422     AddReserve(
1423         {
1424             branchcode     => $local_patron_excluded->branchcode,
1425             borrowernumber => $local_patron_excluded->borrowernumber,
1426             biblionumber   => $item1->biblionumber,
1427             priority       => 2,
1428             itemtype       => $item1->effective_itemtype
1429         }
1430     );
1431
1432     AddReserve(
1433         {
1434             branchcode     => $local_patron_not_excluded->branchcode,
1435             borrowernumber => $local_patron_not_excluded->borrowernumber,
1436             biblionumber   => $item1->biblionumber,
1437             priority       => 3,
1438             itemtype       => $item1->effective_itemtype
1439         }
1440     );
1441
1442     C4::HoldsQueue::CreateQueue();
1443
1444     my $queue_rs = $schema->resultset('TmpHoldsqueue');
1445     my $next = $queue_rs->next;
1446     is($queue_rs->count, 1, 'Only 1 patron queueud' );
1447     is($next->borrowernumber->borrowernumber, $local_patron_not_excluded->borrowernumber, 'Not excluded local patron is queued');
1448
1449     my $item2  = $builder->build_sample_item(
1450         {
1451             biblionumber => $item1->biblionumber,
1452             library      => $branch->branchcode,
1453             exclude_from_local_holds_priority => 1,
1454         }
1455     );
1456     C4::HoldsQueue::CreateQueue();
1457
1458     $queue_rs = $schema->resultset('TmpHoldsqueue');
1459     is( $queue_rs->count, 2, '2 patrons queued' );
1460     $next = $queue_rs->next;
1461     is($next->borrowernumber->borrowernumber, $local_patron_not_excluded->borrowernumber, 'Not excluded local patron is queued');
1462     $next = $queue_rs->next;
1463     is($next->borrowernumber->borrowernumber, $other_patron->borrowernumber, 'Other patron is queued');
1464
1465     $item1->exclude_from_local_holds_priority(1)->store;
1466
1467     C4::HoldsQueue::CreateQueue();
1468
1469     $queue_rs = $schema->resultset('TmpHoldsqueue');
1470     is( $queue_rs->count, 2, '2 patrons queued' );
1471     $next = $queue_rs->next;
1472     is($next->borrowernumber->borrowernumber, $other_patron->borrowernumber, 'Other patron is queued');
1473     $next = $queue_rs->next;
1474     is($next->borrowernumber->borrowernumber, $local_patron_excluded->borrowernumber, 'Excluded local patron is queued');
1475 };
1476
1477 subtest "Test item group holds" => sub {
1478
1479     plan tests => 4;
1480
1481     $dbh->do("DELETE FROM tmp_holdsqueue");
1482     $dbh->do("DELETE FROM hold_fill_targets");
1483     $dbh->do("DELETE FROM reserves");
1484     $dbh->do("DELETE FROM circulation_rules");
1485
1486     t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 0);
1487     t::lib::Mocks::mock_preference('LocalHoldsPriority', 0);
1488
1489     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
1490     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
1491     my $patron_1 = $builder->build_object(
1492         {
1493             class => "Koha::Patrons",
1494             value => {
1495                 branchcode => $library->branchcode,
1496                 categorycode => $category->categorycode
1497             }
1498         }
1499     );
1500
1501     my $patron_2 = $builder->build_object(
1502         {
1503             class => "Koha::Patrons",
1504             value => {
1505                 branchcode => $library->branchcode,
1506                 categorycode => $category->categorycode
1507             }
1508         }
1509     );
1510
1511     my $patron_3 = $builder->build_object(
1512         {
1513             class => "Koha::Patrons",
1514             value => {
1515                 branchcode => $library->branchcode,
1516                 categorycode => $category->categorycode
1517             }
1518         }
1519     );
1520
1521     my $patron_4 = $builder->build_object(
1522         {
1523             class => "Koha::Patrons",
1524             value => {
1525                 branchcode => $library->branchcode,
1526                 categorycode => $category->categorycode
1527             }
1528         }
1529     );
1530
1531     my $biblio = $builder->build_sample_biblio();
1532
1533     my $item_1 = $builder->build_sample_item(
1534         {
1535             biblionumber => $biblio->biblionumber,
1536             library      => $library->branchcode,
1537             exclude_from_local_holds_priority => 0,
1538         }
1539     );
1540     my $item_2 = $builder->build_sample_item(
1541         {
1542             biblionumber => $biblio->biblionumber,
1543             library      => $library->branchcode,
1544             exclude_from_local_holds_priority => 0,
1545         }
1546     );
1547     my $item_3 = $builder->build_sample_item(
1548         {
1549             biblionumber => $biblio->biblionumber,
1550             library      => $library->branchcode,
1551             exclude_from_local_holds_priority => 0,
1552         }
1553     );
1554     my $item_4 = $builder->build_sample_item(
1555         {
1556             biblionumber => $biblio->biblionumber,
1557             library      => $library->branchcode,
1558             exclude_from_local_holds_priority => 0,
1559         }
1560     );
1561
1562     my $item_group_1 = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store();
1563     my $item_group_2 = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store();
1564
1565     $item_group_1->add_item({ item_id => $item_1->id });
1566     $item_group_1->add_item({ item_id => $item_2->id });
1567
1568     # Add item-level hold for patron_1
1569     my $reserve_id_1 = AddReserve(
1570         {
1571             branchcode     => $library->branchcode,
1572             borrowernumber => $patron_1->borrowernumber,
1573             biblionumber   => $biblio->id,
1574             itemnumber     => $item_1->itemnumber,
1575             priority       => 1,
1576             item_group_id  => $item_group_1->id
1577         }
1578     );
1579
1580     my $reserve_id_2 = AddReserve(
1581         {
1582             branchcode     => $library->branchcode,
1583             borrowernumber => $patron_2->borrowernumber,
1584             biblionumber   => $biblio->id,
1585             priority       => 2,
1586             item_group_id  => $item_group_2->id
1587         }
1588     );
1589
1590     my $reserve_id_3 = AddReserve(
1591         {
1592             branchcode     => $library->branchcode,
1593             borrowernumber => $patron_3->borrowernumber,
1594             biblionumber   => $biblio->id,
1595             priority       => 3,
1596             item_group_id  => $item_group_1->id
1597         }
1598     );
1599
1600     my $reserve_id_4 = AddReserve(
1601         {
1602             branchcode     => $library->branchcode,
1603             borrowernumber => $patron_4->borrowernumber,
1604             biblionumber   => $biblio->id,
1605             priority       => 4,
1606             item_group_id  => undef
1607         }
1608     );
1609
1610     C4::HoldsQueue::CreateQueue();
1611
1612     my $queue_rs = $schema->resultset('TmpHoldsqueue');
1613
1614     is( $queue_rs->count(), 3, "Hold queue contains two holds" );
1615
1616     my $queue_line_1 = $queue_rs->next;
1617     is( $queue_line_1->borrowernumber->id, $patron_1->id, "Correct Hold was filled for the correct patron, item group 1, priority 1" );
1618
1619     my $queue_line_2 = $queue_rs->next;
1620     is( $queue_line_2->borrowernumber->id, $patron_3->id, "Correct Hold was filled for the correct patron, item group 1, priority 2" );
1621
1622     my $queue_line_3 = $queue_rs->next;
1623     is( $queue_line_3->borrowernumber->id, $patron_4->id, "Correct Hold was filled for the correct patron, no item group" );
1624 };
1625
1626 # Cleanup
1627 $schema->storage->txn_rollback;
1628
1629 ### END Test holds queue builder does not violate holds policy ###
1630
1631 sub test_queue {
1632     my ($test_name, $use_cost_matrix, $pick_branch, $hold_branch) = @_;
1633
1634     $test_name = "$test_name (".($use_cost_matrix ? "" : "don't ")."use cost matrix)";
1635
1636     $use_cost_matrix_sth->execute($use_cost_matrix);
1637     C4::Context->clear_syspref_cache();
1638     C4::HoldsQueue::CreateQueue();
1639
1640     my $results = $dbh->selectall_arrayref($test_sth, { Slice => {} }); # should be only one
1641     my $r = $results->[0];
1642
1643     my $ok = is( $r->{pickbranch}, $pick_branch, "$test_name pick up branch");
1644     $ok &&=  is( $r->{holdingbranch}, $hold_branch, "$test_name holding branch")
1645       if $hold_branch;
1646
1647     diag( "Wrong pick-up/hold for first target (pick_branch, hold_branch, reserves, hold_fill_targets, tmp_holdsqueue): "
1648         . Dumper ($pick_branch, $hold_branch, map dump_records($_), qw(reserves hold_fill_targets tmp_holdsqueue)) )
1649       unless $ok;
1650
1651     # Test enforcement of branch transfer limit
1652     if ( $r->{pickbranch} ne $r->{holdingbranch} ) {
1653         t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' );
1654         my $limit = Koha::Item::Transfer::Limit->new(
1655             {
1656                 toBranch   => $r->{pickbranch},
1657                 fromBranch => $r->{holdingbranch},
1658                 itemtype   => $r->{itype},
1659             }
1660         )->store();
1661         C4::Context->clear_syspref_cache();
1662         C4::HoldsQueue::CreateQueue();
1663         $results = $dbh->selectall_arrayref( $test_sth, { Slice => {} } )
1664           ;    # should be only one
1665         my $s = $results->[0];
1666         isnt( $r->{holdingbranch}, $s->{holdingbranch}, 'Hold is not trapped for pickup at a branch that cannot be transferred to');
1667
1668         $limit->delete();
1669         t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' );
1670         C4::Context->clear_syspref_cache();
1671         C4::HoldsQueue::CreateQueue();
1672     }
1673
1674 }
1675
1676 subtest "Test _checkHoldPolicy" => sub {
1677
1678     plan tests => 25;
1679
1680     $schema->storage->txn_begin;
1681
1682     my $library1  = $builder->build_object( { class => 'Koha::Libraries' } );
1683     my $library2  = $builder->build_object( { class => 'Koha::Libraries' } );
1684     my $library_nongroup = $builder->build_object( { class => 'Koha::Libraries' } );
1685     my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} });
1686     my $patron  = $builder->build_object(
1687         {
1688             class => "Koha::Patrons",
1689             value => {
1690                 branchcode => $library1->branchcode,
1691                 categorycode => $category->categorycode,
1692             }
1693         }
1694     );
1695     my $biblio = $builder->build_sample_biblio();
1696     my $item1  = $builder->build_sample_item(
1697         {
1698             biblionumber => $biblio->biblionumber,
1699             library      => $library1->branchcode,
1700             exclude_from_local_holds_priority => 0,
1701         }
1702     );
1703
1704     $reserve_id = AddReserve(
1705         {
1706             branchcode     => $item1->homebranch,
1707             borrowernumber => $patron->borrowernumber,
1708             biblionumber   => $biblio->id,
1709             priority       => 1
1710         }
1711     );
1712     ok( $reserve_id, "Hold was created");
1713     my $requests = C4::HoldsQueue::GetPendingHoldRequestsForBib($biblio->biblionumber);
1714     is( @$requests, 1, "Got correct number of holds");
1715
1716     my $request = $requests->[0];
1717     is( $request->{biblionumber}, $biblio->id, "Hold has correct biblio");
1718     is( $request->{borrowernumber}, $patron->id, "Hold has correct borrower");
1719     is( $request->{borrowerbranch}, $patron->branchcode, "Hold has correct borrowerbranch");
1720
1721     my $hold = Koha::Holds->find( $reserve_id );
1722     ok( $hold, "Found hold" );
1723
1724     my $item = {
1725         holdallowed              => 'from_home_library',
1726         homebranch               => $request->{borrowerbranch}, # library1
1727         hold_fulfillment_policy  => 'any'
1728     };
1729
1730     # Base case should work
1731     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true" );
1732
1733     # Test holdallowed = 'not_allowed'
1734     $item->{holdallowed} = 'not_allowed';
1735     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, "_checkHoldPolicy returns false if holdallowed = not_allowed" );
1736
1737     # Test holdallowed = 'from_home_library'
1738     $item->{holdallowed} = 'from_home_library';
1739     $item->{homebranch} = $library_nongroup->id;
1740     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, "_checkHoldPolicy returns false if holdallowed = from_home_library and branches do not match" );
1741
1742     $item->{homebranch} = $request->{borrowerbranch};
1743     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if holdallowed = from_home_library and branches do match" );
1744
1745     # Test holdallowed = 3
1746     $item->{holdallowed} = 'from_local_hold_group';
1747     $item->{homebranch} = $library_nongroup->id;
1748     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, "_checkHoldPolicy returns false if branchode doesn't match, holdallowed = from_local_hold_group and no group branches exist" );
1749     $item->{homebranch} = $request->{borrowerbranch};
1750     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if branchode matches, holdallowed = from_local_hold_group and no group branches exist" );
1751
1752     # Create library groups hierarchy
1753     my $rootgroup = $builder->build_object( { class => 'Koha::Library::Groups', value => {ft_local_hold_group => 1} } );
1754     my $group1 = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library1->branchcode}} );
1755     my $group2 = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library2->branchcode}} );
1756
1757     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if holdallowed = from_local_hold_group and no group branches exist" );
1758
1759     $group1->delete;
1760
1761     # Test hold_fulfillment_policy = holdgroup
1762     $item->{hold_fulfillment_policy} = 'holdgroup';
1763     $item->{homebranch} = $library_nongroup->id;
1764     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, "_checkHoldPolicy returns true if library is not part of hold group, branches don't match and hfp = holdgroup" );
1765     $item->{homebranch} = $request->{borrowerbranch};
1766     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if library is not part of hold group, branches match and hfp = holdgroup" );
1767
1768     $group1 = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library1->branchcode}} );
1769     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if library is part of hold group with hfp = holdgroup" );
1770
1771     $item->{homebranch} = $library2->id;
1772     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if library is part of hold group with hfp = holdgroup" );
1773     $item->{homebranch} = $library1->id;
1774
1775     $group1->delete;
1776
1777     # Test hold_fulfillment_policy = homebranch
1778     $item->{hold_fulfillment_policy} = 'homebranch';
1779     $item->{homebranch} = $library_nongroup->id;
1780     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, "_checkHoldPolicy returns false if hfp = homebranch and pickup branch != item homebranch" );
1781
1782     $item->{homebranch} = $request->{borrowerbranch};
1783     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if hfp = homebranch and pickup branch = item homebranch" );
1784
1785     # Test hold_fulfillment_policy = holdingbranch
1786     $item->{hold_fulfillment_policy} = 'holdingbranch';
1787     $item->{holdingbranch} = $library_nongroup->id;
1788     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, "_checkHoldPolicy returns false if hfp = holdingbranch and pickup branch != item holdingbranch" );
1789
1790     $item->{holdingbranch} = $request->{borrowerbranch};
1791     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if hfp = holdingbranch and pickup branch = item holdingbranch" );
1792
1793     # Test hold_fulfillment_policy = patrongroup
1794     $item->{hold_fulfillment_policy} = 'patrongroup';
1795     $item->{borrowerbranch} = $library1->id;
1796
1797     $item->{homebranch} = $library_nongroup->id;
1798     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, "_checkHoldPolicy returns false if library is not part of hold group, branches don't match, hfp = patrongroup" );
1799     $item->{homebranch} = $request->{borrowerbranch};
1800     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns false if library is not part of hold group, branches match, hfp = patrongroup" );
1801
1802     $group1 = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library1->branchcode}} );
1803     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if library is part of hold group with hfp = holdgroup" );
1804
1805     $item->{borrowerbranch} = $library2->id;
1806     is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if library is part of hold group with hfp = holdgroup" );
1807     $item->{borrowerbranch} = $library1->id;
1808
1809     $schema->storage->txn_rollback;
1810 };
1811
1812 sub dump_records {
1813     my ($tablename) = @_;
1814     return $dbh->selectall_arrayref("SELECT * from $tablename where borrowernumber = ?", { Slice => {} }, $borrowernumber);
1815 }
1816
1817 subtest 'Remove holds on check-in match' => sub {
1818
1819     plan tests => 2;
1820
1821     $schema->storage->txn_begin;
1822
1823     my $lib = $builder->build_object( { class => 'Koha::Libraries' } );
1824
1825     my $patron1 = $builder->build_object(
1826         {
1827             class => 'Koha::Patrons',
1828             value => { branchcode => $lib->branchcode }
1829         }
1830     );
1831     my $patron2 = $builder->build_object(
1832         {
1833             class => 'Koha::Patrons',
1834             value => { branchcode => $lib->branchcode }
1835         }
1836     );
1837
1838     my $item = $builder->build_sample_item(
1839         { homebranch => $lib->branchcode, holdingbranch => $lib->branchcode } );
1840
1841     t::lib::Mocks::mock_userenv( { branchcode => $lib->branchcode } );
1842
1843     AddIssue( $patron1->unblessed, $item->barcode, dt_from_string );
1844
1845     my $hold_id = AddReserve(
1846         {
1847             branchcode     => $item->homebranch,
1848             borrowernumber => $patron2->borrowernumber,
1849             biblionumber   => $item->biblionumber,
1850             itemnumber     => undef,
1851             priority       => 1
1852         }
1853     );
1854
1855     my $hold = Koha::Holds->find($hold_id);
1856
1857     AddReturn( $item->barcode, $item->homebranch );
1858
1859     C4::HoldsQueue::CreateQueue();
1860
1861     my $sth = $dbh->prepare(q{
1862         SELECT  COUNT(*)
1863         FROM    tmp_holdsqueue q
1864         INNER JOIN hold_fill_targets t
1865         ON  q.borrowernumber = t.borrowernumber
1866             AND q.biblionumber = t.biblionumber
1867             AND q.itemnumber = t.itemnumber
1868             AND q.item_level_request = t.item_level_request
1869             AND q.holdingbranch = t.source_branchcode
1870         WHERE t.reserve_id = ?
1871     });
1872     $sth->execute($hold->reserve_id);
1873     my ($count_1) = $sth->fetchrow_array;
1874
1875     is( $count_1, 1, "Holds queue has one element" );
1876
1877     AddReturn( $item->barcode, $item->homebranch, undef, dt_from_string );
1878
1879     ModReserveAffect( $item->itemnumber, $hold->borrowernumber, 0,
1880         $hold->reserve_id );
1881
1882     $sth->execute($hold->reserve_id);
1883     my ($count_2) = $sth->fetchrow_array;
1884
1885     is( $count_2, 0,
1886         "Holds queue has no elements, even when queue was not rebuilt" );
1887
1888     $schema->storage->txn_rollback;
1889 };
1890
1891 subtest "GetHoldsQueueItems" => sub {
1892     plan tests => 4;
1893
1894     $schema->storage->txn_begin;
1895
1896     my $ccode = $builder->build_object(
1897         {
1898             class => 'Koha::AuthorisedValues',
1899             value => {
1900                 category => 'CCODE'
1901             }
1902         }
1903     );
1904     my $location = $builder->build_object(
1905         {
1906             class => 'Koha::AuthorisedValues',
1907             value => {
1908                 category => 'LOC'
1909             }
1910         }
1911     );
1912     my $item_1 = $builder->build_sample_item();
1913     my $item_2 = $builder->build_sample_item(
1914         {
1915             itype => $item_1->itype,
1916             ccode => $ccode->authorised_value
1917         }
1918     );
1919     my $item_3 = $builder->build_sample_item(
1920         {
1921             itype    => $item_1->itype,
1922             ccode    => $item_2->ccode,
1923             location => $location->authorised_value
1924         }
1925     );
1926
1927     my $itemnumber_1 = $item_1->itemnumber;
1928     my $itemnumber_2 = $item_2->itemnumber;
1929     my $itemnumber_3 = $item_3->itemnumber;
1930
1931     my $biblionumber_1 = $item_1->biblionumber;
1932     my $biblionumber_2 = $item_2->biblionumber;
1933     my $biblionumber_3 = $item_3->biblionumber;
1934
1935     my $sth = $dbh->prepare(q{ SELECT  COUNT(*) FROM tmp_holdsqueue });
1936     $sth->execute();
1937     my ($count) = $sth->fetchrow_array;
1938
1939     $dbh->do( "
1940         INSERT INTO tmp_holdsqueue (itemnumber,biblionumber,surname,firstname,phone,borrowernumber,title,notes) VALUES
1941         ($itemnumber_1,$biblionumber_1,'','','',22,'',''),
1942         ($itemnumber_2,$biblionumber_2,'','','',32,'',''),
1943         ($itemnumber_3,$biblionumber_3,'','','',42,'','')
1944      " );
1945
1946     my $queue_items = GetHoldsQueueItems();
1947     is( scalar @$queue_items, $count + 3, 'Three items added to queue' );
1948
1949     $queue_items = GetHoldsQueueItems( { itemtypeslimit => $item_1->itype } );
1950     is( scalar @$queue_items,
1951         3, 'Three items of same itemtype found when itemtypeslimit passed' );
1952
1953     $queue_items = GetHoldsQueueItems(
1954         { itemtypeslimit => $item_1->itype, ccodeslimit => $item_2->ccode } );
1955     is( scalar @$queue_items,
1956         2, 'Two items of same collection found when ccodeslimit passed' );
1957
1958     @$queue_items = GetHoldsQueueItems(
1959         {
1960             itemtypeslimit => $item_1->itype,
1961             ccodeslimit    => $item_2->ccode,
1962             locationslimit => $item_3->location
1963         }
1964     );
1965     is( scalar @$queue_items,
1966         1, 'One item of shleving location found when locationslimit passed' );
1967
1968     $schema->storage->txn_rollback;
1969 };