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