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 MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
402 sub MapItemsToHoldRequests {
403 my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
405 # handle trival cases
406 return unless scalar(@$hold_requests) > 0;
407 return unless scalar(@$available_items) > 0;
409 # identify item-level requests
410 my %specific_items_requested = map { $_->{itemnumber} => 1 }
411 grep { defined($_->{itemnumber}) }
414 map { $_->{_object} = Koha::Items->find( $_->{itemnumber} ) } @$available_items;
416 map { $libraries->{$_->id} = $_ } Koha::Libraries->search->as_list;
418 # group available items by itemnumber
419 my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
421 # items already allocated
422 my %allocated_items = ();
424 # map of items to hold requests
427 # figure out which item-level requests can be filled
428 my $num_items_remaining = scalar(@$available_items);
430 # Look for Local Holds Priority matches first
431 if ( C4::Context->preference('LocalHoldsPriority') ) {
432 my $LocalHoldsPriorityPatronControl =
433 C4::Context->preference('LocalHoldsPriorityPatronControl');
434 my $LocalHoldsPriorityItemControl =
435 C4::Context->preference('LocalHoldsPriorityItemControl');
437 foreach my $request (@$hold_requests) {
438 last if $num_items_remaining == 0;
439 my $patron = Koha::Patrons->find($request->{borrowernumber});
440 next if $patron->category->exclude_from_local_holds_priority;
442 my $local_hold_match;
443 foreach my $item (@$available_items) {
444 next if $item->{_object}->exclude_from_local_holds_priority;
446 next unless _checkHoldPolicy($item, $request);
448 next if $request->{itemnumber} && $request->{itemnumber} != $item->{itemnumber};
450 next if $request->{item_group_id} && $item->{_object}->item_group && $item->{_object}->item_group->id ne $request->{item_group_id};
452 next unless $item->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
454 my $local_holds_priority_item_branchcode =
455 $item->{$LocalHoldsPriorityItemControl};
457 my $local_holds_priority_patron_branchcode =
458 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
459 ? $request->{branchcode}
460 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
461 ? $request->{borrowerbranch}
465 $local_holds_priority_item_branchcode eq
466 $local_holds_priority_patron_branchcode;
468 if ($local_hold_match) {
469 if ( exists $items_by_itemnumber{ $item->{itemnumber} }
470 and not exists $allocated_items{ $item->{itemnumber} }
471 and not $request->{allocated})
473 $item_map{ $item->{itemnumber} } = {
474 borrowernumber => $request->{borrowernumber},
475 biblionumber => $request->{biblionumber},
476 holdingbranch => $item->{holdingbranch},
477 pickup_branch => $request->{branchcode}
478 || $request->{borrowerbranch},
479 reserve_id => $request->{reserve_id},
480 item_level => $request->{item_level_hold},
481 reservedate => $request->{reservedate},
482 reservenotes => $request->{reservenotes},
484 $allocated_items{ $item->{itemnumber} }++;
485 $request->{allocated} = 1;
486 $num_items_remaining--;
493 foreach my $request (@$hold_requests) {
494 last if $num_items_remaining == 0;
495 next if $request->{allocated};
497 # is this an item-level request?
498 if (defined($request->{itemnumber})) {
499 # fill it if possible; if not skip it
501 exists $items_by_itemnumber{ $request->{itemnumber} }
502 and not exists $allocated_items{ $request->{itemnumber} }
503 and _checkHoldPolicy($items_by_itemnumber{ $request->{itemnumber} }, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
504 and ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
505 || $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} )
506 and ( !$request->{item_group_id} # If hold item_group is set, item's item_group must match
507 || ( $items_by_itemnumber{ $request->{itemnumber} }->{_object}->item_group
508 && $items_by_itemnumber{ $request->{itemnumber} }->{_object}->item_group->id eq $request->{item_group_id} ) )
509 and $items_by_itemnumber{ $request->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } )
514 $item_map{ $request->{itemnumber} } = {
515 borrowernumber => $request->{borrowernumber},
516 biblionumber => $request->{biblionumber},
517 holdingbranch => $items_by_itemnumber{ $request->{itemnumber} }->{holdingbranch},
518 pickup_branch => $request->{branchcode} || $request->{borrowerbranch},
519 reserve_id => $request->{reserve_id},
520 item_level => $request->{item_level_hold},
521 reservedate => $request->{reservedate},
522 reservenotes => $request->{reservenotes},
524 $allocated_items{ $request->{itemnumber} }++;
525 $num_items_remaining--;
528 # it's title-level request that will take up one item
529 $num_items_remaining--;
533 # group available items by branch
534 my %items_by_branch = ();
535 foreach my $item (@$available_items) {
536 next unless $item->{holdallowed} ne 'not_allowed';
538 push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
539 unless exists $allocated_items{ $item->{itemnumber} };
541 return \%item_map unless keys %items_by_branch;
543 # now handle the title-level requests
544 $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
546 foreach my $request (@$hold_requests) {
547 last if $num_items_remaining == 0;
548 next if $request->{allocated};
549 next if defined($request->{itemnumber}); # already handled these
551 # look for local match first
552 my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
553 my ($itemnumber, $holdingbranch);
555 my $holding_branch_items = $items_by_branch{$pickup_branch};
556 my $priority_branch = C4::Context->preference('HoldsQueuePrioritizeBranch') // 'homebranch';
557 if ( $holding_branch_items ) {
558 foreach my $item (@$holding_branch_items) {
559 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
562 $request->{borrowerbranch} eq $item->{$priority_branch}
563 && _checkHoldPolicy($item, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
564 && ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
565 || ( $request->{itemnumber} && ( $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} ) ) )
566 && ( !$request->{item_group_id} # If hold item_group is set, item's item_group must match
567 || ( $item->{_object}->item_group && $item->{_object}->item_group->id eq $request->{item_group_id} ) )
570 $itemnumber = $item->{itemnumber};
574 $holdingbranch = $pickup_branch;
576 elsif ($transport_cost_matrix) {
577 $pull_branches = [keys %items_by_branch];
578 $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
579 if ( $holdingbranch ) {
581 my $holding_branch_items = $items_by_branch{$holdingbranch};
582 foreach my $item (@$holding_branch_items) {
583 next if $request->{borrowerbranch} ne $item->{$priority_branch};
584 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
586 # Don't fill item level holds that contravene the hold pickup policy at this time
587 next unless _checkHoldPolicy($item, $request);
589 # If hold itemtype is set, item's itemtype must match
590 next unless ( !$request->{itemtype}
591 || $item->{itype} eq $request->{itemtype} );
593 # If hold item_group is set, item's item_group must match
595 !$request->{item_group_id}
596 || ( $item->{_object}->item_group
597 && $item->{_object}->item_group->id eq $request->{item_group_id} )
600 $itemnumber = $item->{itemnumber};
609 unless ($itemnumber) {
610 # not found yet, fall back to basics
611 if ($branches_to_use) {
612 $pull_branches = $branches_to_use;
614 $pull_branches = [keys %items_by_branch];
617 # Try picking items where the home and pickup branch match first
619 foreach my $branch (@$pull_branches) {
620 my $holding_branch_items = $items_by_branch{$branch}
623 $holdingbranch ||= $branch;
624 foreach my $item (@$holding_branch_items) {
625 next if $pickup_branch ne $item->{homebranch};
626 next unless _checkHoldPolicy($item, $request);
627 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
629 # If hold itemtype is set, item's itemtype must match
630 next unless ( !$request->{itemtype}
631 || $item->{itype} eq $request->{itemtype} );
633 # If hold item_group is set, item's item_group must match
635 !$request->{item_group_id}
636 || ( $item->{_object}->item_group
637 && $item->{_object}->item_group->id eq $request->{item_group_id} )
640 $itemnumber = $item->{itemnumber};
641 $holdingbranch = $branch;
646 # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight
647 unless ( $itemnumber || !$holdingbranch) {
648 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
649 next unless _checkHoldPolicy($current_item, $request); # Don't fill item level holds that contravene the hold pickup policy at this time
651 # If hold itemtype is set, item's itemtype must match
652 next unless ( !$request->{itemtype}
653 || $current_item->{itype} eq $request->{itemtype} );
655 next unless $items_by_itemnumber{ $current_item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
657 # If hold item_group is set, item's item_group must match
659 !$request->{item_group_id}
660 || ( $current_item->{_object}->item_group
661 && $current_item->{_object}->item_group->id eq $request->{item_group_id} )
665 $itemnumber = $current_item->{itemnumber};
666 last; # quit this loop as soon as we have a suitable item
670 # Now try for items for any item that can fill this hold
671 unless ( $itemnumber ) {
673 foreach my $branch (@$pull_branches) {
674 my $holding_branch_items = $items_by_branch{$branch}
677 foreach my $item (@$holding_branch_items) {
678 # Don't fill item level holds that contravene the hold pickup policy at this time
679 next unless _checkHoldPolicy($item, $request);
681 # If hold itemtype is set, item's itemtype must match
682 next unless ( !$request->{itemtype}
683 || $item->{itype} eq $request->{itemtype} );
685 # If hold item_group is set, item's item_group must match
687 !$request->{item_group_id}
688 || ( $item->{_object}->item_group
689 && $item->{_object}->item_group->id eq $request->{item_group_id} )
692 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
694 $itemnumber = $item->{itemnumber};
695 $holdingbranch = $branch;
703 my $holding_branch_items = $items_by_branch{$holdingbranch}
704 or die "Have $itemnumber, $holdingbranch, but no items!";
705 @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
706 delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
708 $item_map{$itemnumber} = {
709 borrowernumber => $request->{borrowernumber},
710 biblionumber => $request->{biblionumber},
711 holdingbranch => $holdingbranch,
712 pickup_branch => $pickup_branch,
713 reserve_id => $request->{reserve_id},
714 item_level => $request->{item_level_hold},
715 reservedate => $request->{reservedate},
716 reservenotes => $request->{reservenotes},
718 $num_items_remaining--;
724 =head2 CreatePickListFromItemMap
728 sub CreatePicklistFromItemMap {
729 my $item_map = shift;
731 my $dbh = C4::Context->dbh;
733 my $sth_load=$dbh->prepare("
734 INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
735 cardnumber,reservedate,title, itemcallnumber,
736 holdingbranch,pickbranch,notes, item_level_request)
737 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
740 foreach my $itemnumber (sort keys %$item_map) {
741 my $mapped_item = $item_map->{$itemnumber};
742 my $biblionumber = $mapped_item->{biblionumber};
743 my $borrowernumber = $mapped_item->{borrowernumber};
744 my $pickbranch = $mapped_item->{pickup_branch};
745 my $holdingbranch = $mapped_item->{holdingbranch};
746 my $reservedate = $mapped_item->{reservedate};
747 my $reservenotes = $mapped_item->{reservenotes};
748 my $item_level = $mapped_item->{item_level};
750 my $item = Koha::Items->find($itemnumber);
751 my $barcode = $item->barcode;
752 my $itemcallnumber = $item->itemcallnumber;
754 my $patron = Koha::Patrons->find( $borrowernumber );
755 my $cardnumber = $patron->cardnumber;
756 my $surname = $patron->surname;
757 my $firstname = $patron->firstname;
758 my $phone = $patron->phone;
760 my $biblio = Koha::Biblios->find( $biblionumber );
761 my $title = $biblio->title;
763 $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
764 $cardnumber, $reservedate, $title, $itemcallnumber,
765 $holdingbranch, $pickbranch, $reservenotes, $item_level);
769 =head2 AddToHoldTargetMap
773 sub AddToHoldTargetMap {
774 my $item_map = shift;
776 my $dbh = C4::Context->dbh;
777 my $schema = Koha::Database->new->schema;
780 INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request, reserve_id) VALUES (?, ?, ?, ?, ?, ?)
782 my $sth_insert = $dbh->prepare($insert_sql);
784 foreach my $itemnumber ( keys %$item_map ) {
785 my $mapped_item = $item_map->{$itemnumber};
788 $dbh->do( 'DELETE FROM hold_fill_targets WHERE itemnumber = ?', {}, $itemnumber );
789 $sth_insert->execute(
790 $mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
791 $mapped_item->{holdingbranch}, $mapped_item->{item_level}, $mapped_item->{reserve_id}
798 # Helper functions, not part of any interface
801 return $_[0] unless $_[0];
807 sub load_branches_to_pull_from {
808 my $use_transport_cost_matrix = shift;
812 unless ( $use_transport_cost_matrix ) {
813 my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight");
814 @branches_to_use = map { _trim($_) } split( /,/, $static_branch_list )
815 if $static_branch_list;
819 Koha::Database->new()->schema()->resultset('Branch')
820 ->get_column('branchcode')->all()
821 unless (@branches_to_use);
823 @branches_to_use = shuffle(@branches_to_use)
824 if C4::Context->preference("RandomizeHoldsQueueWeight");
826 my $today = dt_from_string();
827 if ( C4::Context->preference('HoldsQueueSkipClosed') ) {
828 @branches_to_use = grep {
829 !Koha::Calendar->new( branchcode => $_ )
830 ->is_holiday( $today )
834 return \@branches_to_use;
837 sub least_cost_branch {
840 my ($to, $from, $transport_cost_matrix) = @_;
842 # Nothing really spectacular: supply to branch, a list of potential from branches
843 # and find the minimum from - to value from the transport_cost_matrix
844 return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{$from->[0]}->{disable_transfer} != 1 );
846 # If the pickup library is in the list of libraries to pull from,
847 # return that library right away, it is obviously the least costly
848 return ($to) if any { $_ eq $to } @$from;
850 my ($least_cost, @branch);
852 my $cell = $transport_cost_matrix->{$to}{$_};
853 next if $cell->{disable_transfer};
855 my $cost = $cell->{cost};
856 next unless defined $cost; # XXX should this be reported?
858 unless (defined $least_cost) {
864 next if $cost > $least_cost;
866 if ($cost == $least_cost) {
877 # XXX return a random @branch with minimum cost instead of the first one;
878 # return $branch[0] if @branch == 1;
881 =head3 update_queue_for_biblio
883 my $result = update_queue_for_biblio(
885 biblio_id => $biblio_id,
886 [ branches_to_use => $branches_to_use,
887 transport_cost_matrix => $transport_cost_matrix,
892 Given a I<biblio_id>, this method calculates and sets the holds queue entries
893 for the biblio's holds, and the hold fill targets (items).
897 It return a hashref containing:
901 =item I<requests>: the pending holds count for the biblio.
903 =item I<available_items> the count of items that are available to fill holds for the biblio.
905 =item I<mapped_items> the total items that got mapped.
909 =head4 Optional parameters
913 =item I<branches_to_use> a list of branchcodes to be used to restrict which items can be used.
915 =item I<transport_cost_matrix> is the output of C<TransportCostMatrix>.
917 =item I<delete> tells the method to delete prior entries on the related tables for the biblio_id.
921 Note: All the optional parameters will be calculated in the method if omitted. They
922 are allowed to be passed to avoid calculating them many times inside loops.
926 sub update_queue_for_biblio {
928 my $biblio_id = $args->{biblio_id};
931 # We need to empty the queue for this biblio unless CreateQueue has emptied the entire queue for rebuilding
932 if ( $args->{delete} ) {
933 my $dbh = C4::Context->dbh;
935 $dbh->do("DELETE FROM tmp_holdsqueue WHERE biblionumber=$biblio_id");
936 $dbh->do("DELETE FROM hold_fill_targets WHERE biblionumber=$biblio_id");
939 my $hold_requests = GetPendingHoldRequestsForBib($biblio_id);
940 $result->{requests} = scalar( @{$hold_requests} );
941 # No need to check anything else if there are no holds to fill
942 return $result unless $result->{requests};
944 my $branches_to_use = $args->{branches_to_use} // load_branches_to_pull_from( C4::Context->preference('UseTransportCostMatrix') );
945 my $transport_cost_matrix;
947 if ( !exists $args->{transport_cost_matrix}
948 && C4::Context->preference('UseTransportCostMatrix') ) {
949 $transport_cost_matrix = TransportCostMatrix();
951 $transport_cost_matrix = $args->{transport_cost_matrix};
954 my $available_items = GetItemsAvailableToFillHoldRequestsForBib( $biblio_id, $branches_to_use );
956 $result->{available_items} = scalar( @{$available_items} );
958 my $item_map = MapItemsToHoldRequests( $hold_requests, $available_items, $branches_to_use, $transport_cost_matrix );
959 $result->{mapped_items} = scalar( keys %{$item_map} );
962 CreatePicklistFromItemMap($item_map);
963 AddToHoldTargetMap($item_map);