1 package C4::HoldsQueue;
3 # Copyright 2011 Catalyst IT
5 # This file is part of Koha.
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.
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.
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>.
20 # FIXME: expand perldoc, explain intended logic
26 use C4::Circulation qw( GetBranchItemRule );
27 use Koha::DateUtils qw( dt_from_string );
28 use Koha::Hold::HoldsQueueItems;
33 use List::Util qw( shuffle );
34 use List::MoreUtils qw( any );
36 our (@ISA, @EXPORT_OK);
45 UpdateTransportCostMatrix
46 GetPendingHoldRequestsForBib
47 load_branches_to_pull_from
48 update_queue_for_biblio
55 =head2 TransportCostMatrix
57 TransportCostMatrix();
59 Returns Transport Cost Matrix as a hashref <to branch code> => <from branch code> => cost
63 sub TransportCostMatrix {
66 my $dbh = C4::Context->dbh;
67 my $transport_costs = $dbh->selectall_arrayref("SELECT * FROM transport_cost",{ Slice => {} });
69 my $today = dt_from_string();
70 my %transport_cost_matrix;
71 foreach (@$transport_costs) {
72 my $from = $_->{frombranch};
73 my $to = $_->{tobranch};
74 my $cost = $_->{cost};
75 my $disabled = $_->{disable_transfer};
76 $transport_cost_matrix{$to}{$from} = {
78 disable_transfer => $disabled
82 return \%transport_cost_matrix;
85 =head2 UpdateTransportCostMatrix
87 UpdateTransportCostMatrix($records);
89 Updates full Transport Cost Matrix table. $records is an arrayref of records.
90 Records: { frombranch => <code>, tobranch => <code>, cost => <figure>, disable_transfer => <0,1> }
94 sub UpdateTransportCostMatrix {
96 my $dbh = C4::Context->dbh;
98 my $sth = $dbh->prepare("INSERT INTO transport_cost (frombranch, tobranch, cost, disable_transfer) VALUES (?, ?, ?, ?)");
100 $dbh->do("DELETE FROM transport_cost");
101 foreach (@$records) {
102 my $cost = $_->{cost};
103 my $from = $_->{frombranch};
104 my $to = $_->{tobranch};
105 if ($_->{disable_transfer}) {
108 elsif ( !defined ($cost) || ($cost !~ m/(0|[1-9][0-9]*)(\.[0-9]*)?/o) ) {
109 warn "Invalid $from -> $to cost $cost - must be a number >= 0, disabling";
111 $_->{disable_transfer} = 1;
113 $sth->execute( $from, $to, $cost, $_->{disable_transfer} ? 1 : 0 );
117 =head2 GetHoldsQueueItems
119 GetHoldsQueueItems({ branchlimit => $branch, itemtypeslimit => $itype, ccodeslimit => $ccode, locationslimit => $location );
121 Returns hold queue for a holding branch. If branch is omitted, then whole queue is returned
125 sub GetHoldsQueueItems {
127 my $dbh = C4::Context->dbh;
130 $search_params->{'me.holdingbranch'} = $params->{branchlimit} if $params->{branchlimit};
131 $search_params->{'itype'} = $params->{itemtypeslimit} if $params->{itemtypeslimit};
132 $search_params->{'ccode'} = $params->{ccodeslimit} if $params->{ccodeslimit};
133 $search_params->{'location'} = $params->{locationslimit} if $params->{locationslimit};
135 my $results = Koha::Hold::HoldsQueueItems->search(
146 'item_group_item' => 'item_group'
151 'ccode', 'location', 'item.cn_sort', 'author',
152 'biblio.title', 'pickbranch', 'reservedate'
164 Top level function that turns reserves into tmp_holdsqueue and hold_fill_targets.
169 my $dbh = C4::Context->dbh;
171 $dbh->do("DELETE FROM tmp_holdsqueue"); # clear the old table for new info
172 $dbh->do("DELETE FROM hold_fill_targets");
175 my $total_requests = 0;
176 my $total_available_items = 0;
177 my $num_items_mapped = 0;
180 my $transport_cost_matrix;
181 my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix");
182 if ($use_transport_cost_matrix) {
183 $transport_cost_matrix = TransportCostMatrix();
184 unless (keys %$transport_cost_matrix) {
185 warn "UseTransportCostMatrix set to yes, but matrix not populated";
186 undef $transport_cost_matrix;
190 $branches_to_use = load_branches_to_pull_from($use_transport_cost_matrix);
192 my $bibs_with_pending_requests = GetBibsWithPendingHoldRequests();
194 foreach my $biblionumber (@$bibs_with_pending_requests) {
198 my $result = update_queue_for_biblio(
199 { biblio_id => $biblionumber,
200 branches_to_use => $branches_to_use,
201 transport_cost_matrix => $transport_cost_matrix,
205 $total_requests += $result->{requests};
206 $total_available_items += $result->{available_items};
207 $num_items_mapped += $result->{mapped_items};
211 =head2 GetBibsWithPendingHoldRequests
213 my $biblionumber_aref = GetBibsWithPendingHoldRequests();
215 Return an arrayref of the biblionumbers of all bibs
216 that have one or more unfilled hold requests.
220 sub GetBibsWithPendingHoldRequests {
221 my $dbh = C4::Context->dbh;
223 my $bib_query = "SELECT DISTINCT biblionumber
227 AND reservedate <= CURRENT_DATE()
230 my $sth = $dbh->prepare($bib_query);
233 my $biblionumbers = $sth->fetchall_arrayref();
235 return [ map { $_->[0] } @$biblionumbers ];
238 =head2 GetPendingHoldRequestsForBib
240 my $requests = GetPendingHoldRequestsForBib($biblionumber);
242 Returns an arrayref of hashrefs to pending, unfilled hold requests
243 on the bib identified by $biblionumber. The following keys
244 are present in each hashref:
255 The arrayref is sorted in order of increasing priority.
259 sub GetPendingHoldRequestsForBib {
260 my $biblionumber = shift;
262 my $dbh = C4::Context->dbh;
264 my $request_query = "SELECT biblionumber, borrowernumber, itemnumber, priority, reserve_id, reserves.branchcode,
265 reservedate, reservenotes, borrowers.branchcode AS borrowerbranch, itemtype, item_level_hold, item_group_id
267 JOIN borrowers USING (borrowernumber)
268 WHERE biblionumber = ?
271 AND reservedate <= CURRENT_DATE()
274 my $sth = $dbh->prepare($request_query);
275 $sth->execute($biblionumber);
277 my $requests = $sth->fetchall_arrayref({});
282 =head2 GetItemsAvailableToFillHoldRequestsForBib
284 my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_ar);
286 Returns an arrayref of items available to fill hold requests
287 for the bib identified by C<$biblionumber>. An item is available
288 to fill a hold request if and only if:
291 * it is not withdrawn
292 * it is not marked notforloan
293 * it is not currently in transit
295 * it is not sitting on the hold shelf
296 * it is not damaged (unless AllowHoldsOnDamagedItems is on)
300 sub GetItemsAvailableToFillHoldRequestsForBib {
301 my ($biblionumber, $branches_to_use) = @_;
303 my $dbh = C4::Context->dbh;
304 my $items_query = "SELECT items.itemnumber, homebranch, holdingbranch, itemtypes.itemtype AS itype
307 if (C4::Context->preference('item-level_itypes')) {
308 $items_query .= "LEFT JOIN itemtypes ON (itemtypes.itemtype = items.itype) ";
310 $items_query .= "JOIN biblioitems USING (biblioitemnumber)
311 LEFT JOIN itemtypes USING (itemtype) ";
313 $items_query .= " LEFT JOIN branchtransfers ON (
314 items.itemnumber = branchtransfers.itemnumber
315 AND branchtransfers.datearrived IS NULL AND branchtransfers.datecancelled IS NULL
317 $items_query .= " WHERE items.notforloan = 0
318 AND holdingbranch IS NOT NULL
321 $items_query .= " AND damaged = 0" unless C4::Context->preference('AllowHoldsOnDamagedItems');
322 $items_query .= " AND items.onloan IS NULL
323 AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
324 AND items.itemnumber NOT IN (
327 WHERE biblionumber = ?
328 AND itemnumber IS NOT NULL
329 AND (found IS NOT NULL OR priority = 0)
331 AND items.biblionumber = ?
332 AND branchtransfers.itemnumber IS NULL";
334 my @params = ($biblionumber, $biblionumber);
335 if ($branches_to_use && @$branches_to_use) {
336 $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
337 push @params, @$branches_to_use;
339 my $sth = $dbh->prepare($items_query);
340 $sth->execute(@params);
342 my $itm = $sth->fetchall_arrayref({});
344 my $rule = C4::Circulation::GetBranchItemRule($_->{homebranch}, $_->{itype});
345 $_->{holdallowed} = $rule->{holdallowed};
346 $_->{hold_fulfillment_policy} = $rule->{hold_fulfillment_policy};
350 =head2 _checkHoldPolicy
352 _checkHoldPolicy($item, $request)
354 check if item agrees with hold policies
358 sub _checkHoldPolicy {
359 my ( $item, $request ) = @_;
361 return 0 unless $item->{holdallowed} ne 'not_allowed';
364 if $item->{holdallowed} eq 'from_home_library'
365 && $item->{homebranch} ne $request->{borrowerbranch};
368 if $item->{'holdallowed'} eq 'from_local_hold_group'
369 && !Koha::Libraries->find( $item->{homebranch} )
370 ->validate_hold_sibling( { branchcode => $request->{borrowerbranch} } );
372 my $hold_fulfillment_policy = $item->{hold_fulfillment_policy};
375 if $hold_fulfillment_policy eq 'holdgroup'
376 && !Koha::Libraries->find( $item->{homebranch} )
377 ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
380 if $hold_fulfillment_policy eq 'homebranch'
381 && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
384 if $hold_fulfillment_policy eq 'holdingbranch'
385 && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
388 if $hold_fulfillment_policy eq 'patrongroup'
389 && !Koha::Libraries->find( $request->{borrowerbranch} )
390 ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
396 =head2 MapItemsToHoldRequests
398 my $item_map = MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
401 $hold_requests is a hash containing hold information built by GetPendingHoldRequestsForBib
402 $available_items is a hash containing item information built by GetItemsAvailableToFillHoldRequestsForBib
403 $branches is an arrayref to a list of branches filled by load_branches_to_pull_from
404 $transport_cost_matrix is a hash of hashes with branchcodes as keys, listing the cost to transfer from that branch to another
406 Returns a hash of hashes with itemnumbers as keys, each itemnumber containing a hash with the information
407 about the hold it has been mapped to.
411 sub MapItemsToHoldRequests {
412 my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
414 # handle trival cases
415 return unless scalar(@$hold_requests) > 0;
416 return unless scalar(@$available_items) > 0;
418 # identify item-level requests
419 my %specific_items_requested = map { $_->{itemnumber} => 1 }
420 grep { defined($_->{itemnumber}) }
423 map { $_->{_object} = Koha::Items->find( $_->{itemnumber} ) } @$available_items;
425 map { $libraries->{$_->id} = $_ } Koha::Libraries->search->as_list;
427 # group available items by itemnumber
428 my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
430 # items already allocated
431 my %allocated_items = ();
433 # map of items to hold requests
436 # figure out which item-level requests can be filled
437 my $num_items_remaining = scalar(@$available_items);
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');
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;
451 my $local_hold_match;
452 foreach my $item (@$available_items) {
453 next if $item->{_object}->exclude_from_local_holds_priority;
455 next unless _can_item_fill_request( $item, $request, $libraries );
457 next if $request->{itemnumber} && $request->{itemnumber} != $item->{itemnumber};
459 my $local_holds_priority_item_branchcode =
460 $item->{$LocalHoldsPriorityItemControl};
462 my $local_holds_priority_patron_branchcode =
463 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
464 ? $request->{branchcode}
465 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
466 ? $request->{borrowerbranch}
470 $local_holds_priority_item_branchcode eq
471 $local_holds_priority_patron_branchcode;
473 if ($local_hold_match) {
474 if ( exists $items_by_itemnumber{ $item->{itemnumber} }
475 and not exists $allocated_items{ $item->{itemnumber} }
476 and not $request->{allocated})
478 $item_map{ $item->{itemnumber} } = {
479 borrowernumber => $request->{borrowernumber},
480 biblionumber => $request->{biblionumber},
481 holdingbranch => $item->{holdingbranch},
482 pickup_branch => $request->{branchcode}
483 || $request->{borrowerbranch},
484 reserve_id => $request->{reserve_id},
485 item_level => $request->{item_level_hold},
486 reservedate => $request->{reservedate},
487 reservenotes => $request->{reservenotes},
489 $allocated_items{ $item->{itemnumber} }++;
490 $request->{allocated} = 1;
491 $num_items_remaining--;
498 foreach my $request (@$hold_requests) {
499 last if $num_items_remaining == 0;
500 next if $request->{allocated};
502 # is this an item-level request?
503 if (defined($request->{itemnumber})) {
504 # fill it if possible; if not skip it
505 if ( exists $items_by_itemnumber{ $request->{itemnumber} }
506 and not exists $allocated_items{ $request->{itemnumber} }
507 and _can_item_fill_request( $items_by_itemnumber{ $request->{itemnumber} }, $request, $libraries ) )
510 $item_map{ $request->{itemnumber} } = {
511 borrowernumber => $request->{borrowernumber},
512 biblionumber => $request->{biblionumber},
513 holdingbranch => $items_by_itemnumber{ $request->{itemnumber} }->{holdingbranch},
514 pickup_branch => $request->{branchcode} || $request->{borrowerbranch},
515 reserve_id => $request->{reserve_id},
516 item_level => $request->{item_level_hold},
517 reservedate => $request->{reservedate},
518 reservenotes => $request->{reservenotes},
520 $allocated_items{ $request->{itemnumber} }++;
521 $num_items_remaining--;
524 # it's title-level request that will take up one item
525 $num_items_remaining--;
529 # group available items by branch
530 my %items_by_branch = ();
531 foreach my $item (@$available_items) {
532 next unless $item->{holdallowed} ne 'not_allowed';
534 push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
535 unless exists $allocated_items{ $item->{itemnumber} };
537 return \%item_map unless keys %items_by_branch;
539 # now handle the title-level requests
540 $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
542 foreach my $request (@$hold_requests) {
543 last if $num_items_remaining == 0;
544 next if $request->{allocated};
545 next if defined($request->{itemnumber}); # already handled these
547 # HoldsQueuePrioritizeBranch check
548 # ********************************
549 my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
550 my ( $itemnumber, $holdingbranch ); # These variables are used for tracking the filling of the hold
551 # $itemnumber, when set, is the item that has been chosen for the hold
552 # $holdingbranch gets set to the pickup branch of the request if there are items held at that branch
553 # otherwise it gets set to the least cost branch of the transport cost matrix
554 # otherwise it gets sets to the first branch from the list of branches to pull from
556 my $holding_branch_items = $items_by_branch{$pickup_branch};
557 if ($holding_branch_items) {
558 $holdingbranch = $pickup_branch;
559 } elsif ($transport_cost_matrix) {
560 $pull_branches = [ keys %items_by_branch ];
561 $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
563 unless $holdingbranch
564 ; # If using the matrix, and nothing is least cost, it means we cannot transfer to the pikcup branch for this request
565 $holding_branch_items = $items_by_branch{$holdingbranch};
568 my $priority_branch = C4::Context->preference('HoldsQueuePrioritizeBranch') // 'homebranch';
569 foreach my $item (@$holding_branch_items) {
570 if ( _can_item_fill_request( $item, $request, $libraries )
571 && $request->{borrowerbranch} eq $item->{$priority_branch} )
573 $itemnumber = $item->{itemnumber};
577 # End HoldsQueuePrioritizeBranch check
578 # ********************************
581 unless ($itemnumber) {
582 # not found yet, fall back to basics
583 if ($branches_to_use) {
584 $pull_branches = $branches_to_use;
586 $pull_branches = [keys %items_by_branch];
589 # Try picking items where the home and pickup branch match first
591 foreach my $branch (@$pull_branches) {
592 my $holding_branch_items = $items_by_branch{$branch}
595 $holdingbranch ||= $branch; # We set this as the first from the list of pull branches
596 # unless we set it above to the pickupbranch or the least cost branch
597 # FIXME: The itention is to follow StaticHoldsQueueWeight, but we don't check that pref
598 foreach my $item (@$holding_branch_items) {
599 next if $pickup_branch ne $item->{homebranch};
600 next unless _can_item_fill_request( $item, $request, $libraries );
602 $itemnumber = $item->{itemnumber};
603 $holdingbranch = $branch;
608 # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight
609 unless ( $itemnumber || !$holdingbranch) {
610 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
611 next unless _can_item_fill_request( $current_item, $request, $libraries );
613 $itemnumber = $current_item->{itemnumber};
614 last; # quit this loop as soon as we have a suitable item
618 # Now try for items for any item that can fill this hold
619 unless ( $itemnumber ) {
621 foreach my $branch (@$pull_branches) {
622 my $holding_branch_items = $items_by_branch{$branch}
625 foreach my $item (@$holding_branch_items) {
627 next unless _can_item_fill_request( $item, $request, $libraries );
629 $itemnumber = $item->{itemnumber};
630 $holdingbranch = $branch;
638 my $holding_branch_items = $items_by_branch{$holdingbranch}
639 or die "Have $itemnumber, $holdingbranch, but no items!";
640 @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
641 delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
643 $item_map{$itemnumber} = {
644 borrowernumber => $request->{borrowernumber},
645 biblionumber => $request->{biblionumber},
646 holdingbranch => $holdingbranch,
647 pickup_branch => $pickup_branch,
648 reserve_id => $request->{reserve_id},
649 item_level => $request->{item_level_hold},
650 reservedate => $request->{reservedate},
651 reservenotes => $request->{reservenotes},
653 $num_items_remaining--;
660 =head2 _can_item_fill_request
662 my $bool = _can_item_fill_request( $item, $request, $libraries );
664 This is an internal function of MapItemsToHoldRequests for checking an item against a hold. It uses the custom hashes for item and hold information
669 sub _can_item_fill_request {
670 my ( $item, $request, $libraries ) = @_;
672 # Don't fill item level holds that contravene the hold pickup policy at this time
673 return unless _checkHoldPolicy( $item, $request );
675 # If hold itemtype is set, item's itemtype must match
676 return unless ( !$request->{itemtype}
677 || $item->{itype} eq $request->{itemtype} );
679 # If hold item_group is set, item's item_group must match
682 !$request->{item_group_id}
683 || ( $item->{_object}->item_group
684 && $item->{_object}->item_group->id eq $request->{item_group_id} )
688 unless $item->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
695 =head2 CreatePickListFromItemMap
699 sub CreatePicklistFromItemMap {
700 my $item_map = shift;
702 my $dbh = C4::Context->dbh;
704 my $sth_load=$dbh->prepare("
705 INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
706 cardnumber,reservedate,title, itemcallnumber,
707 holdingbranch,pickbranch,notes, item_level_request)
708 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
711 foreach my $itemnumber (sort keys %$item_map) {
712 my $mapped_item = $item_map->{$itemnumber};
713 my $biblionumber = $mapped_item->{biblionumber};
714 my $borrowernumber = $mapped_item->{borrowernumber};
715 my $pickbranch = $mapped_item->{pickup_branch};
716 my $holdingbranch = $mapped_item->{holdingbranch};
717 my $reservedate = $mapped_item->{reservedate};
718 my $reservenotes = $mapped_item->{reservenotes};
719 my $item_level = $mapped_item->{item_level};
721 my $item = Koha::Items->find($itemnumber);
722 my $barcode = $item->barcode;
723 my $itemcallnumber = $item->itemcallnumber;
725 my $patron = Koha::Patrons->find( $borrowernumber );
726 my $cardnumber = $patron->cardnumber;
727 my $surname = $patron->surname;
728 my $firstname = $patron->firstname;
729 my $phone = $patron->phone;
731 my $biblio = Koha::Biblios->find( $biblionumber );
732 my $title = $biblio->title;
734 $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
735 $cardnumber, $reservedate, $title, $itemcallnumber,
736 $holdingbranch, $pickbranch, $reservenotes, $item_level);
740 =head2 AddToHoldTargetMap
744 sub AddToHoldTargetMap {
745 my $item_map = shift;
747 my $dbh = C4::Context->dbh;
748 my $schema = Koha::Database->new->schema;
751 INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request, reserve_id) VALUES (?, ?, ?, ?, ?, ?)
753 my $sth_insert = $dbh->prepare($insert_sql);
755 foreach my $itemnumber ( keys %$item_map ) {
756 my $mapped_item = $item_map->{$itemnumber};
759 $dbh->do( 'DELETE FROM hold_fill_targets WHERE itemnumber = ?', {}, $itemnumber );
760 $sth_insert->execute(
761 $mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
762 $mapped_item->{holdingbranch}, $mapped_item->{item_level}, $mapped_item->{reserve_id}
769 # Helper functions, not part of any interface
772 return $_[0] unless $_[0];
778 sub load_branches_to_pull_from {
779 my $use_transport_cost_matrix = shift;
783 unless ( $use_transport_cost_matrix ) {
784 my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight");
785 @branches_to_use = map { _trim($_) } split( /,/, $static_branch_list )
786 if $static_branch_list;
790 Koha::Database->new()->schema()->resultset('Branch')
791 ->get_column('branchcode')->all()
792 unless (@branches_to_use);
794 @branches_to_use = shuffle(@branches_to_use)
795 if C4::Context->preference("RandomizeHoldsQueueWeight");
797 my $today = dt_from_string();
798 if ( C4::Context->preference('HoldsQueueSkipClosed') ) {
799 @branches_to_use = grep {
800 !Koha::Calendar->new( branchcode => $_ )
801 ->is_holiday( $today )
805 return \@branches_to_use;
808 sub least_cost_branch {
811 my ($to, $from, $transport_cost_matrix) = @_;
813 # Nothing really spectacular: supply to branch, a list of potential from branches
814 # and find the minimum from - to value from the transport_cost_matrix
815 return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{$from->[0]}->{disable_transfer} != 1 );
817 # If the pickup library is in the list of libraries to pull from,
818 # return that library right away, it is obviously the least costly
819 return ($to) if any { $_ eq $to } @$from;
821 my ($least_cost, @branch);
823 my $cell = $transport_cost_matrix->{$to}{$_};
824 next if $cell->{disable_transfer};
826 my $cost = $cell->{cost};
827 next unless defined $cost; # XXX should this be reported?
829 unless (defined $least_cost) {
835 next if $cost > $least_cost;
837 if ($cost == $least_cost) {
848 # XXX return a random @branch with minimum cost instead of the first one;
849 # return $branch[0] if @branch == 1;
852 =head3 update_queue_for_biblio
854 my $result = update_queue_for_biblio(
856 biblio_id => $biblio_id,
857 [ branches_to_use => $branches_to_use,
858 transport_cost_matrix => $transport_cost_matrix,
863 Given a I<biblio_id>, this method calculates and sets the holds queue entries
864 for the biblio's holds, and the hold fill targets (items).
868 It return a hashref containing:
872 =item I<requests>: the pending holds count for the biblio.
874 =item I<available_items> the count of items that are available to fill holds for the biblio.
876 =item I<mapped_items> the total items that got mapped.
880 =head4 Optional parameters
884 =item I<branches_to_use> a list of branchcodes to be used to restrict which items can be used.
886 =item I<transport_cost_matrix> is the output of C<TransportCostMatrix>.
888 =item I<delete> tells the method to delete prior entries on the related tables for the biblio_id.
892 Note: All the optional parameters will be calculated in the method if omitted. They
893 are allowed to be passed to avoid calculating them many times inside loops.
897 sub update_queue_for_biblio {
899 my $biblio_id = $args->{biblio_id};
902 # We need to empty the queue for this biblio unless CreateQueue has emptied the entire queue for rebuilding
903 if ( $args->{delete} ) {
904 my $dbh = C4::Context->dbh;
906 $dbh->do("DELETE FROM tmp_holdsqueue WHERE biblionumber=$biblio_id");
907 $dbh->do("DELETE FROM hold_fill_targets WHERE biblionumber=$biblio_id");
910 my $hold_requests = GetPendingHoldRequestsForBib($biblio_id);
911 $result->{requests} = scalar( @{$hold_requests} );
912 # No need to check anything else if there are no holds to fill
913 return $result unless $result->{requests};
915 my $branches_to_use = $args->{branches_to_use} // load_branches_to_pull_from( C4::Context->preference('UseTransportCostMatrix') );
916 my $transport_cost_matrix;
918 if ( !exists $args->{transport_cost_matrix}
919 && C4::Context->preference('UseTransportCostMatrix') ) {
920 $transport_cost_matrix = TransportCostMatrix();
922 $transport_cost_matrix = $args->{transport_cost_matrix};
925 my $available_items = GetItemsAvailableToFillHoldRequestsForBib( $biblio_id, $branches_to_use );
927 $result->{available_items} = scalar( @{$available_items} );
929 my $item_map = MapItemsToHoldRequests( $hold_requests, $available_items, $branches_to_use, $transport_cost_matrix );
930 $result->{mapped_items} = scalar( keys %{$item_map} );
933 CreatePicklistFromItemMap($item_map);
934 AddToHoldTargetMap($item_map);