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