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