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