Bug 35432: Simplay HoldsQueuePrioritize branch check
[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::Hold::HoldsQueueItems;
29 use Koha::Items;
30 use Koha::Libraries;
31 use Koha::Patrons;
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 $search_params;
130     $search_params->{'me.holdingbranch'} = $params->{branchlimit} if $params->{branchlimit};
131     $search_params->{'itype'} = $params->{itemtypeslimit} if $params->{itemtypeslimit};
132     $search_params->{'ccode'} = $params->{ccodeslimit} if $params->{ccodeslimit};
133     $search_params->{'location'} = $params->{locationslimit} if $params->{locationslimit};
134
135     my $results = Koha::Hold::HoldsQueueItems->search(
136         $search_params,
137         {
138             join => [
139                 'borrower',
140             ],
141             prefetch => [
142                 'biblio',
143                 'biblioitem',
144                 {
145                     'item' => {
146                         'item_group_item' => 'item_group'
147                     }
148                 }
149             ],
150             order_by => [
151                 'ccode',        'location',   'item.cn_sort', 'author',
152                 'biblio.title', 'pickbranch', 'reservedate'
153             ],
154         }
155     );
156
157     return $results;
158 }
159
160 =head2 CreateQueue
161
162   CreateQueue();
163
164 Top level function that turns reserves into tmp_holdsqueue and hold_fill_targets.
165
166 =cut
167
168 sub CreateQueue {
169     my $dbh   = C4::Context->dbh;
170
171     $dbh->do("DELETE FROM tmp_holdsqueue");  # clear the old table for new info
172     $dbh->do("DELETE FROM hold_fill_targets");
173
174     my $total_bibs            = 0;
175     my $total_requests        = 0;
176     my $total_available_items = 0;
177     my $num_items_mapped      = 0;
178
179     my $branches_to_use;
180     my $transport_cost_matrix;
181     my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix");
182     if ($use_transport_cost_matrix) {
183         $transport_cost_matrix = TransportCostMatrix();
184         unless (keys %$transport_cost_matrix) {
185             warn "UseTransportCostMatrix set to yes, but matrix not populated";
186             undef $transport_cost_matrix;
187         }
188     }
189
190     $branches_to_use = load_branches_to_pull_from($use_transport_cost_matrix);
191
192     my $bibs_with_pending_requests = GetBibsWithPendingHoldRequests();
193
194     foreach my $biblionumber (@$bibs_with_pending_requests) {
195
196         $total_bibs++;
197
198         my $result = update_queue_for_biblio(
199             {   biblio_id             => $biblionumber,
200                 branches_to_use       => $branches_to_use,
201                 transport_cost_matrix => $transport_cost_matrix,
202             }
203         );
204
205         $total_requests        += $result->{requests};
206         $total_available_items += $result->{available_items};
207         $num_items_mapped      += $result->{mapped_items};
208     }
209 }
210
211 =head2 GetBibsWithPendingHoldRequests
212
213   my $biblionumber_aref = GetBibsWithPendingHoldRequests();
214
215 Return an arrayref of the biblionumbers of all bibs
216 that have one or more unfilled hold requests.
217
218 =cut
219
220 sub GetBibsWithPendingHoldRequests {
221     my $dbh = C4::Context->dbh;
222
223     my $bib_query = "SELECT DISTINCT biblionumber
224                      FROM reserves
225                      WHERE found IS NULL
226                      AND priority > 0
227                      AND reservedate <= CURRENT_DATE()
228                      AND suspend = 0
229                      ";
230     my $sth = $dbh->prepare($bib_query);
231
232     $sth->execute();
233     my $biblionumbers = $sth->fetchall_arrayref();
234
235     return [ map { $_->[0] } @$biblionumbers ];
236 }
237
238 =head2 GetPendingHoldRequestsForBib
239
240   my $requests = GetPendingHoldRequestsForBib($biblionumber);
241
242 Returns an arrayref of hashrefs to pending, unfilled hold requests
243 on the bib identified by $biblionumber.  The following keys
244 are present in each hashref:
245
246     biblionumber
247     borrowernumber
248     itemnumber
249     priority
250     branchcode
251     reservedate
252     reservenotes
253     borrowerbranch
254
255 The arrayref is sorted in order of increasing priority.
256
257 =cut
258
259 sub GetPendingHoldRequestsForBib {
260     my $biblionumber = shift;
261
262     my $dbh = C4::Context->dbh;
263
264     my $request_query = "SELECT biblionumber, borrowernumber, itemnumber, priority, reserve_id, reserves.branchcode,
265                                 reservedate, reservenotes, borrowers.branchcode AS borrowerbranch, itemtype, item_level_hold, item_group_id
266                          FROM reserves
267                          JOIN borrowers USING (borrowernumber)
268                          WHERE biblionumber = ?
269                          AND found IS NULL
270                          AND priority > 0
271                          AND reservedate <= CURRENT_DATE()
272                          AND suspend = 0
273                          ORDER BY priority";
274     my $sth = $dbh->prepare($request_query);
275     $sth->execute($biblionumber);
276
277     my $requests = $sth->fetchall_arrayref({});
278     return $requests;
279
280 }
281
282 =head2 GetItemsAvailableToFillHoldRequestsForBib
283
284   my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_ar);
285
286 Returns an arrayref of items available to fill hold requests
287 for the bib identified by C<$biblionumber>.  An item is available
288 to fill a hold request if and only if:
289
290     * it is not on loan
291     * it is not withdrawn
292     * it is not marked notforloan
293     * it is not currently in transit
294     * it is not lost
295     * it is not sitting on the hold shelf
296     * it is not damaged (unless AllowHoldsOnDamagedItems is on)
297
298 =cut
299
300 sub GetItemsAvailableToFillHoldRequestsForBib {
301     my ($biblionumber, $branches_to_use) = @_;
302
303     my $dbh = C4::Context->dbh;
304     my $items_query = "SELECT items.itemnumber, homebranch, holdingbranch, itemtypes.itemtype AS itype
305                        FROM items ";
306
307     if (C4::Context->preference('item-level_itypes')) {
308         $items_query .=   "LEFT JOIN itemtypes ON (itemtypes.itemtype = items.itype) ";
309     } else {
310         $items_query .=   "JOIN biblioitems USING (biblioitemnumber)
311                            LEFT JOIN itemtypes USING (itemtype) ";
312     }
313     $items_query .=  " LEFT JOIN branchtransfers ON (
314                            items.itemnumber = branchtransfers.itemnumber
315                            AND branchtransfers.datearrived IS NULL AND branchtransfers.datecancelled IS NULL
316                      )";
317     $items_query .=  " WHERE items.notforloan = 0
318                        AND holdingbranch IS NOT NULL
319                        AND itemlost = 0
320                        AND withdrawn = 0";
321     $items_query .= "  AND damaged = 0" unless C4::Context->preference('AllowHoldsOnDamagedItems');
322     $items_query .= "  AND items.onloan IS NULL
323                        AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
324                        AND items.itemnumber NOT IN (
325                            SELECT itemnumber
326                            FROM reserves
327                            WHERE biblionumber = ?
328                            AND itemnumber IS NOT NULL
329                            AND (found IS NOT NULL OR priority = 0)
330                         )
331                        AND items.biblionumber = ?
332                        AND branchtransfers.itemnumber IS NULL";
333
334     my @params = ($biblionumber, $biblionumber);
335     if ($branches_to_use && @$branches_to_use) {
336         $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
337         push @params, @$branches_to_use;
338     }
339     my $sth = $dbh->prepare($items_query);
340     $sth->execute(@params);
341
342     my $itm = $sth->fetchall_arrayref({});
343     return [ grep {
344         my $rule = C4::Circulation::GetBranchItemRule($_->{homebranch}, $_->{itype});
345         $_->{holdallowed} = $rule->{holdallowed};
346         $_->{hold_fulfillment_policy} = $rule->{hold_fulfillment_policy};
347     } @{$itm} ];
348 }
349
350 =head2 _checkHoldPolicy
351
352     _checkHoldPolicy($item, $request)
353
354     check if item agrees with hold policies
355
356 =cut
357
358 sub _checkHoldPolicy {
359     my ( $item, $request ) = @_;
360
361     return 0 unless $item->{holdallowed} ne 'not_allowed';
362
363     return 0
364       if $item->{holdallowed} eq 'from_home_library'
365       && $item->{homebranch} ne $request->{borrowerbranch};
366
367     return 0
368       if $item->{'holdallowed'} eq 'from_local_hold_group'
369       && !Koha::Libraries->find( $item->{homebranch} )
370               ->validate_hold_sibling( { branchcode => $request->{borrowerbranch} } );
371
372     my $hold_fulfillment_policy = $item->{hold_fulfillment_policy};
373
374     return 0
375       if $hold_fulfillment_policy eq 'holdgroup'
376       && !Koha::Libraries->find( $item->{homebranch} )
377             ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
378
379     return 0
380       if $hold_fulfillment_policy eq 'homebranch'
381       && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
382
383     return 0
384       if $hold_fulfillment_policy eq 'holdingbranch'
385       && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
386
387     return 0
388       if $hold_fulfillment_policy eq 'patrongroup'
389       && !Koha::Libraries->find( $request->{borrowerbranch} )
390               ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
391
392     return 1;
393
394 }
395
396 =head2 MapItemsToHoldRequests
397
398   my $item_map = MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
399
400   Parameters:
401   $hold_requests is a hash containing hold information built by GetPendingHoldRequestsForBib
402   $available_items is a hash containing item information built by GetItemsAvailableToFillHoldRequestsForBib
403   $branches is an arrayref to a list of branches filled by load_branches_to_pull_from
404   $transport_cost_matrix is a hash of hashes with branchcodes as keys, listing the cost to transfer from that branch to another
405
406   Returns a hash of hashes with itemnumbers as keys, each itemnumber containing a hash with the information
407   about the hold it has been mapped to.
408
409 =cut
410
411 sub MapItemsToHoldRequests {
412     my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
413
414     # handle trival cases
415     return unless scalar(@$hold_requests) > 0;
416     return unless scalar(@$available_items) > 0;
417
418     # identify item-level requests
419     my %specific_items_requested = map { $_->{itemnumber} => 1 }
420                                    grep { defined($_->{itemnumber}) }
421                                    @$hold_requests;
422
423     map { $_->{_object} = Koha::Items->find( $_->{itemnumber} ) } @$available_items;
424     my $libraries = {};
425     map { $libraries->{$_->id} = $_ } Koha::Libraries->search->as_list;
426
427     # group available items by itemnumber
428     my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
429
430     # items already allocated
431     my %allocated_items = ();
432
433     # map of items to hold requests
434     my %item_map = ();
435
436     # figure out which item-level requests can be filled
437     my $num_items_remaining = scalar(@$available_items);
438
439     # Look for Local Holds Priority matches first
440     if ( C4::Context->preference('LocalHoldsPriority') ) {
441         my $LocalHoldsPriorityPatronControl =
442           C4::Context->preference('LocalHoldsPriorityPatronControl');
443         my $LocalHoldsPriorityItemControl =
444           C4::Context->preference('LocalHoldsPriorityItemControl');
445
446         foreach my $request (@$hold_requests) {
447             last if $num_items_remaining == 0;
448             my $patron = Koha::Patrons->find($request->{borrowernumber});
449             next if $patron->category->exclude_from_local_holds_priority;
450
451             my $local_hold_match;
452             foreach my $item (@$available_items) {
453                 next if $item->{_object}->exclude_from_local_holds_priority;
454
455                 next unless _can_item_fill_request( $item, $request, $libraries );
456
457                 next if $request->{itemnumber} && $request->{itemnumber} != $item->{itemnumber};
458
459                 my $local_holds_priority_item_branchcode =
460                   $item->{$LocalHoldsPriorityItemControl};
461
462                 my $local_holds_priority_patron_branchcode =
463                   ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
464                   ? $request->{branchcode}
465                   : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
466                   ? $request->{borrowerbranch}
467                   : undef;
468
469                 $local_hold_match =
470                   $local_holds_priority_item_branchcode eq
471                   $local_holds_priority_patron_branchcode;
472
473                 if ($local_hold_match) {
474                     if ( exists $items_by_itemnumber{ $item->{itemnumber} }
475                         and not exists $allocated_items{ $item->{itemnumber} }
476                         and not $request->{allocated})
477                     {
478                         $item_map{ $item->{itemnumber} } = {
479                             borrowernumber => $request->{borrowernumber},
480                             biblionumber   => $request->{biblionumber},
481                             holdingbranch  => $item->{holdingbranch},
482                             pickup_branch  => $request->{branchcode}
483                               || $request->{borrowerbranch},
484                             reserve_id   => $request->{reserve_id},
485                             item_level   => $request->{item_level_hold},
486                             reservedate  => $request->{reservedate},
487                             reservenotes => $request->{reservenotes},
488                         };
489                         $allocated_items{ $item->{itemnumber} }++;
490                         $request->{allocated} = 1;
491                         $num_items_remaining--;
492                     }
493                 }
494             }
495         }
496     }
497
498     foreach my $request (@$hold_requests) {
499         last if $num_items_remaining == 0;
500         next if $request->{allocated};
501
502         # is this an item-level request?
503         if (defined($request->{itemnumber})) {
504             # fill it if possible; if not skip it
505             if (    exists $items_by_itemnumber{ $request->{itemnumber} }
506                 and not exists $allocated_items{ $request->{itemnumber} }
507                 and _can_item_fill_request( $items_by_itemnumber{ $request->{itemnumber} }, $request, $libraries ) )
508             {
509
510                 $item_map{ $request->{itemnumber} } = {
511                     borrowernumber => $request->{borrowernumber},
512                     biblionumber   => $request->{biblionumber},
513                     holdingbranch  => $items_by_itemnumber{ $request->{itemnumber} }->{holdingbranch},
514                     pickup_branch  => $request->{branchcode} || $request->{borrowerbranch},
515                     reserve_id     => $request->{reserve_id},
516                     item_level     => $request->{item_level_hold},
517                     reservedate    => $request->{reservedate},
518                     reservenotes   => $request->{reservenotes},
519                 };
520                 $allocated_items{ $request->{itemnumber} }++;
521                 $num_items_remaining--;
522             }
523         } else {
524             # it's title-level request that will take up one item
525             $num_items_remaining--;
526         }
527     }
528
529     # group available items by branch
530     my %items_by_branch = ();
531     foreach my $item (@$available_items) {
532         next unless $item->{holdallowed} ne 'not_allowed';
533
534         push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
535           unless exists $allocated_items{ $item->{itemnumber} };
536     }
537     return \%item_map unless keys %items_by_branch;
538
539     # now handle the title-level requests
540     $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
541     my $pull_branches;
542     foreach my $request (@$hold_requests) {
543         last if $num_items_remaining == 0;
544         next if $request->{allocated};
545         next if defined($request->{itemnumber}); # already handled these
546
547         # HoldsQueuePrioritizeBranch check
548         # ********************************
549         my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
550         my ( $itemnumber, $holdingbranch );    # These variables are used for tracking the filling of the hold
551                                                # $itemnumber, when set, is the item that has been chosen for the hold
552             # $holdingbranch gets set to the pickup branch of the request if there are items held at that branch
553             # otherwise it gets set to the least cost branch of the transport cost matrix
554             # otherwise it gets sets to the first branch from the list of branches to pull from
555
556         my $holding_branch_items = $items_by_branch{$pickup_branch};
557         if ($holding_branch_items) {
558             $holdingbranch = $pickup_branch;
559         } elsif ($transport_cost_matrix) {
560             $pull_branches = [ keys %items_by_branch ];
561             $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
562             next
563                 unless $holdingbranch
564                 ; # If using the matrix, and nothing is least cost, it means we cannot transfer to the pikcup branch for this request
565             $holding_branch_items = $items_by_branch{$holdingbranch};
566         }
567
568         my $priority_branch = C4::Context->preference('HoldsQueuePrioritizeBranch') // 'homebranch';
569         foreach my $item (@$holding_branch_items) {
570             if ( _can_item_fill_request( $item, $request, $libraries )
571                 && $request->{borrowerbranch} eq $item->{$priority_branch} )
572             {
573                 $itemnumber = $item->{itemnumber};
574                 last;
575             }
576         }
577         # End HoldsQueuePrioritizeBranch check
578         # ********************************
579
580
581         unless ($itemnumber) {
582             # not found yet, fall back to basics
583             if ($branches_to_use) {
584                 $pull_branches = $branches_to_use;
585             } else {
586                 $pull_branches = [keys %items_by_branch];
587             }
588
589             # Try picking items where the home and pickup branch match first
590             PULL_BRANCHES:
591             foreach my $branch (@$pull_branches) {
592                 my $holding_branch_items = $items_by_branch{$branch}
593                   or next;
594
595                 $holdingbranch ||= $branch; # We set this as the first from the list of pull branches
596                 # unless we set it above to the pickupbranch or the least cost branch
597                 # FIXME: The itention is to follow StaticHoldsQueueWeight, but we don't check that pref
598                 foreach my $item (@$holding_branch_items) {
599                     next if $pickup_branch ne $item->{homebranch};
600                     next unless _can_item_fill_request( $item, $request, $libraries );
601
602                     $itemnumber = $item->{itemnumber};
603                     $holdingbranch = $branch;
604                     last PULL_BRANCHES;
605                 }
606             }
607
608             # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight
609             unless ( $itemnumber || !$holdingbranch) {
610                 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
611                     next unless _can_item_fill_request( $current_item, $request, $libraries );
612
613                     $itemnumber = $current_item->{itemnumber};
614                     last; # quit this loop as soon as we have a suitable item
615                 }
616             }
617
618             # Now try for items for any item that can fill this hold
619             unless ( $itemnumber ) {
620                 PULL_BRANCHES2:
621                 foreach my $branch (@$pull_branches) {
622                     my $holding_branch_items = $items_by_branch{$branch}
623                       or next;
624
625                     foreach my $item (@$holding_branch_items) {
626
627                         next unless _can_item_fill_request( $item, $request, $libraries );
628
629                         $itemnumber = $item->{itemnumber};
630                         $holdingbranch = $branch;
631                         last PULL_BRANCHES2;
632                     }
633                 }
634             }
635         }
636
637         if ($itemnumber) {
638             my $holding_branch_items = $items_by_branch{$holdingbranch}
639               or die "Have $itemnumber, $holdingbranch, but no items!";
640             @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
641             delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
642
643             $item_map{$itemnumber} = {
644                 borrowernumber => $request->{borrowernumber},
645                 biblionumber => $request->{biblionumber},
646                 holdingbranch => $holdingbranch,
647                 pickup_branch => $pickup_branch,
648                 reserve_id => $request->{reserve_id},
649                 item_level => $request->{item_level_hold},
650                 reservedate => $request->{reservedate},
651                 reservenotes => $request->{reservenotes},
652             };
653             $num_items_remaining--;
654         }
655     }
656     return \%item_map;
657 }
658
659
660 =head2 _can_item_fill_request
661
662   my $bool = _can_item_fill_request( $item, $request, $libraries );
663
664   This is an internal function of MapItemsToHoldRequests for checking an item against a hold. It uses the custom hashes for item and hold information
665   used by thta routine
666
667 =cut
668
669 sub _can_item_fill_request {
670     my ( $item, $request, $libraries ) = @_;
671
672     # Don't fill item level holds that contravene the hold pickup policy at this time
673     return unless _checkHoldPolicy( $item, $request );
674
675     # If hold itemtype is set, item's itemtype must match
676     return unless ( !$request->{itemtype}
677         || $item->{itype} eq $request->{itemtype} );
678
679     # If hold item_group is set, item's item_group must match
680     return
681         unless (
682         !$request->{item_group_id}
683         || (   $item->{_object}->item_group
684             && $item->{_object}->item_group->id eq $request->{item_group_id} )
685         );
686
687     return
688         unless $item->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
689
690     return 1;
691 }
692
693
694
695 =head2 CreatePickListFromItemMap
696
697 =cut
698
699 sub CreatePicklistFromItemMap {
700     my $item_map = shift;
701
702     my $dbh = C4::Context->dbh;
703
704     my $sth_load=$dbh->prepare("
705         INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
706                                     cardnumber,reservedate,title, itemcallnumber,
707                                     holdingbranch,pickbranch,notes, item_level_request)
708         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
709     ");
710
711     foreach my $itemnumber  (sort keys %$item_map) {
712         my $mapped_item = $item_map->{$itemnumber};
713         my $biblionumber = $mapped_item->{biblionumber};
714         my $borrowernumber = $mapped_item->{borrowernumber};
715         my $pickbranch = $mapped_item->{pickup_branch};
716         my $holdingbranch = $mapped_item->{holdingbranch};
717         my $reservedate = $mapped_item->{reservedate};
718         my $reservenotes = $mapped_item->{reservenotes};
719         my $item_level = $mapped_item->{item_level};
720
721         my $item = Koha::Items->find($itemnumber);
722         my $barcode = $item->barcode;
723         my $itemcallnumber = $item->itemcallnumber;
724
725         my $patron = Koha::Patrons->find( $borrowernumber );
726         my $cardnumber = $patron->cardnumber;
727         my $surname = $patron->surname;
728         my $firstname = $patron->firstname;
729         my $phone = $patron->phone;
730
731         my $biblio = Koha::Biblios->find( $biblionumber );
732         my $title = $biblio->title;
733
734         $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
735                            $cardnumber, $reservedate, $title, $itemcallnumber,
736                            $holdingbranch, $pickbranch, $reservenotes, $item_level);
737     }
738 }
739
740 =head2 AddToHoldTargetMap
741
742 =cut
743
744 sub AddToHoldTargetMap {
745     my $item_map = shift;
746
747     my $dbh    = C4::Context->dbh;
748     my $schema = Koha::Database->new->schema;
749
750     my $insert_sql = q(
751         INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request, reserve_id) VALUES (?, ?, ?, ?, ?, ?)
752     );
753     my $sth_insert = $dbh->prepare($insert_sql);
754
755     foreach my $itemnumber ( keys %$item_map ) {
756         my $mapped_item = $item_map->{$itemnumber};
757         $schema->txn_do(
758             sub {
759                 $dbh->do( 'DELETE FROM hold_fill_targets WHERE itemnumber = ?', {}, $itemnumber );
760                 $sth_insert->execute(
761                     $mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
762                     $mapped_item->{holdingbranch},  $mapped_item->{item_level},   $mapped_item->{reserve_id}
763                 );
764             }
765         );
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     my $biblio_id = $args->{biblio_id};
900     my $result;
901
902     # We need to empty the queue for this biblio unless CreateQueue has emptied the entire queue for rebuilding
903     if ( $args->{delete} ) {
904         my $dbh = C4::Context->dbh;
905
906         $dbh->do("DELETE FROM tmp_holdsqueue WHERE biblionumber=$biblio_id");
907         $dbh->do("DELETE FROM hold_fill_targets WHERE biblionumber=$biblio_id");
908     }
909
910     my $hold_requests   = GetPendingHoldRequestsForBib($biblio_id);
911     $result->{requests} = scalar( @{$hold_requests} );
912     # No need to check anything else if there are no holds to fill
913     return $result unless $result->{requests};
914
915     my $branches_to_use = $args->{branches_to_use} // load_branches_to_pull_from( C4::Context->preference('UseTransportCostMatrix') );
916     my $transport_cost_matrix;
917
918     if ( !exists $args->{transport_cost_matrix}
919         && C4::Context->preference('UseTransportCostMatrix') ) {
920         $transport_cost_matrix = TransportCostMatrix();
921     } else {
922         $transport_cost_matrix = $args->{transport_cost_matrix};
923     }
924
925     my $available_items = GetItemsAvailableToFillHoldRequestsForBib( $biblio_id, $branches_to_use );
926
927     $result->{available_items}  = scalar( @{$available_items} );
928
929     my $item_map = MapItemsToHoldRequests( $hold_requests, $available_items, $branches_to_use, $transport_cost_matrix );
930     $result->{mapped_items} = scalar( keys %{$item_map} );
931
932     if ($item_map) {
933         CreatePicklistFromItemMap($item_map);
934         AddToHoldTargetMap($item_map);
935     }
936
937     return $result;
938 }
939
940 1;