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