Bug 23104: (follow-up) fix display for 0/Unlimited
[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::Search;
27 use C4::Items;
28 use C4::Circulation;
29 use C4::Members;
30 use C4::Biblio;
31 use Koha::DateUtils;
32 use Koha::Items;
33 use Koha::Patrons;
34
35 use List::Util qw(shuffle);
36 use List::MoreUtils qw(any);
37 use Data::Dumper;
38
39 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
40 BEGIN {
41     require Exporter;
42     @ISA = qw(Exporter);
43     @EXPORT_OK = qw(
44         &CreateQueue
45         &GetHoldsQueueItems
46
47         &TransportCostMatrix
48         &UpdateTransportCostMatrix
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 $dbh   = C4::Context->dbh;
65     my $transport_costs = $dbh->selectall_arrayref("SELECT * FROM transport_cost",{ Slice => {} });
66
67     my $today = dt_from_string();
68     my $calendars;
69     my %transport_cost_matrix;
70     foreach (@$transport_costs) {
71         my $from     = $_->{frombranch};
72         my $to       = $_->{tobranch};
73         my $cost     = $_->{cost};
74         my $disabled = $_->{disable_transfer};
75         $transport_cost_matrix{$to}{$from} = {
76             cost             => $cost,
77             disable_transfer => $disabled
78         };
79
80         if ( C4::Context->preference("HoldsQueueSkipClosed") ) {
81             $calendars->{$from} ||= Koha::Calendar->new( branchcode => $from );
82             $transport_cost_matrix{$to}{$from}{disable_transfer} ||=
83               $calendars->{$from}->is_holiday( $today );
84         }
85
86     }
87     return \%transport_cost_matrix;
88 }
89
90 =head2 UpdateTransportCostMatrix
91
92   UpdateTransportCostMatrix($records);
93
94 Updates full Transport Cost Matrix table. $records is an arrayref of records.
95 Records: { frombranch => <code>, tobranch => <code>, cost => <figure>, disable_transfer => <0,1> }
96
97 =cut
98
99 sub UpdateTransportCostMatrix {
100     my ($records) = @_;
101     my $dbh   = C4::Context->dbh;
102
103     my $sth = $dbh->prepare("INSERT INTO transport_cost (frombranch, tobranch, cost, disable_transfer) VALUES (?, ?, ?, ?)");
104
105     $dbh->do("DELETE FROM transport_cost");
106     foreach (@$records) {
107         my $cost = $_->{cost};
108         my $from = $_->{frombranch};
109         my $to = $_->{tobranch};
110         if ($_->{disable_transfer}) {
111             $cost ||= 0;
112         }
113         elsif ( !defined ($cost) || ($cost !~ m/(0|[1-9][0-9]*)(\.[0-9]*)?/o) ) {
114             warn  "Invalid $from -> $to cost $cost - must be a number >= 0, disabling";
115             $cost = 0;
116             $_->{disable_transfer} = 1;
117         }
118         $sth->execute( $from, $to, $cost, $_->{disable_transfer} ? 1 : 0 );
119     }
120 }
121
122 =head2 GetHoldsQueueItems
123
124   GetHoldsQueueItems($branch);
125
126 Returns hold queue for a holding branch. If branch is omitted, then whole queue is returned
127
128 =cut
129
130 sub GetHoldsQueueItems {
131     my ($branchlimit) = @_;
132     my $dbh   = C4::Context->dbh;
133
134     my @bind_params = ();
135     my $query = q/SELECT tmp_holdsqueue.*, biblio.author, items.ccode, items.itype, biblioitems.itemtype, items.location, items.enumchron, items.cn_sort, biblioitems.publishercode,biblio.copyrightdate,biblioitems.publicationyear,biblioitems.pages,biblioitems.size,biblioitems.publicationyear,biblioitems.isbn,items.copynumber
136                   FROM tmp_holdsqueue
137                        JOIN biblio      USING (biblionumber)
138                   LEFT JOIN biblioitems USING (biblionumber)
139                   LEFT JOIN items       USING (  itemnumber)
140                 /;
141     if ($branchlimit) {
142         $query .=" WHERE tmp_holdsqueue.holdingbranch = ?";
143         push @bind_params, $branchlimit;
144     }
145     $query .= " ORDER BY ccode, location, cn_sort, author, title, pickbranch, reservedate";
146     my $sth = $dbh->prepare($query);
147     $sth->execute(@bind_params);
148     my $items = [];
149     while ( my $row = $sth->fetchrow_hashref ){
150         my $record = GetMarcBiblio({ biblionumber => $row->{biblionumber} });
151         if ($record){
152             $row->{subtitle} = [ map { $_->{subfield} } @{ GetRecordValue( 'subtitle', $record, '' ) } ];
153             $row->{parts} = GetRecordValue('parts',$record,'')->[0]->{subfield};
154             $row->{numbers} = GetRecordValue('numbers',$record,'')->[0]->{subfield};
155         }
156
157         # return the bib-level or item-level itype per syspref
158         if (!C4::Context->preference('item-level_itypes')) {
159             $row->{itype} = $row->{itemtype};
160         }
161         delete $row->{itemtype};
162
163         push @$items, $row;
164     }
165     return $items;
166 }
167
168 =head2 CreateQueue
169
170   CreateQueue();
171
172 Top level function that turns reserves into tmp_holdsqueue and hold_fill_targets.
173
174 =cut
175
176 sub CreateQueue {
177     my $dbh   = C4::Context->dbh;
178
179     $dbh->do("DELETE FROM tmp_holdsqueue");  # clear the old table for new info
180     $dbh->do("DELETE FROM hold_fill_targets");
181
182     my $total_bibs            = 0;
183     my $total_requests        = 0;
184     my $total_available_items = 0;
185     my $num_items_mapped      = 0;
186
187     my $branches_to_use;
188     my $transport_cost_matrix;
189     my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix");
190     if ($use_transport_cost_matrix) {
191         $transport_cost_matrix = TransportCostMatrix();
192         unless (keys %$transport_cost_matrix) {
193             warn "UseTransportCostMatrix set to yes, but matrix not populated";
194             undef $transport_cost_matrix;
195         }
196     }
197     unless ($transport_cost_matrix) {
198         $branches_to_use = load_branches_to_pull_from();
199     }
200
201     my $bibs_with_pending_requests = GetBibsWithPendingHoldRequests();
202
203     foreach my $biblionumber (@$bibs_with_pending_requests) {
204         $total_bibs++;
205         my $hold_requests   = GetPendingHoldRequestsForBib($biblionumber);
206         my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_to_use);
207         $total_requests        += scalar(@$hold_requests);
208         $total_available_items += scalar(@$available_items);
209
210         my $item_map = MapItemsToHoldRequests($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix);
211         $item_map  or next;
212         my $item_map_size = scalar(keys %$item_map)
213           or next;
214
215         $num_items_mapped += $item_map_size;
216         CreatePicklistFromItemMap($item_map);
217         AddToHoldTargetMap($item_map);
218         if (($item_map_size < scalar(@$hold_requests  )) and
219             ($item_map_size < scalar(@$available_items))) {
220             # DOUBLE CHECK, but this is probably OK - unfilled item-level requests
221             # FIXME
222             #warn "unfilled requests for $biblionumber";
223             #warn Dumper($hold_requests), Dumper($available_items), Dumper($item_map);
224         }
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, reserves.branchcode,
282                                 reservedate, reservenotes, borrowers.branchcode AS borrowerbranch, itemtype
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 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 .=   "WHERE items.notforloan = 0
331                        AND holdingbranch IS NOT NULL
332                        AND itemlost = 0
333                        AND withdrawn = 0";
334     $items_query .= "  AND damaged = 0" unless C4::Context->preference('AllowHoldsOnDamagedItems');
335     $items_query .= "  AND items.onloan IS NULL
336                        AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
337                        AND itemnumber NOT IN (
338                            SELECT itemnumber
339                            FROM reserves
340                            WHERE biblionumber = ?
341                            AND itemnumber IS NOT NULL
342                            AND (found IS NOT NULL OR priority = 0)
343                         )
344                        AND items.biblionumber = ?";
345
346     my @params = ($biblionumber, $biblionumber);
347     if ($branches_to_use && @$branches_to_use) {
348         $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
349         push @params, @$branches_to_use;
350     }
351     my $sth = $dbh->prepare($items_query);
352     $sth->execute(@params);
353
354     my $itm = $sth->fetchall_arrayref({});
355     my @items = grep { ! scalar GetTransfers($_->{itemnumber}) } @$itm;
356     return [ grep {
357         my $rule = GetBranchItemRule($_->{homebranch}, $_->{itype});
358         $_->{holdallowed} = $rule->{holdallowed};
359         $_->{hold_fulfillment_policy} = $rule->{hold_fulfillment_policy};
360     } @items ];
361 }
362
363 =head2 MapItemsToHoldRequests
364
365   MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
366
367 =cut
368
369 sub MapItemsToHoldRequests {
370     my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
371
372     # handle trival cases
373     return unless scalar(@$hold_requests) > 0;
374     return unless scalar(@$available_items) > 0;
375
376     # identify item-level requests
377     my %specific_items_requested = map { $_->{itemnumber} => 1 }
378                                    grep { defined($_->{itemnumber}) }
379                                    @$hold_requests;
380
381     map { $_->{_object} = Koha::Items->find( $_->{itemnumber} ) } @$available_items;
382     my $libraries = {};
383     map { $libraries->{$_->id} = $_ } Koha::Libraries->search();
384
385     # group available items by itemnumber
386     my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
387
388     # items already allocated
389     my %allocated_items = ();
390
391     # map of items to hold requests
392     my %item_map = ();
393
394     # figure out which item-level requests can be filled
395     my $num_items_remaining = scalar(@$available_items);
396
397     # Look for Local Holds Priority matches first
398     if ( C4::Context->preference('LocalHoldsPriority') ) {
399         my $LocalHoldsPriorityPatronControl =
400           C4::Context->preference('LocalHoldsPriorityPatronControl');
401         my $LocalHoldsPriorityItemControl =
402           C4::Context->preference('LocalHoldsPriorityItemControl');
403
404         foreach my $request (@$hold_requests) {
405             next if (defined($request->{itemnumber})); #skip item level holds in local priority checking
406             last if $num_items_remaining == 0;
407
408             my $local_hold_match;
409             foreach my $item (@$available_items) {
410                 next
411                   if ( !$item->{holdallowed} )
412                   || ( $item->{holdallowed} == 1
413                     && $item->{homebranch} ne $request->{borrowerbranch} );
414
415                 next unless $item->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
416
417                 my $local_holds_priority_item_branchcode =
418                   $item->{$LocalHoldsPriorityItemControl};
419
420                 my $local_holds_priority_patron_branchcode =
421                   ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
422                   ? $request->{branchcode}
423                   : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
424                   ? $request->{borrowerbranch}
425                   : undef;
426
427                 $local_hold_match =
428                   $local_holds_priority_item_branchcode eq
429                   $local_holds_priority_patron_branchcode;
430
431                 if ($local_hold_match) {
432                     if ( exists $items_by_itemnumber{ $item->{itemnumber} }
433                         and not exists $allocated_items{ $item->{itemnumber} }
434                         and not $request->{allocated})
435                     {
436                         $item_map{ $item->{itemnumber} } = {
437                             borrowernumber => $request->{borrowernumber},
438                             biblionumber   => $request->{biblionumber},
439                             holdingbranch  => $item->{holdingbranch},
440                             pickup_branch  => $request->{branchcode}
441                               || $request->{borrowerbranch},
442                             item_level   => 0,
443                             reservedate  => $request->{reservedate},
444                             reservenotes => $request->{reservenotes},
445                         };
446                         $allocated_items{ $item->{itemnumber} }++;
447                         $request->{allocated} = 1;
448                         $num_items_remaining--;
449                     }
450                 }
451             }
452         }
453     }
454
455     foreach my $request (@$hold_requests) {
456         last if $num_items_remaining == 0;
457         next if $request->{allocated};
458
459         # is this an item-level request?
460         if (defined($request->{itemnumber})) {
461             # fill it if possible; if not skip it
462             if (
463                     exists $items_by_itemnumber{ $request->{itemnumber} }
464                 and not exists $allocated_items{ $request->{itemnumber} }
465                 and ( # Don't fill item level holds that contravene the hold pickup policy at this time
466                     ( $items_by_itemnumber{ $request->{itemnumber} }->{hold_fulfillment_policy} eq 'any' )
467                     || ( $request->{branchcode} eq $items_by_itemnumber{ $request->{itemnumber} }->{ $items_by_itemnumber{ $request->{itemnumber} }->{hold_fulfillment_policy} }  )
468                 and ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
469                     || $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} )
470                 )
471                 and $items_by_itemnumber{ $request->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } )
472
473               )
474             {
475
476                 $item_map{ $request->{itemnumber} } = {
477                     borrowernumber => $request->{borrowernumber},
478                     biblionumber   => $request->{biblionumber},
479                     holdingbranch  => $items_by_itemnumber{ $request->{itemnumber} }->{holdingbranch},
480                     pickup_branch  => $request->{branchcode} || $request->{borrowerbranch},
481                     item_level     => 1,
482                     reservedate    => $request->{reservedate},
483                     reservenotes   => $request->{reservenotes},
484                 };
485                 $allocated_items{ $request->{itemnumber} }++;
486                 $num_items_remaining--;
487             }
488         } else {
489             # it's title-level request that will take up one item
490             $num_items_remaining--;
491         }
492     }
493
494     # group available items by branch
495     my %items_by_branch = ();
496     foreach my $item (@$available_items) {
497         next unless $item->{holdallowed};
498
499         push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
500           unless exists $allocated_items{ $item->{itemnumber} };
501     }
502     return \%item_map unless keys %items_by_branch;
503
504     # now handle the title-level requests
505     $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
506     my $pull_branches;
507     foreach my $request (@$hold_requests) {
508         last if $num_items_remaining == 0;
509         next if $request->{allocated};
510         next if defined($request->{itemnumber}); # already handled these
511
512         # look for local match first
513         my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
514         my ($itemnumber, $holdingbranch);
515
516         my $holding_branch_items = $items_by_branch{$pickup_branch};
517         if ( $holding_branch_items ) {
518             foreach my $item (@$holding_branch_items) {
519                 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
520
521                 if (
522                     $request->{borrowerbranch} eq $item->{homebranch}
523                     && ( ( $item->{hold_fulfillment_policy} eq 'any' ) # Don't fill item level holds that contravene the hold pickup policy at this time
524                         || $request->{branchcode} eq $item->{ $item->{hold_fulfillment_policy} } )
525                     && ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
526                         || $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} )
527                   )
528                 {
529                     $itemnumber = $item->{itemnumber};
530                     last;
531                 }
532             }
533             $holdingbranch = $pickup_branch;
534         }
535         elsif ($transport_cost_matrix) {
536             $pull_branches = [keys %items_by_branch];
537             $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
538             if ( $holdingbranch ) {
539
540                 my $holding_branch_items = $items_by_branch{$holdingbranch};
541                 foreach my $item (@$holding_branch_items) {
542                     next if $request->{borrowerbranch} ne $item->{homebranch};
543                     next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
544
545                     # Don't fill item level holds that contravene the hold pickup policy at this time
546                     next unless $item->{hold_fulfillment_policy} eq 'any'
547                         || $request->{branchcode} eq $item->{ $item->{hold_fulfillment_policy} };
548
549                     # If hold itemtype is set, item's itemtype must match
550                     next unless ( !$request->{itemtype}
551                         || $item->{itype} eq $request->{itemtype} );
552
553                     $itemnumber = $item->{itemnumber};
554                     last;
555                 }
556             }
557             else {
558                 next;
559             }
560         }
561
562         unless ($itemnumber) {
563             # not found yet, fall back to basics
564             if ($branches_to_use) {
565                 $pull_branches = $branches_to_use;
566             } else {
567                 $pull_branches = [keys %items_by_branch];
568             }
569
570             # Try picking items where the home and pickup branch match first
571             PULL_BRANCHES:
572             foreach my $branch (@$pull_branches) {
573                 my $holding_branch_items = $items_by_branch{$branch}
574                   or next;
575
576                 $holdingbranch ||= $branch;
577                 foreach my $item (@$holding_branch_items) {
578                     next if $pickup_branch ne $item->{homebranch};
579                     next if ( $item->{holdallowed} == 1 && $item->{homebranch} ne $request->{borrowerbranch} );
580                     next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
581
582                     # Don't fill item level holds that contravene the hold pickup policy at this time
583                     next unless $item->{hold_fulfillment_policy} eq 'any'
584                         || $request->{branchcode} eq $item->{ $item->{hold_fulfillment_policy} };
585
586                     # If hold itemtype is set, item's itemtype must match
587                     next unless ( !$request->{itemtype}
588                         || $item->{itype} eq $request->{itemtype} );
589
590                     $itemnumber = $item->{itemnumber};
591                     $holdingbranch = $branch;
592                     last PULL_BRANCHES;
593                 }
594             }
595
596             # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight
597             unless ( $itemnumber ) {
598                 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
599                     if ( $holdingbranch && ( $current_item->{holdallowed} == 2 || $request->{borrowerbranch} eq $current_item->{homebranch} ) ) {
600
601                         # Don't fill item level holds that contravene the hold pickup policy at this time
602                         next unless $current_item->{hold_fulfillment_policy} eq 'any'
603                             || $request->{branchcode} eq $current_item->{ $current_item->{hold_fulfillment_policy} };
604
605                         # If hold itemtype is set, item's itemtype must match
606                         next unless ( !$request->{itemtype}
607                             || $current_item->{itype} eq $request->{itemtype} );
608
609                         next unless $items_by_itemnumber{ $current_item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
610
611                         $itemnumber = $current_item->{itemnumber};
612                         last; # quit this loop as soon as we have a suitable item
613                     }
614                 }
615             }
616
617             # Now try for items for any item that can fill this hold
618             unless ( $itemnumber ) {
619                 PULL_BRANCHES2:
620                 foreach my $branch (@$pull_branches) {
621                     my $holding_branch_items = $items_by_branch{$branch}
622                       or next;
623
624                     foreach my $item (@$holding_branch_items) {
625                         next if ( $item->{holdallowed} == 1 && $item->{homebranch} ne $request->{borrowerbranch} );
626
627                         # Don't fill item level holds that contravene the hold pickup policy at this time
628                         next unless $item->{hold_fulfillment_policy} eq 'any'
629                             || $request->{branchcode} eq $item->{ $item->{hold_fulfillment_policy} };
630
631                         # If hold itemtype is set, item's itemtype must match
632                         next unless ( !$request->{itemtype}
633                             || $item->{itype} eq $request->{itemtype} );
634
635                         next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
636
637                         $itemnumber = $item->{itemnumber};
638                         $holdingbranch = $branch;
639                         last PULL_BRANCHES2;
640                     }
641                 }
642             }
643         }
644
645         if ($itemnumber) {
646             my $holding_branch_items = $items_by_branch{$holdingbranch}
647               or die "Have $itemnumber, $holdingbranch, but no items!";
648             @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
649             delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
650
651             $item_map{$itemnumber} = {
652                 borrowernumber => $request->{borrowernumber},
653                 biblionumber => $request->{biblionumber},
654                 holdingbranch => $holdingbranch,
655                 pickup_branch => $pickup_branch,
656                 item_level => 0,
657                 reservedate => $request->{reservedate},
658                 reservenotes => $request->{reservenotes},
659             };
660             $num_items_remaining--;
661         }
662     }
663     return \%item_map;
664 }
665
666 =head2 CreatePickListFromItemMap
667
668 =cut
669
670 sub CreatePicklistFromItemMap {
671     my $item_map = shift;
672
673     my $dbh = C4::Context->dbh;
674
675     my $sth_load=$dbh->prepare("
676         INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
677                                     cardnumber,reservedate,title, itemcallnumber,
678                                     holdingbranch,pickbranch,notes, item_level_request)
679         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
680     ");
681
682     foreach my $itemnumber  (sort keys %$item_map) {
683         my $mapped_item = $item_map->{$itemnumber};
684         my $biblionumber = $mapped_item->{biblionumber};
685         my $borrowernumber = $mapped_item->{borrowernumber};
686         my $pickbranch = $mapped_item->{pickup_branch};
687         my $holdingbranch = $mapped_item->{holdingbranch};
688         my $reservedate = $mapped_item->{reservedate};
689         my $reservenotes = $mapped_item->{reservenotes};
690         my $item_level = $mapped_item->{item_level};
691
692         my $item = Koha::Items->find($itemnumber);
693         my $barcode = $item->barcode;
694         my $itemcallnumber = $item->itemcallnumber;
695
696         my $patron = Koha::Patrons->find( $borrowernumber );
697         my $cardnumber = $patron->cardnumber;
698         my $surname = $patron->surname;
699         my $firstname = $patron->firstname;
700         my $phone = $patron->phone;
701
702         my $biblio = Koha::Biblios->find( $biblionumber );
703         my $title = $biblio->title;
704
705         $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
706                            $cardnumber, $reservedate, $title, $itemcallnumber,
707                            $holdingbranch, $pickbranch, $reservenotes, $item_level);
708     }
709 }
710
711 =head2 AddToHoldTargetMap
712
713 =cut
714
715 sub AddToHoldTargetMap {
716     my $item_map = shift;
717
718     my $dbh = C4::Context->dbh;
719
720     my $insert_sql = q(
721         INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request)
722                                VALUES (?, ?, ?, ?, ?)
723     );
724     my $sth_insert = $dbh->prepare($insert_sql);
725
726     foreach my $itemnumber (keys %$item_map) {
727         my $mapped_item = $item_map->{$itemnumber};
728         $sth_insert->execute($mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
729                              $mapped_item->{holdingbranch}, $mapped_item->{item_level});
730     }
731 }
732
733 # Helper functions, not part of any interface
734
735 sub _trim {
736     return $_[0] unless $_[0];
737     $_[0] =~ s/^\s+//;
738     $_[0] =~ s/\s+$//;
739     $_[0];
740 }
741
742 sub load_branches_to_pull_from {
743     my @branches_to_use;
744
745     my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight");
746     @branches_to_use = map { _trim($_) } split( /,/, $static_branch_list )
747       if $static_branch_list;
748
749     @branches_to_use =
750       Koha::Database->new()->schema()->resultset('Branch')
751       ->get_column('branchcode')->all()
752       unless (@branches_to_use);
753
754     @branches_to_use = shuffle(@branches_to_use)
755       if C4::Context->preference("RandomizeHoldsQueueWeight");
756
757     my $today = dt_from_string();
758     if ( C4::Context->preference('HoldsQueueSkipClosed') ) {
759         @branches_to_use = grep {
760             !Koha::Calendar->new( branchcode => $_ )
761               ->is_holiday( $today )
762         } @branches_to_use;
763     }
764
765     return \@branches_to_use;
766 }
767
768 sub least_cost_branch {
769
770     #$from - arrayref
771     my ($to, $from, $transport_cost_matrix) = @_;
772
773     # Nothing really spectacular: supply to branch, a list of potential from branches
774     # and find the minimum from - to value from the transport_cost_matrix
775     return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{$from->[0]}->{disable_transfer} != 1 );
776
777     # If the pickup library is in the list of libraries to pull from,
778     # return that library right away, it is obviously the least costly
779     return ($to) if any { $_ eq $to } @$from;
780
781     my ($least_cost, @branch);
782     foreach (@$from) {
783         my $cell = $transport_cost_matrix->{$to}{$_};
784         next if $cell->{disable_transfer};
785
786         my $cost = $cell->{cost};
787         next unless defined $cost; # XXX should this be reported?
788
789         unless (defined $least_cost) {
790             $least_cost = $cost;
791             push @branch, $_;
792             next;
793         }
794
795         next if $cost > $least_cost;
796
797         if ($cost == $least_cost) {
798             push @branch, $_;
799             next;
800         }
801
802         @branch = ($_);
803         $least_cost = $cost;
804     }
805
806     return $branch[0];
807
808     # XXX return a random @branch with minimum cost instead of the first one;
809     # return $branch[0] if @branch == 1;
810 }
811
812
813 1;