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 );
32 use List::Util qw( shuffle );
33 use List::MoreUtils qw( any );
35 our (@ISA, @EXPORT_OK);
44 UpdateTransportCostMatrix
45 GetPendingHoldRequestsForBib
46 load_branches_to_pull_from
47 update_queue_for_biblio
54 =head2 TransportCostMatrix
56 TransportCostMatrix();
58 Returns Transport Cost Matrix as a hashref <to branch code> => <from branch code> => cost
62 sub TransportCostMatrix {
65 my $dbh = C4::Context->dbh;
66 my $transport_costs = $dbh->selectall_arrayref("SELECT * FROM transport_cost",{ Slice => {} });
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} = {
77 disable_transfer => $disabled
81 return \%transport_cost_matrix;
84 =head2 UpdateTransportCostMatrix
86 UpdateTransportCostMatrix($records);
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> }
93 sub UpdateTransportCostMatrix {
95 my $dbh = C4::Context->dbh;
97 my $sth = $dbh->prepare("INSERT INTO transport_cost (frombranch, tobranch, cost, disable_transfer) VALUES (?, ?, ?, ?)");
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}) {
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";
110 $_->{disable_transfer} = 1;
112 $sth->execute( $from, $to, $cost, $_->{disable_transfer} ? 1 : 0 );
116 =head2 GetHoldsQueueItems
118 GetHoldsQueueItems({ branchlimit => $branch, itemtypeslimit => $itype, ccodeslimit => $ccode, locationslimit => $location );
120 Returns hold queue for a holding branch. If branch is omitted, then whole queue is returned
124 sub GetHoldsQueueItems {
126 my $dbh = C4::Context->dbh;
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
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 )
144 if ($params->{branchlimit}) {
145 $query .="AND tmp_holdsqueue.holdingbranch = ? ";
146 push @bind_params, $params->{branchlimit};
148 if( $params->{itemtypeslimit} ) {
149 $query .=" AND items.itype = ? ";
150 push @bind_params, $params->{itemtypeslimit};
152 if( $params->{ccodeslimit} ) {
153 $query .=" AND items.ccode = ? ";
154 push @bind_params, $params->{ccodeslimit};
156 if( $params->{locationslimit} ) {
157 $query .=" AND items.location = ? ";
158 push @bind_params, $params->{locationslimit};
160 $query .= " ORDER BY ccode, location, cn_sort, author, title, pickbranch, reservedate";
161 my $sth = $dbh->prepare($query);
162 $sth->execute(@bind_params);
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};
169 delete $row->{itemtype};
180 Top level function that turns reserves into tmp_holdsqueue and hold_fill_targets.
186 my $unallocated = $params->{unallocated};
187 my $dbh = C4::Context->dbh;
189 unless( $unallocated ){
190 $dbh->do("DELETE FROM tmp_holdsqueue"); # clear the old table for new info
191 $dbh->do("DELETE FROM hold_fill_targets");
195 my $total_requests = 0;
196 my $total_available_items = 0;
197 my $num_items_mapped = 0;
200 my $transport_cost_matrix;
201 my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix");
202 if ($use_transport_cost_matrix) {
203 $transport_cost_matrix = TransportCostMatrix();
204 unless (keys %$transport_cost_matrix) {
205 warn "UseTransportCostMatrix set to yes, but matrix not populated";
206 undef $transport_cost_matrix;
210 $branches_to_use = load_branches_to_pull_from($use_transport_cost_matrix);
212 my $bibs_with_pending_requests = GetBibsWithPendingHoldRequests();
214 foreach my $biblionumber (@$bibs_with_pending_requests) {
218 my $result = update_queue_for_biblio(
219 { biblio_id => $biblionumber,
220 branches_to_use => $branches_to_use,
221 transport_cost_matrix => $transport_cost_matrix,
222 unallocated => $unallocated
226 $total_requests += $result->{requests};
227 $total_available_items += $result->{available_items};
228 $num_items_mapped += $result->{mapped_items};
232 =head2 GetBibsWithPendingHoldRequests
234 my $biblionumber_aref = GetBibsWithPendingHoldRequests();
236 Return an arrayref of the biblionumbers of all bibs
237 that have one or more unfilled hold requests.
241 sub GetBibsWithPendingHoldRequests {
242 my $dbh = C4::Context->dbh;
244 my $bib_query = "SELECT DISTINCT biblionumber
248 AND reservedate <= CURRENT_DATE()
250 AND reserve_id NOT IN (SELECT reserve_id FROM hold_fill_targets)
252 my $sth = $dbh->prepare($bib_query);
255 my $biblionumbers = $sth->fetchall_arrayref();
257 return [ map { $_->[0] } @$biblionumbers ];
260 =head2 GetPendingHoldRequestsForBib
262 my $requests = GetPendingHoldRequestsForBib({ biblionumber => $biblionumber, unallocated => $unallocated });
264 Returns an arrayref of hashrefs to pending, unfilled hold requests
265 on the bib identified by $biblionumber. Optionally returns only unallocated holds. The following keys
266 are present in each hashref:
277 The arrayref is sorted in order of increasing priority.
281 sub GetPendingHoldRequestsForBib {
283 my $biblionumber = $params->{biblionumber};
284 my $unallocated = $params->{unallocated};
286 my $dbh = C4::Context->dbh;
288 my $request_query = "SELECT biblionumber, borrowernumber, itemnumber, priority, reserve_id, reserves.branchcode,
289 reservedate, reservenotes, borrowers.branchcode AS borrowerbranch, itemtype, item_level_hold, item_group_id
291 JOIN borrowers USING (borrowernumber)
292 WHERE biblionumber = ?
295 AND reservedate <= CURRENT_DATE()
297 $request_query .= "AND reserve_id NOT IN (SELECT reserve_id FROM hold_fill_targets) " if $unallocated;
298 $request_query .= "ORDER BY priority";
299 my $sth = $dbh->prepare($request_query);
300 $sth->execute($biblionumber);
302 my $requests = $sth->fetchall_arrayref({});
307 =head2 GetItemsAvailableToFillHoldRequestsForBib
309 my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_ar);
311 Returns an arrayref of items available to fill hold requests
312 for the bib identified by C<$biblionumber>. An item is available
313 to fill a hold request if and only if:
316 * it is not withdrawn
317 * it is not marked notforloan
318 * it is not currently in transit
320 * it is not sitting on the hold shelf
321 * it is not damaged (unless AllowHoldsOnDamagedItems is on)
325 sub GetItemsAvailableToFillHoldRequestsForBib {
326 my ($biblionumber, $branches_to_use) = @_;
328 my $dbh = C4::Context->dbh;
329 my $items_query = "SELECT items.itemnumber, homebranch, holdingbranch, itemtypes.itemtype AS itype
332 if (C4::Context->preference('item-level_itypes')) {
333 $items_query .= "LEFT JOIN itemtypes ON (itemtypes.itemtype = items.itype) ";
335 $items_query .= "JOIN biblioitems USING (biblioitemnumber)
336 LEFT JOIN itemtypes USING (itemtype) ";
338 $items_query .= " LEFT JOIN branchtransfers ON (
339 items.itemnumber = branchtransfers.itemnumber
340 AND branchtransfers.datearrived IS NULL AND branchtransfers.datecancelled IS NULL
342 $items_query .= " WHERE items.notforloan = 0
343 AND holdingbranch IS NOT NULL
346 $items_query .= " AND damaged = 0" unless C4::Context->preference('AllowHoldsOnDamagedItems');
347 $items_query .= " AND items.onloan IS NULL
348 AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
349 AND items.itemnumber NOT IN (
352 WHERE biblionumber = ?
353 AND itemnumber IS NOT NULL
354 AND (found IS NOT NULL OR priority = 0)
356 AND items.itemnumber NOT IN (
359 WHERE biblionumber = ?
361 AND items.biblionumber = ?
362 AND branchtransfers.itemnumber IS NULL";
364 my @params = ($biblionumber, $biblionumber, $biblionumber);
365 if ($branches_to_use && @$branches_to_use) {
366 $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
367 push @params, @$branches_to_use;
369 my $sth = $dbh->prepare($items_query);
370 $sth->execute(@params);
372 my $itm = $sth->fetchall_arrayref({});
374 my $rule = C4::Circulation::GetBranchItemRule($_->{homebranch}, $_->{itype});
375 $_->{holdallowed} = $rule->{holdallowed};
376 $_->{hold_fulfillment_policy} = $rule->{hold_fulfillment_policy};
380 =head2 _checkHoldPolicy
382 _checkHoldPolicy($item, $request)
384 check if item agrees with hold policies
388 sub _checkHoldPolicy {
389 my ( $item, $request ) = @_;
391 return 0 unless $item->{holdallowed} ne 'not_allowed';
394 if $item->{holdallowed} eq 'from_home_library'
395 && $item->{homebranch} ne $request->{borrowerbranch};
398 if $item->{'holdallowed'} eq 'from_local_hold_group'
399 && !Koha::Libraries->find( $item->{homebranch} )
400 ->validate_hold_sibling( { branchcode => $request->{borrowerbranch} } );
402 my $hold_fulfillment_policy = $item->{hold_fulfillment_policy};
405 if $hold_fulfillment_policy eq 'holdgroup'
406 && !Koha::Libraries->find( $item->{homebranch} )
407 ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
410 if $hold_fulfillment_policy eq 'homebranch'
411 && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
414 if $hold_fulfillment_policy eq 'holdingbranch'
415 && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
418 if $hold_fulfillment_policy eq 'patrongroup'
419 && !Koha::Libraries->find( $request->{borrowerbranch} )
420 ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
426 =head2 MapItemsToHoldRequests
428 MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
432 sub MapItemsToHoldRequests {
433 my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
435 # handle trival cases
436 return unless scalar(@$hold_requests) > 0;
437 return unless scalar(@$available_items) > 0;
439 # identify item-level requests
440 my %specific_items_requested = map { $_->{itemnumber} => 1 }
441 grep { defined($_->{itemnumber}) }
444 map { $_->{_object} = Koha::Items->find( $_->{itemnumber} ) } @$available_items;
446 map { $libraries->{$_->id} = $_ } Koha::Libraries->search->as_list;
448 # group available items by itemnumber
449 my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
451 # items already allocated
452 my %allocated_items = ();
454 # map of items to hold requests
457 # figure out which item-level requests can be filled
458 my $num_items_remaining = scalar(@$available_items);
460 # Look for Local Holds Priority matches first
461 if ( C4::Context->preference('LocalHoldsPriority') ) {
462 my $LocalHoldsPriorityPatronControl =
463 C4::Context->preference('LocalHoldsPriorityPatronControl');
464 my $LocalHoldsPriorityItemControl =
465 C4::Context->preference('LocalHoldsPriorityItemControl');
467 foreach my $request (@$hold_requests) {
468 last if $num_items_remaining == 0;
469 my $patron = Koha::Patrons->find($request->{borrowernumber});
470 next if $patron->category->exclude_from_local_holds_priority;
472 my $local_hold_match;
473 foreach my $item (@$available_items) {
474 next if $item->{_object}->exclude_from_local_holds_priority;
476 next unless _checkHoldPolicy($item, $request);
478 next if $request->{itemnumber} && $request->{itemnumber} != $item->{itemnumber};
480 next if $request->{item_group_id} && $item->{_object}->item_group && $item->{_object}->item_group->id ne $request->{item_group_id};
482 next unless $item->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
484 my $local_holds_priority_item_branchcode =
485 $item->{$LocalHoldsPriorityItemControl};
487 my $local_holds_priority_patron_branchcode =
488 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
489 ? $request->{branchcode}
490 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
491 ? $request->{borrowerbranch}
495 $local_holds_priority_item_branchcode eq
496 $local_holds_priority_patron_branchcode;
498 if ($local_hold_match) {
499 if ( exists $items_by_itemnumber{ $item->{itemnumber} }
500 and not exists $allocated_items{ $item->{itemnumber} }
501 and not $request->{allocated})
503 $item_map{ $item->{itemnumber} } = {
504 borrowernumber => $request->{borrowernumber},
505 biblionumber => $request->{biblionumber},
506 holdingbranch => $item->{holdingbranch},
507 pickup_branch => $request->{branchcode}
508 || $request->{borrowerbranch},
509 reserve_id => $request->{reserve_id},
510 item_level => $request->{item_level_hold},
511 reservedate => $request->{reservedate},
512 reservenotes => $request->{reservenotes},
514 $allocated_items{ $item->{itemnumber} }++;
515 $request->{allocated} = 1;
516 $num_items_remaining--;
523 foreach my $request (@$hold_requests) {
524 last if $num_items_remaining == 0;
525 next if $request->{allocated};
527 # is this an item-level request?
528 if (defined($request->{itemnumber})) {
529 # fill it if possible; if not skip it
531 exists $items_by_itemnumber{ $request->{itemnumber} }
532 and not exists $allocated_items{ $request->{itemnumber} }
533 and _checkHoldPolicy($items_by_itemnumber{ $request->{itemnumber} }, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
534 and ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
535 || $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} )
536 and ( !$request->{item_group_id} # If hold item_group is set, item's item_group must match
537 || ( $items_by_itemnumber{ $request->{itemnumber} }->{_object}->item_group
538 && $items_by_itemnumber{ $request->{itemnumber} }->{_object}->item_group->id eq $request->{item_group_id} ) )
539 and $items_by_itemnumber{ $request->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } )
544 $item_map{ $request->{itemnumber} } = {
545 borrowernumber => $request->{borrowernumber},
546 biblionumber => $request->{biblionumber},
547 holdingbranch => $items_by_itemnumber{ $request->{itemnumber} }->{holdingbranch},
548 pickup_branch => $request->{branchcode} || $request->{borrowerbranch},
549 reserve_id => $request->{reserve_id},
550 item_level => $request->{item_level_hold},
551 reservedate => $request->{reservedate},
552 reservenotes => $request->{reservenotes},
554 $allocated_items{ $request->{itemnumber} }++;
555 $num_items_remaining--;
558 # it's title-level request that will take up one item
559 $num_items_remaining--;
563 # group available items by branch
564 my %items_by_branch = ();
565 foreach my $item (@$available_items) {
566 next unless $item->{holdallowed} ne 'not_allowed';
568 push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
569 unless exists $allocated_items{ $item->{itemnumber} };
571 return \%item_map unless keys %items_by_branch;
573 # now handle the title-level requests
574 $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
576 foreach my $request (@$hold_requests) {
577 last if $num_items_remaining == 0;
578 next if $request->{allocated};
579 next if defined($request->{itemnumber}); # already handled these
581 # look for local match first
582 my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
583 my ($itemnumber, $holdingbranch);
585 my $holding_branch_items = $items_by_branch{$pickup_branch};
586 my $priority_branch = C4::Context->preference('HoldsQueuePrioritizeBranch') // 'homebranch';
587 if ( $holding_branch_items ) {
588 foreach my $item (@$holding_branch_items) {
589 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
592 $request->{borrowerbranch} eq $item->{$priority_branch}
593 && _checkHoldPolicy($item, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
594 && ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
595 || ( $request->{itemnumber} && ( $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} ) ) )
596 && ( !$request->{item_group_id} # If hold item_group is set, item's item_group must match
597 || ( $item->{_object}->item_group && $item->{_object}->item_group->id eq $request->{item_group_id} ) )
600 $itemnumber = $item->{itemnumber};
604 $holdingbranch = $pickup_branch;
606 elsif ($transport_cost_matrix) {
607 $pull_branches = [keys %items_by_branch];
608 $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
609 if ( $holdingbranch ) {
611 my $holding_branch_items = $items_by_branch{$holdingbranch};
612 foreach my $item (@$holding_branch_items) {
613 next if $request->{borrowerbranch} ne $item->{$priority_branch};
614 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
616 # Don't fill item level holds that contravene the hold pickup policy at this time
617 next unless _checkHoldPolicy($item, $request);
619 # If hold itemtype is set, item's itemtype must match
620 next unless ( !$request->{itemtype}
621 || $item->{itype} eq $request->{itemtype} );
623 # If hold item_group is set, item's item_group must match
625 !$request->{item_group_id}
626 || ( $item->{_object}->item_group
627 && $item->{_object}->item_group->id eq $request->{item_group_id} )
630 $itemnumber = $item->{itemnumber};
639 unless ($itemnumber) {
640 # not found yet, fall back to basics
641 if ($branches_to_use) {
642 $pull_branches = $branches_to_use;
644 $pull_branches = [keys %items_by_branch];
647 # Try picking items where the home and pickup branch match first
649 foreach my $branch (@$pull_branches) {
650 my $holding_branch_items = $items_by_branch{$branch}
653 $holdingbranch ||= $branch;
654 foreach my $item (@$holding_branch_items) {
655 next if $pickup_branch ne $item->{homebranch};
656 next unless _checkHoldPolicy($item, $request);
657 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
659 # If hold itemtype is set, item's itemtype must match
660 next unless ( !$request->{itemtype}
661 || $item->{itype} eq $request->{itemtype} );
663 # If hold item_group is set, item's item_group must match
665 !$request->{item_group_id}
666 || ( $item->{_object}->item_group
667 && $item->{_object}->item_group->id eq $request->{item_group_id} )
670 $itemnumber = $item->{itemnumber};
671 $holdingbranch = $branch;
676 # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight
677 unless ( $itemnumber || !$holdingbranch) {
678 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
679 next unless _checkHoldPolicy($current_item, $request); # Don't fill item level holds that contravene the hold pickup policy at this time
681 # If hold itemtype is set, item's itemtype must match
682 next unless ( !$request->{itemtype}
683 || $current_item->{itype} eq $request->{itemtype} );
685 next unless $items_by_itemnumber{ $current_item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
687 # If hold item_group is set, item's item_group must match
689 !$request->{item_group_id}
690 || ( $current_item->{_object}->item_group
691 && $current_item->{_object}->item_group->id eq $request->{item_group_id} )
695 $itemnumber = $current_item->{itemnumber};
696 last; # quit this loop as soon as we have a suitable item
700 # Now try for items for any item that can fill this hold
701 unless ( $itemnumber ) {
703 foreach my $branch (@$pull_branches) {
704 my $holding_branch_items = $items_by_branch{$branch}
707 foreach my $item (@$holding_branch_items) {
708 # Don't fill item level holds that contravene the hold pickup policy at this time
709 next unless _checkHoldPolicy($item, $request);
711 # If hold itemtype is set, item's itemtype must match
712 next unless ( !$request->{itemtype}
713 || $item->{itype} eq $request->{itemtype} );
715 # If hold item_group is set, item's item_group must match
717 !$request->{item_group_id}
718 || ( $item->{_object}->item_group
719 && $item->{_object}->item_group->id eq $request->{item_group_id} )
722 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
724 $itemnumber = $item->{itemnumber};
725 $holdingbranch = $branch;
733 my $holding_branch_items = $items_by_branch{$holdingbranch}
734 or die "Have $itemnumber, $holdingbranch, but no items!";
735 @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
736 delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
738 $item_map{$itemnumber} = {
739 borrowernumber => $request->{borrowernumber},
740 biblionumber => $request->{biblionumber},
741 holdingbranch => $holdingbranch,
742 pickup_branch => $pickup_branch,
743 reserve_id => $request->{reserve_id},
744 item_level => $request->{item_level_hold},
745 reservedate => $request->{reservedate},
746 reservenotes => $request->{reservenotes},
748 $num_items_remaining--;
754 =head2 CreatePickListFromItemMap
758 sub CreatePicklistFromItemMap {
759 my $item_map = shift;
761 my $dbh = C4::Context->dbh;
763 my $sth_load=$dbh->prepare("
764 INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
765 cardnumber,reservedate,title, itemcallnumber,
766 holdingbranch,pickbranch,notes, item_level_request)
767 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
770 foreach my $itemnumber (sort keys %$item_map) {
771 my $mapped_item = $item_map->{$itemnumber};
772 my $biblionumber = $mapped_item->{biblionumber};
773 my $borrowernumber = $mapped_item->{borrowernumber};
774 my $pickbranch = $mapped_item->{pickup_branch};
775 my $holdingbranch = $mapped_item->{holdingbranch};
776 my $reservedate = $mapped_item->{reservedate};
777 my $reservenotes = $mapped_item->{reservenotes};
778 my $item_level = $mapped_item->{item_level};
780 my $item = Koha::Items->find($itemnumber);
781 my $barcode = $item->barcode;
782 my $itemcallnumber = $item->itemcallnumber;
784 my $patron = Koha::Patrons->find( $borrowernumber );
785 my $cardnumber = $patron->cardnumber;
786 my $surname = $patron->surname;
787 my $firstname = $patron->firstname;
788 my $phone = $patron->phone;
790 my $biblio = Koha::Biblios->find( $biblionumber );
791 my $title = $biblio->title;
793 $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
794 $cardnumber, $reservedate, $title, $itemcallnumber,
795 $holdingbranch, $pickbranch, $reservenotes, $item_level);
799 =head2 AddToHoldTargetMap
803 sub AddToHoldTargetMap {
804 my $item_map = shift;
806 my $dbh = C4::Context->dbh;
807 my $schema = Koha::Database->new->schema;
810 INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request, reserve_id) VALUES (?, ?, ?, ?, ?, ?)
812 my $sth_insert = $dbh->prepare($insert_sql);
814 foreach my $itemnumber ( keys %$item_map ) {
815 my $mapped_item = $item_map->{$itemnumber};
818 $dbh->do( 'DELETE FROM hold_fill_targets WHERE itemnumber = ?', {}, $itemnumber );
819 $sth_insert->execute(
820 $mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
821 $mapped_item->{holdingbranch}, $mapped_item->{item_level}, $mapped_item->{reserve_id}
828 # Helper functions, not part of any interface
831 return $_[0] unless $_[0];
837 sub load_branches_to_pull_from {
838 my $use_transport_cost_matrix = shift;
842 unless ( $use_transport_cost_matrix ) {
843 my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight");
844 @branches_to_use = map { _trim($_) } split( /,/, $static_branch_list )
845 if $static_branch_list;
849 Koha::Database->new()->schema()->resultset('Branch')
850 ->get_column('branchcode')->all()
851 unless (@branches_to_use);
853 @branches_to_use = shuffle(@branches_to_use)
854 if C4::Context->preference("RandomizeHoldsQueueWeight");
856 my $today = dt_from_string();
857 if ( C4::Context->preference('HoldsQueueSkipClosed') ) {
858 @branches_to_use = grep {
859 !Koha::Calendar->new( branchcode => $_ )
860 ->is_holiday( $today )
864 return \@branches_to_use;
867 sub least_cost_branch {
870 my ($to, $from, $transport_cost_matrix) = @_;
872 # Nothing really spectacular: supply to branch, a list of potential from branches
873 # and find the minimum from - to value from the transport_cost_matrix
874 return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{$from->[0]}->{disable_transfer} != 1 );
876 # If the pickup library is in the list of libraries to pull from,
877 # return that library right away, it is obviously the least costly
878 return ($to) if any { $_ eq $to } @$from;
880 my ($least_cost, @branch);
882 my $cell = $transport_cost_matrix->{$to}{$_};
883 next if $cell->{disable_transfer};
885 my $cost = $cell->{cost};
886 next unless defined $cost; # XXX should this be reported?
888 unless (defined $least_cost) {
894 next if $cost > $least_cost;
896 if ($cost == $least_cost) {
907 # XXX return a random @branch with minimum cost instead of the first one;
908 # return $branch[0] if @branch == 1;
911 =head3 update_queue_for_biblio
913 my $result = update_queue_for_biblio(
915 biblio_id => $biblio_id,
916 [ branches_to_use => $branches_to_use,
917 transport_cost_matrix => $transport_cost_matrix,
919 unallocated => $unallocated, ]
923 Given a I<biblio_id>, this method calculates and sets the holds queue entries
924 for the biblio's holds, and the hold fill targets (items).
928 It return a hashref containing:
932 =item I<requests>: the pending holds count for the biblio.
934 =item I<available_items> the count of items that are available to fill holds for the biblio.
936 =item I<mapped_items> the total items that got mapped.
940 =head4 Optional parameters
944 =item I<branches_to_use> a list of branchcodes to be used to restrict which items can be used.
946 =item I<transport_cost_matrix> is the output of C<TransportCostMatrix>.
948 =item I<delete> tells the method to delete prior entries on the related tables for the biblio_id.
950 =item I<unallocated> tells the method to limit the holds to those not in the holds queue, should not
951 be passed at the same time as delete.
955 Note: All the optional parameters will be calculated in the method if omitted. They
956 are allowed to be passed to avoid calculating them many times inside loops.
960 sub update_queue_for_biblio {
962 my $biblio_id = $args->{biblio_id};
965 # We need to empty the queue for this biblio unless CreateQueue has emptied the entire queue for rebuilding
966 if ( $args->{delete} ) {
967 my $dbh = C4::Context->dbh;
969 $dbh->do("DELETE FROM tmp_holdsqueue WHERE biblionumber=$biblio_id");
970 $dbh->do("DELETE FROM hold_fill_targets WHERE biblionumber=$biblio_id");
973 my $hold_requests = GetPendingHoldRequestsForBib({ biblionumber => $biblio_id, unallocated => $args->{unallocated} });
974 $result->{requests} = scalar( @{$hold_requests} );
975 # No need to check anything else if there are no holds to fill
976 return $result unless $result->{requests};
978 my $branches_to_use = $args->{branches_to_use} // load_branches_to_pull_from( C4::Context->preference('UseTransportCostMatrix') );
979 my $transport_cost_matrix;
981 if ( !exists $args->{transport_cost_matrix}
982 && C4::Context->preference('UseTransportCostMatrix') ) {
983 $transport_cost_matrix = TransportCostMatrix();
985 $transport_cost_matrix = $args->{transport_cost_matrix};
988 my $available_items = GetItemsAvailableToFillHoldRequestsForBib( $biblio_id, $branches_to_use );
990 $result->{available_items} = scalar( @{$available_items} );
992 my $item_map = MapItemsToHoldRequests( $hold_requests, $available_items, $branches_to_use, $transport_cost_matrix );
993 $result->{mapped_items} = scalar( keys %{$item_map} );
996 CreatePicklistFromItemMap($item_map);
997 AddToHoldTargetMap($item_map);