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