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