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