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