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