Bug 12532: (QA follow-up) Add tests for SendQueuedMessages
[koha.git] / C4 / HoldsQueue.pm
1 package C4::HoldsQueue;
2
3 # Copyright 2011 Catalyst IT
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 # FIXME: expand perldoc, explain intended logic
21
22 use strict;
23 use warnings;
24
25 use C4::Context;
26 use C4::Circulation qw( GetBranchItemRule );
27 use Koha::DateUtils qw( dt_from_string );
28 use Koha::Hold::HoldsQueueItems;
29 use Koha::Items;
30 use Koha::Libraries;
31 use Koha::Patrons;
32
33 use List::Util qw( shuffle );
34 use List::MoreUtils qw( any );
35
36 our (@ISA, @EXPORT_OK);
37 BEGIN {
38     require Exporter;
39     @ISA = qw(Exporter);
40     @EXPORT_OK = qw(
41         CreateQueue
42         GetHoldsQueueItems
43
44         TransportCostMatrix
45         UpdateTransportCostMatrix
46         GetPendingHoldRequestsForBib
47         load_branches_to_pull_from
48         update_queue_for_biblio
49      );
50 }
51
52
53 =head1 FUNCTIONS
54
55 =head2 TransportCostMatrix
56
57   TransportCostMatrix();
58
59 Returns Transport Cost Matrix as a hashref <to branch code> => <from branch code> => cost
60
61 =cut
62
63 sub TransportCostMatrix {
64     my ( $params ) = @_;
65
66     my $dbh   = C4::Context->dbh;
67     my $transport_costs = $dbh->selectall_arrayref("SELECT * FROM transport_cost",{ Slice => {} });
68
69     my $today = dt_from_string();
70     my %transport_cost_matrix;
71     foreach (@$transport_costs) {
72         my $from     = $_->{frombranch};
73         my $to       = $_->{tobranch};
74         my $cost     = $_->{cost};
75         my $disabled = $_->{disable_transfer};
76         $transport_cost_matrix{$to}{$from} = {
77             cost             => $cost,
78             disable_transfer => $disabled
79         };
80     }
81
82     return \%transport_cost_matrix;
83 }
84
85 =head2 UpdateTransportCostMatrix
86
87   UpdateTransportCostMatrix($records);
88
89 Updates full Transport Cost Matrix table. $records is an arrayref of records.
90 Records: { frombranch => <code>, tobranch => <code>, cost => <figure>, disable_transfer => <0,1> }
91
92 =cut
93
94 sub UpdateTransportCostMatrix {
95     my ($records) = @_;
96     my $dbh   = C4::Context->dbh;
97
98     my $sth = $dbh->prepare("INSERT INTO transport_cost (frombranch, tobranch, cost, disable_transfer) VALUES (?, ?, ?, ?)");
99
100     $dbh->do("DELETE FROM transport_cost");
101     foreach (@$records) {
102         my $cost = $_->{cost};
103         my $from = $_->{frombranch};
104         my $to = $_->{tobranch};
105         if ($_->{disable_transfer}) {
106             $cost ||= 0;
107         }
108         elsif ( !defined ($cost) || ($cost !~ m/(0|[1-9][0-9]*)(\.[0-9]*)?/o) ) {
109             warn  "Invalid $from -> $to cost $cost - must be a number >= 0, disabling";
110             $cost = 0;
111             $_->{disable_transfer} = 1;
112         }
113         $sth->execute( $from, $to, $cost, $_->{disable_transfer} ? 1 : 0 );
114     }
115 }
116
117 =head2 GetHoldsQueueItems
118
119   GetHoldsQueueItems({ branchlimit => $branch, itemtypeslimit =>  $itype, ccodeslimit => $ccode, locationslimit => $location );
120
121 Returns hold queue for a holding branch. If branch is omitted, then whole queue is returned
122
123 =cut
124
125 sub GetHoldsQueueItems {
126     my $params = shift;
127     my $dbh   = C4::Context->dbh;
128
129     my $search_params;
130     $search_params->{'me.holdingbranch'} = $params->{branchlimit} if $params->{branchlimit};
131     $search_params->{'itype'} = $params->{itemtypeslimit} if $params->{itemtypeslimit};
132     $search_params->{'ccode'} = $params->{ccodeslimit} if $params->{ccodeslimit};
133     $search_params->{'location'} = $params->{locationslimit} if $params->{locationslimit};
134
135     my $results = Koha::Hold::HoldsQueueItems->search(
136         $search_params,
137         {
138             join => [
139                 'borrower',
140             ],
141             prefetch => [
142                 'biblio',
143                 'biblioitem',
144                 {
145                     'item' => {
146                         'item_group_item' => 'item_group'
147                     }
148                 }
149             ],
150             order_by => [
151                 'ccode',        'location',   'item.cn_sort', 'author',
152                 'biblio.title', 'pickbranch', 'reservedate'
153             ],
154         }
155     );
156
157     return $results;
158 }
159
160 =head2 CreateQueue
161
162   CreateQueue();
163
164 Top level function that turns reserves into tmp_holdsqueue and hold_fill_targets.
165
166 =cut
167
168 sub CreateQueue {
169     my $dbh   = C4::Context->dbh;
170
171     $dbh->do("DELETE FROM tmp_holdsqueue");  # clear the old table for new info
172     $dbh->do("DELETE FROM hold_fill_targets");
173
174     my $total_bibs            = 0;
175     my $total_requests        = 0;
176     my $total_available_items = 0;
177     my $num_items_mapped      = 0;
178
179     my $branches_to_use;
180     my $transport_cost_matrix;
181     my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix");
182     if ($use_transport_cost_matrix) {
183         $transport_cost_matrix = TransportCostMatrix();
184         unless (keys %$transport_cost_matrix) {
185             warn "UseTransportCostMatrix set to yes, but matrix not populated";
186             undef $transport_cost_matrix;
187         }
188     }
189
190     $branches_to_use = load_branches_to_pull_from($use_transport_cost_matrix);
191
192     my $bibs_with_pending_requests = GetBibsWithPendingHoldRequests();
193
194     foreach my $biblionumber (@$bibs_with_pending_requests) {
195
196         $total_bibs++;
197
198         my $result = update_queue_for_biblio(
199             {   biblio_id             => $biblionumber,
200                 branches_to_use       => $branches_to_use,
201                 transport_cost_matrix => $transport_cost_matrix,
202             }
203         );
204
205         $total_requests        += $result->{requests};
206         $total_available_items += $result->{available_items};
207         $num_items_mapped      += $result->{mapped_items};
208     }
209 }
210
211 =head2 GetBibsWithPendingHoldRequests
212
213   my $biblionumber_aref = GetBibsWithPendingHoldRequests();
214
215 Return an arrayref of the biblionumbers of all bibs
216 that have one or more unfilled hold requests.
217
218 =cut
219
220 sub GetBibsWithPendingHoldRequests {
221     my $dbh = C4::Context->dbh;
222
223     my $bib_query = "SELECT DISTINCT biblionumber
224                      FROM reserves
225                      WHERE found IS NULL
226                      AND priority > 0
227                      AND reservedate <= CURRENT_DATE()
228                      AND suspend = 0
229                      ";
230     my $sth = $dbh->prepare($bib_query);
231
232     $sth->execute();
233     my $biblionumbers = $sth->fetchall_arrayref();
234
235     return [ map { $_->[0] } @$biblionumbers ];
236 }
237
238 =head2 GetPendingHoldRequestsForBib
239
240   my $requests = GetPendingHoldRequestsForBib($biblionumber);
241
242 Returns an arrayref of hashrefs to pending, unfilled hold requests
243 on the bib identified by $biblionumber.  The following keys
244 are present in each hashref:
245
246     biblionumber
247     borrowernumber
248     itemnumber
249     priority
250     branchcode
251     reservedate
252     reservenotes
253     borrowerbranch
254
255 The arrayref is sorted in order of increasing priority.
256
257 =cut
258
259 sub GetPendingHoldRequestsForBib {
260     my $biblionumber = shift;
261
262     my $dbh = C4::Context->dbh;
263
264     my $request_query = "SELECT biblionumber, borrowernumber, itemnumber, priority, reserve_id, reserves.branchcode,
265                                 reservedate, reservenotes, borrowers.branchcode AS borrowerbranch, itemtype, item_level_hold, item_group_id
266                          FROM reserves
267                          JOIN borrowers USING (borrowernumber)
268                          WHERE biblionumber = ?
269                          AND found IS NULL
270                          AND priority > 0
271                          AND reservedate <= CURRENT_DATE()
272                          AND suspend = 0
273                          ORDER BY priority";
274     my $sth = $dbh->prepare($request_query);
275     $sth->execute($biblionumber);
276
277     my $requests = $sth->fetchall_arrayref({});
278     return $requests;
279
280 }
281
282 =head2 GetItemsAvailableToFillHoldRequestsForBib
283
284   my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_ar);
285
286 Returns an arrayref of items available to fill hold requests
287 for the bib identified by C<$biblionumber>.  An item is available
288 to fill a hold request if and only if:
289
290     * it is not on loan
291     * it is not withdrawn
292     * it is not marked notforloan
293     * it is not currently in transit
294     * it is not lost
295     * it is not sitting on the hold shelf
296     * it is not damaged (unless AllowHoldsOnDamagedItems is on)
297
298 =cut
299
300 sub GetItemsAvailableToFillHoldRequestsForBib {
301     my ($biblionumber, $branches_to_use) = @_;
302
303     my $dbh = C4::Context->dbh;
304     my $items_query = "SELECT items.itemnumber, homebranch, holdingbranch, itemtypes.itemtype AS itype
305                        FROM items ";
306
307     if (C4::Context->preference('item-level_itypes')) {
308         $items_query .=   "LEFT JOIN itemtypes ON (itemtypes.itemtype = items.itype) ";
309     } else {
310         $items_query .=   "JOIN biblioitems USING (biblioitemnumber)
311                            LEFT JOIN itemtypes USING (itemtype) ";
312     }
313     $items_query .=  " LEFT JOIN branchtransfers ON (
314                            items.itemnumber = branchtransfers.itemnumber
315                            AND branchtransfers.datearrived IS NULL AND branchtransfers.datecancelled IS NULL
316                      )";
317     $items_query .=  " WHERE items.notforloan = 0
318                        AND holdingbranch IS NOT NULL
319                        AND itemlost = 0
320                        AND withdrawn = 0";
321     $items_query .= "  AND damaged = 0" unless C4::Context->preference('AllowHoldsOnDamagedItems');
322     $items_query .= "  AND items.onloan IS NULL
323                        AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
324                        AND items.itemnumber NOT IN (
325                            SELECT itemnumber
326                            FROM reserves
327                            WHERE biblionumber = ?
328                            AND itemnumber IS NOT NULL
329                            AND (found IS NOT NULL OR priority = 0)
330                         )
331                        AND items.biblionumber = ?
332                        AND branchtransfers.itemnumber IS NULL";
333
334     my @params = ($biblionumber, $biblionumber);
335     if ($branches_to_use && @$branches_to_use) {
336         $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
337         push @params, @$branches_to_use;
338     }
339     my $sth = $dbh->prepare($items_query);
340     $sth->execute(@params);
341
342     my $itm = $sth->fetchall_arrayref({});
343     return [ grep {
344         my $rule = C4::Circulation::GetBranchItemRule($_->{homebranch}, $_->{itype});
345         $_->{holdallowed} = $rule->{holdallowed};
346         $_->{hold_fulfillment_policy} = $rule->{hold_fulfillment_policy};
347     } @{$itm} ];
348 }
349
350 =head2 _checkHoldPolicy
351
352     _checkHoldPolicy($item, $request)
353
354     check if item agrees with hold policies
355
356 =cut
357
358 sub _checkHoldPolicy {
359     my ( $item, $request ) = @_;
360
361     return 0 unless $item->{holdallowed} ne 'not_allowed';
362
363     return 0
364       if $item->{holdallowed} eq 'from_home_library'
365       && $item->{homebranch} ne $request->{borrowerbranch};
366
367     return 0
368       if $item->{'holdallowed'} eq 'from_local_hold_group'
369       && !Koha::Libraries->find( $item->{homebranch} )
370               ->validate_hold_sibling( { branchcode => $request->{borrowerbranch} } );
371
372     my $hold_fulfillment_policy = $item->{hold_fulfillment_policy};
373
374     return 0
375       if $hold_fulfillment_policy eq 'holdgroup'
376       && !Koha::Libraries->find( $item->{homebranch} )
377             ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
378
379     return 0
380       if $hold_fulfillment_policy eq 'homebranch'
381       && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
382
383     return 0
384       if $hold_fulfillment_policy eq 'holdingbranch'
385       && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
386
387     return 0
388       if $hold_fulfillment_policy eq 'patrongroup'
389       && !Koha::Libraries->find( $request->{borrowerbranch} )
390               ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
391
392     return 1;
393
394 }
395
396 =head2 MapItemsToHoldRequests
397
398   MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
399
400 =cut
401
402 sub MapItemsToHoldRequests {
403     my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
404
405     # handle trival cases
406     return unless scalar(@$hold_requests) > 0;
407     return unless scalar(@$available_items) > 0;
408
409     # identify item-level requests
410     my %specific_items_requested = map { $_->{itemnumber} => 1 }
411                                    grep { defined($_->{itemnumber}) }
412                                    @$hold_requests;
413
414     map { $_->{_object} = Koha::Items->find( $_->{itemnumber} ) } @$available_items;
415     my $libraries = {};
416     map { $libraries->{$_->id} = $_ } Koha::Libraries->search->as_list;
417
418     # group available items by itemnumber
419     my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
420
421     # items already allocated
422     my %allocated_items = ();
423
424     # map of items to hold requests
425     my %item_map = ();
426
427     # figure out which item-level requests can be filled
428     my $num_items_remaining = scalar(@$available_items);
429
430     # Look for Local Holds Priority matches first
431     if ( C4::Context->preference('LocalHoldsPriority') ) {
432         my $LocalHoldsPriorityPatronControl =
433           C4::Context->preference('LocalHoldsPriorityPatronControl');
434         my $LocalHoldsPriorityItemControl =
435           C4::Context->preference('LocalHoldsPriorityItemControl');
436
437         foreach my $request (@$hold_requests) {
438             last if $num_items_remaining == 0;
439             my $patron = Koha::Patrons->find($request->{borrowernumber});
440             next if $patron->category->exclude_from_local_holds_priority;
441
442             my $local_hold_match;
443             foreach my $item (@$available_items) {
444                 next if $item->{_object}->exclude_from_local_holds_priority;
445
446                 next unless _checkHoldPolicy($item, $request);
447
448                 next if $request->{itemnumber} && $request->{itemnumber} != $item->{itemnumber};
449
450                 next if $request->{item_group_id} && $item->{_object}->item_group && $item->{_object}->item_group->id ne $request->{item_group_id};
451
452                 next unless $item->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
453
454                 my $local_holds_priority_item_branchcode =
455                   $item->{$LocalHoldsPriorityItemControl};
456
457                 my $local_holds_priority_patron_branchcode =
458                   ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
459                   ? $request->{branchcode}
460                   : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
461                   ? $request->{borrowerbranch}
462                   : undef;
463
464                 $local_hold_match =
465                   $local_holds_priority_item_branchcode eq
466                   $local_holds_priority_patron_branchcode;
467
468                 if ($local_hold_match) {
469                     if ( exists $items_by_itemnumber{ $item->{itemnumber} }
470                         and not exists $allocated_items{ $item->{itemnumber} }
471                         and not $request->{allocated})
472                     {
473                         $item_map{ $item->{itemnumber} } = {
474                             borrowernumber => $request->{borrowernumber},
475                             biblionumber   => $request->{biblionumber},
476                             holdingbranch  => $item->{holdingbranch},
477                             pickup_branch  => $request->{branchcode}
478                               || $request->{borrowerbranch},
479                             reserve_id   => $request->{reserve_id},
480                             item_level   => $request->{item_level_hold},
481                             reservedate  => $request->{reservedate},
482                             reservenotes => $request->{reservenotes},
483                         };
484                         $allocated_items{ $item->{itemnumber} }++;
485                         $request->{allocated} = 1;
486                         $num_items_remaining--;
487                     }
488                 }
489             }
490         }
491     }
492
493     foreach my $request (@$hold_requests) {
494         last if $num_items_remaining == 0;
495         next if $request->{allocated};
496
497         # is this an item-level request?
498         if (defined($request->{itemnumber})) {
499             # fill it if possible; if not skip it
500             if (
501                     exists $items_by_itemnumber{ $request->{itemnumber} }
502                 and not exists $allocated_items{ $request->{itemnumber} }
503                 and  _checkHoldPolicy($items_by_itemnumber{ $request->{itemnumber} }, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
504                 and ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
505                     || $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} )
506                 and ( !$request->{item_group_id} # If hold item_group is set, item's item_group must match
507                       || ( $items_by_itemnumber{ $request->{itemnumber} }->{_object}->item_group
508                         && $items_by_itemnumber{ $request->{itemnumber} }->{_object}->item_group->id eq $request->{item_group_id} ) )
509                 and $items_by_itemnumber{ $request->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } )
510
511               )
512             {
513
514                 $item_map{ $request->{itemnumber} } = {
515                     borrowernumber => $request->{borrowernumber},
516                     biblionumber   => $request->{biblionumber},
517                     holdingbranch  => $items_by_itemnumber{ $request->{itemnumber} }->{holdingbranch},
518                     pickup_branch  => $request->{branchcode} || $request->{borrowerbranch},
519                     reserve_id     => $request->{reserve_id},
520                     item_level     => $request->{item_level_hold},
521                     reservedate    => $request->{reservedate},
522                     reservenotes   => $request->{reservenotes},
523                 };
524                 $allocated_items{ $request->{itemnumber} }++;
525                 $num_items_remaining--;
526             }
527         } else {
528             # it's title-level request that will take up one item
529             $num_items_remaining--;
530         }
531     }
532
533     # group available items by branch
534     my %items_by_branch = ();
535     foreach my $item (@$available_items) {
536         next unless $item->{holdallowed} ne 'not_allowed';
537
538         push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
539           unless exists $allocated_items{ $item->{itemnumber} };
540     }
541     return \%item_map unless keys %items_by_branch;
542
543     # now handle the title-level requests
544     $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
545     my $pull_branches;
546     foreach my $request (@$hold_requests) {
547         last if $num_items_remaining == 0;
548         next if $request->{allocated};
549         next if defined($request->{itemnumber}); # already handled these
550
551         # look for local match first
552         my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
553         my ($itemnumber, $holdingbranch);
554
555         my $holding_branch_items = $items_by_branch{$pickup_branch};
556         my $priority_branch = C4::Context->preference('HoldsQueuePrioritizeBranch') // 'homebranch';
557         if ( $holding_branch_items ) {
558             foreach my $item (@$holding_branch_items) {
559                 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
560
561                 if (
562                     $request->{borrowerbranch} eq $item->{$priority_branch}
563                     && _checkHoldPolicy($item, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
564                     && ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
565                         || ( $request->{itemnumber} && ( $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} ) ) )
566                     && ( !$request->{item_group_id} # If hold item_group is set, item's item_group must match
567                         || ( $item->{_object}->item_group && $item->{_object}->item_group->id eq $request->{item_group_id} ) )
568                   )
569                 {
570                     $itemnumber = $item->{itemnumber};
571                     last;
572                 }
573             }
574             $holdingbranch = $pickup_branch;
575         }
576         elsif ($transport_cost_matrix) {
577             $pull_branches = [keys %items_by_branch];
578             $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
579             if ( $holdingbranch ) {
580
581                 my $holding_branch_items = $items_by_branch{$holdingbranch};
582                 foreach my $item (@$holding_branch_items) {
583                     next if $request->{borrowerbranch} ne $item->{$priority_branch};
584                     next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
585
586                     # Don't fill item level holds that contravene the hold pickup policy at this time
587                     next unless _checkHoldPolicy($item, $request);
588
589                     # If hold itemtype is set, item's itemtype must match
590                     next unless ( !$request->{itemtype}
591                         || $item->{itype} eq $request->{itemtype} );
592
593                     # If hold item_group is set, item's item_group must match
594                     next unless (
595                         !$request->{item_group_id}
596                         || (   $item->{_object}->item_group
597                             && $item->{_object}->item_group->id eq $request->{item_group_id} )
598                     );
599
600                     $itemnumber = $item->{itemnumber};
601                     last;
602                 }
603             }
604             else {
605                 next;
606             }
607         }
608
609         unless ($itemnumber) {
610             # not found yet, fall back to basics
611             if ($branches_to_use) {
612                 $pull_branches = $branches_to_use;
613             } else {
614                 $pull_branches = [keys %items_by_branch];
615             }
616
617             # Try picking items where the home and pickup branch match first
618             PULL_BRANCHES:
619             foreach my $branch (@$pull_branches) {
620                 my $holding_branch_items = $items_by_branch{$branch}
621                   or next;
622
623                 $holdingbranch ||= $branch;
624                 foreach my $item (@$holding_branch_items) {
625                     next if $pickup_branch ne $item->{homebranch};
626                     next unless _checkHoldPolicy($item, $request);
627                     next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
628
629                     # If hold itemtype is set, item's itemtype must match
630                     next unless ( !$request->{itemtype}
631                         || $item->{itype} eq $request->{itemtype} );
632
633                     # If hold item_group is set, item's item_group must match
634                     next unless (
635                         !$request->{item_group_id}
636                         || (   $item->{_object}->item_group
637                             && $item->{_object}->item_group->id eq $request->{item_group_id} )
638                     );
639
640                     $itemnumber = $item->{itemnumber};
641                     $holdingbranch = $branch;
642                     last PULL_BRANCHES;
643                 }
644             }
645
646             # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight
647             unless ( $itemnumber || !$holdingbranch) {
648                 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
649                     next unless _checkHoldPolicy($current_item, $request); # Don't fill item level holds that contravene the hold pickup policy at this time
650
651                     # If hold itemtype is set, item's itemtype must match
652                     next unless ( !$request->{itemtype}
653                         || $current_item->{itype} eq $request->{itemtype} );
654
655                     next unless $items_by_itemnumber{ $current_item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
656
657                     # If hold item_group is set, item's item_group must match
658                     next unless (
659                         !$request->{item_group_id}
660                         || (   $current_item->{_object}->item_group
661                             && $current_item->{_object}->item_group->id eq $request->{item_group_id} )
662                     );
663
664
665                     $itemnumber = $current_item->{itemnumber};
666                     last; # quit this loop as soon as we have a suitable item
667                 }
668             }
669
670             # Now try for items for any item that can fill this hold
671             unless ( $itemnumber ) {
672                 PULL_BRANCHES2:
673                 foreach my $branch (@$pull_branches) {
674                     my $holding_branch_items = $items_by_branch{$branch}
675                       or next;
676
677                     foreach my $item (@$holding_branch_items) {
678                         # Don't fill item level holds that contravene the hold pickup policy at this time
679                         next unless _checkHoldPolicy($item, $request);
680
681                         # If hold itemtype is set, item's itemtype must match
682                         next unless ( !$request->{itemtype}
683                             || $item->{itype} eq $request->{itemtype} );
684
685                         # If hold item_group is set, item's item_group must match
686                         next unless (
687                             !$request->{item_group_id}
688                             || (   $item->{_object}->item_group
689                                 && $item->{_object}->item_group->id eq $request->{item_group_id} )
690                         );
691
692                         next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
693
694                         $itemnumber = $item->{itemnumber};
695                         $holdingbranch = $branch;
696                         last PULL_BRANCHES2;
697                     }
698                 }
699             }
700         }
701
702         if ($itemnumber) {
703             my $holding_branch_items = $items_by_branch{$holdingbranch}
704               or die "Have $itemnumber, $holdingbranch, but no items!";
705             @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
706             delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
707
708             $item_map{$itemnumber} = {
709                 borrowernumber => $request->{borrowernumber},
710                 biblionumber => $request->{biblionumber},
711                 holdingbranch => $holdingbranch,
712                 pickup_branch => $pickup_branch,
713                 reserve_id => $request->{reserve_id},
714                 item_level => $request->{item_level_hold},
715                 reservedate => $request->{reservedate},
716                 reservenotes => $request->{reservenotes},
717             };
718             $num_items_remaining--;
719         }
720     }
721     return \%item_map;
722 }
723
724 =head2 CreatePickListFromItemMap
725
726 =cut
727
728 sub CreatePicklistFromItemMap {
729     my $item_map = shift;
730
731     my $dbh = C4::Context->dbh;
732
733     my $sth_load=$dbh->prepare("
734         INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
735                                     cardnumber,reservedate,title, itemcallnumber,
736                                     holdingbranch,pickbranch,notes, item_level_request)
737         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
738     ");
739
740     foreach my $itemnumber  (sort keys %$item_map) {
741         my $mapped_item = $item_map->{$itemnumber};
742         my $biblionumber = $mapped_item->{biblionumber};
743         my $borrowernumber = $mapped_item->{borrowernumber};
744         my $pickbranch = $mapped_item->{pickup_branch};
745         my $holdingbranch = $mapped_item->{holdingbranch};
746         my $reservedate = $mapped_item->{reservedate};
747         my $reservenotes = $mapped_item->{reservenotes};
748         my $item_level = $mapped_item->{item_level};
749
750         my $item = Koha::Items->find($itemnumber);
751         my $barcode = $item->barcode;
752         my $itemcallnumber = $item->itemcallnumber;
753
754         my $patron = Koha::Patrons->find( $borrowernumber );
755         my $cardnumber = $patron->cardnumber;
756         my $surname = $patron->surname;
757         my $firstname = $patron->firstname;
758         my $phone = $patron->phone;
759
760         my $biblio = Koha::Biblios->find( $biblionumber );
761         my $title = $biblio->title;
762
763         $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
764                            $cardnumber, $reservedate, $title, $itemcallnumber,
765                            $holdingbranch, $pickbranch, $reservenotes, $item_level);
766     }
767 }
768
769 =head2 AddToHoldTargetMap
770
771 =cut
772
773 sub AddToHoldTargetMap {
774     my $item_map = shift;
775
776     my $dbh = C4::Context->dbh;
777
778     my $insert_sql = q(
779         INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request, reserve_id)
780                                VALUES (?, ?, ?, ?, ?, ?)
781     );
782     my $sth_insert = $dbh->prepare($insert_sql);
783
784     foreach my $itemnumber (keys %$item_map) {
785         my $mapped_item = $item_map->{$itemnumber};
786         $sth_insert->execute($mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
787                              $mapped_item->{holdingbranch}, $mapped_item->{item_level}, $mapped_item->{reserve_id});
788     }
789 }
790
791 # Helper functions, not part of any interface
792
793 sub _trim {
794     return $_[0] unless $_[0];
795     $_[0] =~ s/^\s+//;
796     $_[0] =~ s/\s+$//;
797     $_[0];
798 }
799
800 sub load_branches_to_pull_from {
801     my $use_transport_cost_matrix = shift;
802
803     my @branches_to_use;
804
805     unless ( $use_transport_cost_matrix ) {
806         my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight");
807         @branches_to_use = map { _trim($_) } split( /,/, $static_branch_list )
808           if $static_branch_list;
809     }
810
811     @branches_to_use =
812       Koha::Database->new()->schema()->resultset('Branch')
813       ->get_column('branchcode')->all()
814       unless (@branches_to_use);
815
816     @branches_to_use = shuffle(@branches_to_use)
817       if C4::Context->preference("RandomizeHoldsQueueWeight");
818
819     my $today = dt_from_string();
820     if ( C4::Context->preference('HoldsQueueSkipClosed') ) {
821         @branches_to_use = grep {
822             !Koha::Calendar->new( branchcode => $_ )
823               ->is_holiday( $today )
824         } @branches_to_use;
825     }
826
827     return \@branches_to_use;
828 }
829
830 sub least_cost_branch {
831
832     #$from - arrayref
833     my ($to, $from, $transport_cost_matrix) = @_;
834
835     # Nothing really spectacular: supply to branch, a list of potential from branches
836     # and find the minimum from - to value from the transport_cost_matrix
837     return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{$from->[0]}->{disable_transfer} != 1 );
838
839     # If the pickup library is in the list of libraries to pull from,
840     # return that library right away, it is obviously the least costly
841     return ($to) if any { $_ eq $to } @$from;
842
843     my ($least_cost, @branch);
844     foreach (@$from) {
845         my $cell = $transport_cost_matrix->{$to}{$_};
846         next if $cell->{disable_transfer};
847
848         my $cost = $cell->{cost};
849         next unless defined $cost; # XXX should this be reported?
850
851         unless (defined $least_cost) {
852             $least_cost = $cost;
853             push @branch, $_;
854             next;
855         }
856
857         next if $cost > $least_cost;
858
859         if ($cost == $least_cost) {
860             push @branch, $_;
861             next;
862         }
863
864         @branch = ($_);
865         $least_cost = $cost;
866     }
867
868     return $branch[0];
869
870     # XXX return a random @branch with minimum cost instead of the first one;
871     # return $branch[0] if @branch == 1;
872 }
873
874 =head3 update_queue_for_biblio
875
876     my $result = update_queue_for_biblio(
877         {
878             biblio_id             => $biblio_id,
879           [ branches_to_use       => $branches_to_use,
880             transport_cost_matrix => $transport_cost_matrix,
881             delete                => $delete, ]
882         }
883     );
884
885 Given a I<biblio_id>, this method calculates and sets the holds queue entries
886 for the biblio's holds, and the hold fill targets (items).
887
888 =head4 Return value
889
890 It return a hashref containing:
891
892 =over
893
894 =item I<requests>: the pending holds count for the biblio.
895
896 =item I<available_items> the count of items that are available to fill holds for the biblio.
897
898 =item I<mapped_items> the total items that got mapped.
899
900 =back
901
902 =head4 Optional parameters
903
904 =over
905
906 =item I<branches_to_use> a list of branchcodes to be used to restrict which items can be used.
907
908 =item I<transport_cost_matrix> is the output of C<TransportCostMatrix>.
909
910 =item I<delete> tells the method to delete prior entries on the related tables for the biblio_id.
911
912 =back
913
914 Note: All the optional parameters will be calculated in the method if omitted. They
915 are allowed to be passed to avoid calculating them many times inside loops.
916
917 =cut
918
919 sub update_queue_for_biblio {
920     my ($args) = @_;
921     my $biblio_id = $args->{biblio_id};
922     my $result;
923
924     # We need to empty the queue for this biblio unless CreateQueue has emptied the entire queue for rebuilding
925     if ( $args->{delete} ) {
926         my $dbh = C4::Context->dbh;
927
928         $dbh->do("DELETE FROM tmp_holdsqueue WHERE biblionumber=$biblio_id");
929         $dbh->do("DELETE FROM hold_fill_targets WHERE biblionumber=$biblio_id");
930     }
931
932     my $hold_requests   = GetPendingHoldRequestsForBib($biblio_id);
933     $result->{requests} = scalar( @{$hold_requests} );
934     # No need to check anything else if there are no holds to fill
935     return $result unless $result->{requests};
936
937     my $branches_to_use = $args->{branches_to_use} // load_branches_to_pull_from( C4::Context->preference('UseTransportCostMatrix') );
938     my $transport_cost_matrix;
939
940     if ( !exists $args->{transport_cost_matrix}
941         && C4::Context->preference('UseTransportCostMatrix') ) {
942         $transport_cost_matrix = TransportCostMatrix();
943     } else {
944         $transport_cost_matrix = $args->{transport_cost_matrix};
945     }
946
947     my $available_items = GetItemsAvailableToFillHoldRequestsForBib( $biblio_id, $branches_to_use );
948
949     $result->{available_items}  = scalar( @{$available_items} );
950
951     my $item_map = MapItemsToHoldRequests( $hold_requests, $available_items, $branches_to_use, $transport_cost_matrix );
952     $result->{mapped_items} = scalar( keys %{$item_map} );
953
954     if ($item_map) {
955         CreatePicklistFromItemMap($item_map);
956         AddToHoldTargetMap($item_map);
957     }
958
959     return $result;
960 }
961
962 1;