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