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