]> git.koha-community.org Git - koha.git/blob - C4/HoldsQueue.pm
Bug 28510: Skip processing holds queue items from closed libraries when HoldsQueueSki...
[koha.git] / C4 / HoldsQueue.pm
1 package C4::HoldsQueue;
2
3 # Copyright 2011 Catalyst IT
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 # FIXME: expand perldoc, explain intended logic
21
22 use strict;
23 use warnings;
24
25 use C4::Context;
26 use C4::Search;
27 use C4::Items;
28 use C4::Circulation;
29 use C4::Members;
30 use C4::Biblio;
31 use Koha::DateUtils;
32 use Koha::Items;
33 use Koha::Patrons;
34 use Koha::Libraries;
35
36 use List::Util qw(shuffle);
37 use List::MoreUtils qw(any);
38 use Data::Dumper;
39
40 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
41 BEGIN {
42     require Exporter;
43     @ISA = qw(Exporter);
44     @EXPORT_OK = qw(
45         &CreateQueue
46         &GetHoldsQueueItems
47
48         &TransportCostMatrix
49         &UpdateTransportCostMatrix
50      );
51 }
52
53
54 =head1 FUNCTIONS
55
56 =head2 TransportCostMatrix
57
58   TransportCostMatrix();
59
60 Returns Transport Cost Matrix as a hashref <to branch code> => <from branch code> => cost
61
62 =cut
63
64 sub TransportCostMatrix {
65     my ( $params ) = @_;
66     my $ignore_holds_queue_skip_closed = $params->{ignore_holds_queue_skip_closed};
67
68     my $dbh   = C4::Context->dbh;
69     my $transport_costs = $dbh->selectall_arrayref("SELECT * FROM transport_cost",{ Slice => {} });
70
71     my $today = dt_from_string();
72     my $calendars;
73     my %transport_cost_matrix;
74     foreach (@$transport_costs) {
75         my $from     = $_->{frombranch};
76         my $to       = $_->{tobranch};
77         my $cost     = $_->{cost};
78         my $disabled = $_->{disable_transfer};
79         $transport_cost_matrix{$to}{$from} = {
80             cost             => $cost,
81             disable_transfer => $disabled
82         };
83
84         if ( !$ignore_holds_queue_skip_closed && C4::Context->preference("HoldsQueueSkipClosed") ) {
85             $calendars->{$from} ||= Koha::Calendar->new( branchcode => $from );
86             $transport_cost_matrix{$to}{$from}{disable_transfer} ||=
87               $calendars->{$from}->is_holiday( $today );
88         }
89
90     }
91     return \%transport_cost_matrix;
92 }
93
94 =head2 UpdateTransportCostMatrix
95
96   UpdateTransportCostMatrix($records);
97
98 Updates full Transport Cost Matrix table. $records is an arrayref of records.
99 Records: { frombranch => <code>, tobranch => <code>, cost => <figure>, disable_transfer => <0,1> }
100
101 =cut
102
103 sub UpdateTransportCostMatrix {
104     my ($records) = @_;
105     my $dbh   = C4::Context->dbh;
106
107     my $sth = $dbh->prepare("INSERT INTO transport_cost (frombranch, tobranch, cost, disable_transfer) VALUES (?, ?, ?, ?)");
108
109     $dbh->do("DELETE FROM transport_cost");
110     foreach (@$records) {
111         my $cost = $_->{cost};
112         my $from = $_->{frombranch};
113         my $to = $_->{tobranch};
114         if ($_->{disable_transfer}) {
115             $cost ||= 0;
116         }
117         elsif ( !defined ($cost) || ($cost !~ m/(0|[1-9][0-9]*)(\.[0-9]*)?/o) ) {
118             warn  "Invalid $from -> $to cost $cost - must be a number >= 0, disabling";
119             $cost = 0;
120             $_->{disable_transfer} = 1;
121         }
122         $sth->execute( $from, $to, $cost, $_->{disable_transfer} ? 1 : 0 );
123     }
124 }
125
126 =head2 GetHoldsQueueItems
127
128   GetHoldsQueueItems($branch);
129
130 Returns hold queue for a holding branch. If branch is omitted, then whole queue is returned
131
132 =cut
133
134 sub GetHoldsQueueItems {
135     my ($branchlimit) = @_;
136     my $dbh   = C4::Context->dbh;
137
138     my @bind_params = ();
139     my $query = q/SELECT tmp_holdsqueue.*, biblio.author, items.ccode, items.itype, biblioitems.itemtype, items.location,
140                          items.enumchron, items.cn_sort, biblioitems.publishercode,
141                          biblio.copyrightdate, biblio.subtitle, biblio.medium,
142                          biblio.part_number, biblio.part_name,
143                          biblioitems.publicationyear, biblioitems.pages, biblioitems.size,
144                          biblioitems.isbn, biblioitems.editionstatement, items.copynumber
145                   FROM tmp_holdsqueue
146                        JOIN biblio      USING (biblionumber)
147                   LEFT JOIN biblioitems USING (biblionumber)
148                   LEFT JOIN items       USING (  itemnumber)
149                 /;
150     if ($branchlimit) {
151         $query .=" WHERE tmp_holdsqueue.holdingbranch = ?";
152         push @bind_params, $branchlimit;
153     }
154     $query .= " ORDER BY ccode, location, cn_sort, author, title, pickbranch, reservedate";
155     my $sth = $dbh->prepare($query);
156     $sth->execute(@bind_params);
157     my $items = [];
158     while ( my $row = $sth->fetchrow_hashref ){
159         # return the bib-level or item-level itype per syspref
160         if (!C4::Context->preference('item-level_itypes')) {
161             $row->{itype} = $row->{itemtype};
162         }
163         delete $row->{itemtype};
164
165         push @$items, $row;
166     }
167     return $items;
168 }
169
170 =head2 CreateQueue
171
172   CreateQueue();
173
174 Top level function that turns reserves into tmp_holdsqueue and hold_fill_targets.
175
176 =cut
177
178 sub CreateQueue {
179     my $dbh   = C4::Context->dbh;
180
181     $dbh->do("DELETE FROM tmp_holdsqueue");  # clear the old table for new info
182     $dbh->do("DELETE FROM hold_fill_targets");
183
184     my $total_bibs            = 0;
185     my $total_requests        = 0;
186     my $total_available_items = 0;
187     my $num_items_mapped      = 0;
188
189     my $branches_to_use;
190     my $transport_cost_matrix;
191     my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix");
192     if ($use_transport_cost_matrix) {
193         $transport_cost_matrix = TransportCostMatrix();
194         unless (keys %$transport_cost_matrix) {
195             warn "UseTransportCostMatrix set to yes, but matrix not populated";
196             undef $transport_cost_matrix;
197         }
198     }
199
200     $branches_to_use = load_branches_to_pull_from($use_transport_cost_matrix);
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 _checkHoldPolicy
365
366     _checkHoldPolicy($item, $request)
367
368     check if item agrees with hold policies
369
370 =cut
371
372 sub _checkHoldPolicy {
373     my ( $item, $request ) = @_;
374
375     return 0 unless $item->{holdallowed};
376
377     return 0
378       if $item->{holdallowed} == 1
379       && $item->{homebranch} ne $request->{borrowerbranch};
380
381     return 0
382       if $item->{'holdallowed'} == 3
383       && !Koha::Libraries->find( $item->{homebranch} )
384               ->validate_hold_sibling( { branchcode => $request->{borrowerbranch} } );
385
386     my $hold_fulfillment_policy = $item->{hold_fulfillment_policy};
387
388     return 0
389       if $hold_fulfillment_policy eq 'holdgroup'
390       && !Koha::Libraries->find( $item->{homebranch} )
391             ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
392
393     return 0
394       if $hold_fulfillment_policy eq 'homebranch'
395       && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
396
397     return 0
398       if $hold_fulfillment_policy eq 'holdingbranch'
399       && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
400
401     return 0
402       if $hold_fulfillment_policy eq 'patrongroup'
403       && !Koha::Libraries->find( $request->{borrowerbranch} )
404               ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
405
406     return 1;
407
408 }
409
410 =head2 MapItemsToHoldRequests
411
412   MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
413
414 =cut
415
416 sub MapItemsToHoldRequests {
417     my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
418
419     # handle trival cases
420     return unless scalar(@$hold_requests) > 0;
421     return unless scalar(@$available_items) > 0;
422
423     # identify item-level requests
424     my %specific_items_requested = map { $_->{itemnumber} => 1 }
425                                    grep { defined($_->{itemnumber}) }
426                                    @$hold_requests;
427
428     map { $_->{_object} = Koha::Items->find( $_->{itemnumber} ) } @$available_items;
429     my $libraries = {};
430     map { $libraries->{$_->id} = $_ } Koha::Libraries->search();
431
432     # group available items by itemnumber
433     my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
434
435     # items already allocated
436     my %allocated_items = ();
437
438     # map of items to hold requests
439     my %item_map = ();
440
441     # figure out which item-level requests can be filled
442     my $num_items_remaining = scalar(@$available_items);
443
444     # Look for Local Holds Priority matches first
445     if ( C4::Context->preference('LocalHoldsPriority') ) {
446         my $LocalHoldsPriorityPatronControl =
447           C4::Context->preference('LocalHoldsPriorityPatronControl');
448         my $LocalHoldsPriorityItemControl =
449           C4::Context->preference('LocalHoldsPriorityItemControl');
450
451         foreach my $request (@$hold_requests) {
452             last if $num_items_remaining == 0;
453             my $patron = Koha::Patrons->find($request->{borrowernumber});
454             next if $patron->category->exclude_from_local_holds_priority;
455
456             my $local_hold_match;
457             foreach my $item (@$available_items) {
458                 next if $item->{_object}->exclude_from_local_holds_priority;
459
460                 next unless _checkHoldPolicy($item, $request);
461
462                 next if $request->{itemnumber} && $request->{itemnumber} != $item->{itemnumber};
463
464                 next unless $item->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
465
466                 my $local_holds_priority_item_branchcode =
467                   $item->{$LocalHoldsPriorityItemControl};
468
469                 my $local_holds_priority_patron_branchcode =
470                   ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
471                   ? $request->{branchcode}
472                   : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
473                   ? $request->{borrowerbranch}
474                   : undef;
475
476                 $local_hold_match =
477                   $local_holds_priority_item_branchcode eq
478                   $local_holds_priority_patron_branchcode;
479
480                 if ($local_hold_match) {
481                     if ( exists $items_by_itemnumber{ $item->{itemnumber} }
482                         and not exists $allocated_items{ $item->{itemnumber} }
483                         and not $request->{allocated})
484                     {
485                         $item_map{ $item->{itemnumber} } = {
486                             borrowernumber => $request->{borrowernumber},
487                             biblionumber   => $request->{biblionumber},
488                             holdingbranch  => $item->{holdingbranch},
489                             pickup_branch  => $request->{branchcode}
490                               || $request->{borrowerbranch},
491                             reserve_id   => $request->{reserve_id},
492                             item_level   => $request->{item_level_hold},
493                             reservedate  => $request->{reservedate},
494                             reservenotes => $request->{reservenotes},
495                         };
496                         $allocated_items{ $item->{itemnumber} }++;
497                         $request->{allocated} = 1;
498                         $num_items_remaining--;
499                     }
500                 }
501             }
502         }
503     }
504
505     foreach my $request (@$hold_requests) {
506         last if $num_items_remaining == 0;
507         next if $request->{allocated};
508
509         # is this an item-level request?
510         if (defined($request->{itemnumber})) {
511             # fill it if possible; if not skip it
512             if (
513                     exists $items_by_itemnumber{ $request->{itemnumber} }
514                 and not exists $allocated_items{ $request->{itemnumber} }
515                 and  _checkHoldPolicy($items_by_itemnumber{ $request->{itemnumber} }, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
516                 and ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
517                     || $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} )
518
519                 and $items_by_itemnumber{ $request->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } )
520
521               )
522             {
523
524                 $item_map{ $request->{itemnumber} } = {
525                     borrowernumber => $request->{borrowernumber},
526                     biblionumber   => $request->{biblionumber},
527                     holdingbranch  => $items_by_itemnumber{ $request->{itemnumber} }->{holdingbranch},
528                     pickup_branch  => $request->{branchcode} || $request->{borrowerbranch},
529                     reserve_id     => $request->{reserve_id},
530                     item_level     => $request->{item_level_hold},
531                     reservedate    => $request->{reservedate},
532                     reservenotes   => $request->{reservenotes},
533                 };
534                 $allocated_items{ $request->{itemnumber} }++;
535                 $num_items_remaining--;
536             }
537         } else {
538             # it's title-level request that will take up one item
539             $num_items_remaining--;
540         }
541     }
542
543     # group available items by branch
544     my %items_by_branch = ();
545     foreach my $item (@$available_items) {
546         next unless $item->{holdallowed};
547
548         push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
549           unless exists $allocated_items{ $item->{itemnumber} };
550     }
551     return \%item_map unless keys %items_by_branch;
552
553     # now handle the title-level requests
554     $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
555     my $pull_branches;
556     foreach my $request (@$hold_requests) {
557         last if $num_items_remaining == 0;
558         next if $request->{allocated};
559         next if defined($request->{itemnumber}); # already handled these
560
561         # look for local match first
562         my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
563         my ($itemnumber, $holdingbranch);
564
565         my $holding_branch_items = $items_by_branch{$pickup_branch};
566         if ( $holding_branch_items ) {
567             foreach my $item (@$holding_branch_items) {
568                 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
569
570                 if (
571                     $request->{borrowerbranch} eq $item->{homebranch}
572                     && _checkHoldPolicy($item, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
573                     && ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
574                         || ( $request->{itemnumber} && ( $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} ) ) )
575                   )
576                 {
577                     $itemnumber = $item->{itemnumber};
578                     last;
579                 }
580             }
581             $holdingbranch = $pickup_branch;
582         }
583         elsif ($transport_cost_matrix) {
584             $pull_branches = [keys %items_by_branch];
585             $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
586             if ( $holdingbranch ) {
587
588                 my $holding_branch_items = $items_by_branch{$holdingbranch};
589                 foreach my $item (@$holding_branch_items) {
590                     next if $request->{borrowerbranch} ne $item->{homebranch};
591                     next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
592
593                     # Don't fill item level holds that contravene the hold pickup policy at this time
594                     next unless _checkHoldPolicy($item, $request);
595
596                     # If hold itemtype is set, item's itemtype must match
597                     next unless ( !$request->{itemtype}
598                         || $item->{itype} eq $request->{itemtype} );
599
600                     $itemnumber = $item->{itemnumber};
601                     last;
602                 }
603             }
604             else {
605                 next;
606             }
607         }
608
609         unless ($itemnumber) {
610             # not found yet, fall back to basics
611             if ($branches_to_use) {
612                 $pull_branches = $branches_to_use;
613             } else {
614                 $pull_branches = [keys %items_by_branch];
615             }
616
617             # Try picking items where the home and pickup branch match first
618             PULL_BRANCHES:
619             foreach my $branch (@$pull_branches) {
620                 my $holding_branch_items = $items_by_branch{$branch}
621                   or next;
622
623                 $holdingbranch ||= $branch;
624                 foreach my $item (@$holding_branch_items) {
625                     next if $pickup_branch ne $item->{homebranch};
626                     next unless _checkHoldPolicy($item, $request);
627                     next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
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                     $itemnumber = $item->{itemnumber};
638                     $holdingbranch = $branch;
639                     last PULL_BRANCHES;
640                 }
641             }
642
643             # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight
644             unless ( $itemnumber || !$holdingbranch) {
645                 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
646                     next unless _checkHoldPolicy($current_item, $request); # Don't fill item level holds that contravene the hold pickup policy at this time
647
648                     # If hold itemtype is set, item's itemtype must match
649                     next unless ( !$request->{itemtype}
650                         || $current_item->{itype} eq $request->{itemtype} );
651
652                     next unless $items_by_itemnumber{ $current_item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
653
654                     $itemnumber = $current_item->{itemnumber};
655                     last; # quit this loop as soon as we have a suitable item
656                 }
657             }
658
659             # Now try for items for any item that can fill this hold
660             unless ( $itemnumber ) {
661                 PULL_BRANCHES2:
662                 foreach my $branch (@$pull_branches) {
663                     my $holding_branch_items = $items_by_branch{$branch}
664                       or next;
665
666                     foreach my $item (@$holding_branch_items) {
667                         # Don't fill item level holds that contravene the hold pickup policy at this time
668                         next unless _checkHoldPolicy($item, $request);
669
670                         # If hold itemtype is set, item's itemtype must match
671                         next unless ( !$request->{itemtype}
672                             || $item->{itype} eq $request->{itemtype} );
673
674                         next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
675
676                         $itemnumber = $item->{itemnumber};
677                         $holdingbranch = $branch;
678                         last PULL_BRANCHES2;
679                     }
680                 }
681             }
682         }
683
684         if ($itemnumber) {
685             my $holding_branch_items = $items_by_branch{$holdingbranch}
686               or die "Have $itemnumber, $holdingbranch, but no items!";
687             @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
688             delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
689
690             $item_map{$itemnumber} = {
691                 borrowernumber => $request->{borrowernumber},
692                 biblionumber => $request->{biblionumber},
693                 holdingbranch => $holdingbranch,
694                 pickup_branch => $pickup_branch,
695                 reserve_id => $request->{reserve_id},
696                 item_level => $request->{item_level_hold},
697                 reservedate => $request->{reservedate},
698                 reservenotes => $request->{reservenotes},
699             };
700             $num_items_remaining--;
701         }
702     }
703     return \%item_map;
704 }
705
706 =head2 CreatePickListFromItemMap
707
708 =cut
709
710 sub CreatePicklistFromItemMap {
711     my $item_map = shift;
712
713     my $dbh = C4::Context->dbh;
714
715     my $sth_load=$dbh->prepare("
716         INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
717                                     cardnumber,reservedate,title, itemcallnumber,
718                                     holdingbranch,pickbranch,notes, item_level_request)
719         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
720     ");
721
722     foreach my $itemnumber  (sort keys %$item_map) {
723         my $mapped_item = $item_map->{$itemnumber};
724         my $biblionumber = $mapped_item->{biblionumber};
725         my $borrowernumber = $mapped_item->{borrowernumber};
726         my $pickbranch = $mapped_item->{pickup_branch};
727         my $holdingbranch = $mapped_item->{holdingbranch};
728         my $reservedate = $mapped_item->{reservedate};
729         my $reservenotes = $mapped_item->{reservenotes};
730         my $item_level = $mapped_item->{item_level};
731
732         my $item = Koha::Items->find($itemnumber);
733         my $barcode = $item->barcode;
734         my $itemcallnumber = $item->itemcallnumber;
735
736         my $patron = Koha::Patrons->find( $borrowernumber );
737         my $cardnumber = $patron->cardnumber;
738         my $surname = $patron->surname;
739         my $firstname = $patron->firstname;
740         my $phone = $patron->phone;
741
742         my $biblio = Koha::Biblios->find( $biblionumber );
743         my $title = $biblio->title;
744
745         $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
746                            $cardnumber, $reservedate, $title, $itemcallnumber,
747                            $holdingbranch, $pickbranch, $reservenotes, $item_level);
748     }
749 }
750
751 =head2 AddToHoldTargetMap
752
753 =cut
754
755 sub AddToHoldTargetMap {
756     my $item_map = shift;
757
758     my $dbh = C4::Context->dbh;
759
760     my $insert_sql = q(
761         INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request, reserve_id)
762                                VALUES (?, ?, ?, ?, ?, ?)
763     );
764     my $sth_insert = $dbh->prepare($insert_sql);
765
766     foreach my $itemnumber (keys %$item_map) {
767         my $mapped_item = $item_map->{$itemnumber};
768         $sth_insert->execute($mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
769                              $mapped_item->{holdingbranch}, $mapped_item->{item_level}, $mapped_item->{reserve_id});
770     }
771 }
772
773 # Helper functions, not part of any interface
774
775 sub _trim {
776     return $_[0] unless $_[0];
777     $_[0] =~ s/^\s+//;
778     $_[0] =~ s/\s+$//;
779     $_[0];
780 }
781
782 sub load_branches_to_pull_from {
783     my $use_transport_cost_matrix = shift;
784
785     my @branches_to_use;
786
787     unless ( $use_transport_cost_matrix ) {
788         my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight");
789         @branches_to_use = map { _trim($_) } split( /,/, $static_branch_list )
790           if $static_branch_list;
791     }
792
793     @branches_to_use =
794       Koha::Database->new()->schema()->resultset('Branch')
795       ->get_column('branchcode')->all()
796       unless (@branches_to_use);
797
798     @branches_to_use = shuffle(@branches_to_use)
799       if C4::Context->preference("RandomizeHoldsQueueWeight");
800
801     my $today = dt_from_string();
802     if ( C4::Context->preference('HoldsQueueSkipClosed') ) {
803         @branches_to_use = grep {
804             !Koha::Calendar->new( branchcode => $_ )
805               ->is_holiday( $today )
806         } @branches_to_use;
807     }
808
809     return \@branches_to_use;
810 }
811
812 sub least_cost_branch {
813
814     #$from - arrayref
815     my ($to, $from, $transport_cost_matrix) = @_;
816
817     # Nothing really spectacular: supply to branch, a list of potential from branches
818     # and find the minimum from - to value from the transport_cost_matrix
819     return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{$from->[0]}->{disable_transfer} != 1 );
820
821     # If the pickup library is in the list of libraries to pull from,
822     # return that library right away, it is obviously the least costly
823     return ($to) if any { $_ eq $to } @$from;
824
825     my ($least_cost, @branch);
826     foreach (@$from) {
827         my $cell = $transport_cost_matrix->{$to}{$_};
828         next if $cell->{disable_transfer};
829
830         my $cost = $cell->{cost};
831         next unless defined $cost; # XXX should this be reported?
832
833         unless (defined $least_cost) {
834             $least_cost = $cost;
835             push @branch, $_;
836             next;
837         }
838
839         next if $cost > $least_cost;
840
841         if ($cost == $least_cost) {
842             push @branch, $_;
843             next;
844         }
845
846         @branch = ($_);
847         $least_cost = $cost;
848     }
849
850     return $branch[0];
851
852     # XXX return a random @branch with minimum cost instead of the first one;
853     # return $branch[0] if @branch == 1;
854 }
855
856
857 1;