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