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(
220 biblio_id => $biblionumber,
221 branches_to_use => $branches_to_use,
222 transport_cost_matrix => $transport_cost_matrix,
223 unallocated => $unallocated
227 $total_requests += $result->{requests};
228 $total_available_items += $result->{available_items};
229 $num_items_mapped += $result->{mapped_items};
233 =head2 GetBibsWithPendingHoldRequests
235 my $biblionumber_aref = GetBibsWithPendingHoldRequests();
237 Return an arrayref of the biblionumbers of all bibs
238 that have one or more unfilled hold requests.
242 sub GetBibsWithPendingHoldRequests {
243 my $dbh = C4::Context->dbh;
245 my $bib_query = "SELECT DISTINCT biblionumber
249 AND reservedate <= CURRENT_DATE()
251 AND reserve_id NOT IN (SELECT reserve_id FROM hold_fill_targets)
253 my $sth = $dbh->prepare($bib_query);
256 my $biblionumbers = $sth->fetchall_arrayref();
258 return [ map { $_->[0] } @$biblionumbers ];
261 =head2 GetPendingHoldRequestsForBib
263 my $requests = GetPendingHoldRequestsForBib( { biblionumber => $biblionumber, unallocated => $unallocated } );
265 Returns an arrayref of hashrefs to pending, unfilled hold requests
266 on the bib identified by $biblionumber. Optionally returns only unallocated holds. The following keys
267 are present in each hashref:
278 The arrayref is sorted in order of increasing priority.
282 sub GetPendingHoldRequestsForBib {
284 my $biblionumber = $params->{biblionumber};
285 my $unallocated = $params->{unallocated};
287 my $dbh = C4::Context->dbh;
289 my $request_query = "SELECT biblionumber, borrowernumber, itemnumber, priority, reserve_id, reserves.branchcode,
290 reservedate, reservenotes, borrowers.branchcode AS borrowerbranch, itemtype, item_level_hold, item_group_id
292 JOIN borrowers USING (borrowernumber)
293 WHERE biblionumber = ?
296 AND reservedate <= CURRENT_DATE()
298 $request_query .= "AND reserve_id NOT IN (SELECT reserve_id FROM hold_fill_targets) " if $unallocated;
299 $request_query .= "ORDER BY priority";
300 my $sth = $dbh->prepare($request_query);
301 $sth->execute($biblionumber);
303 my $requests = $sth->fetchall_arrayref({});
308 =head2 GetItemsAvailableToFillHoldRequestsForBib
310 my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_ar);
312 Returns an arrayref of items available to fill hold requests
313 for the bib identified by C<$biblionumber>. An item is available
314 to fill a hold request if and only if:
317 * it is not withdrawn
318 * it is not marked notforloan
319 * it is not currently in transit
321 * it is not sitting on the hold shelf
322 * it is not damaged (unless AllowHoldsOnDamagedItems is on)
326 sub GetItemsAvailableToFillHoldRequestsForBib {
327 my ($biblionumber, $branches_to_use) = @_;
329 my $dbh = C4::Context->dbh;
330 my $items_query = "SELECT items.itemnumber, homebranch, holdingbranch, itemtypes.itemtype AS itype
333 if ( C4::Context->preference('item-level_itypes') ) {
334 $items_query .= "LEFT JOIN itemtypes ON (itemtypes.itemtype = items.itype) ";
336 $items_query .= "JOIN biblioitems USING (biblioitemnumber)
337 LEFT JOIN itemtypes USING (itemtype) ";
339 $items_query .= " LEFT JOIN branchtransfers ON (
340 items.itemnumber = branchtransfers.itemnumber
341 AND branchtransfers.datearrived IS NULL AND branchtransfers.datecancelled IS NULL
343 $items_query .= " WHERE items.notforloan = 0
344 AND holdingbranch IS NOT NULL
347 $items_query .= " AND damaged = 0" unless C4::Context->preference('AllowHoldsOnDamagedItems');
348 $items_query .= " AND items.onloan IS NULL
349 AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
350 AND items.itemnumber NOT IN (
353 WHERE biblionumber = ?
354 AND itemnumber IS NOT NULL
355 AND (found IS NOT NULL OR priority = 0)
357 AND items.itemnumber NOT IN (
360 WHERE biblionumber = ?
362 AND items.biblionumber = ?
363 AND branchtransfers.itemnumber IS NULL";
365 my @params = ($biblionumber, $biblionumber, $biblionumber);
366 if ($branches_to_use && @$branches_to_use) {
367 $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
368 push @params, @$branches_to_use;
370 my $sth = $dbh->prepare($items_query);
371 $sth->execute(@params);
373 my $itm = $sth->fetchall_arrayref({});
375 my $rule = C4::Circulation::GetBranchItemRule($_->{homebranch}, $_->{itype});
376 $_->{holdallowed} = $rule->{holdallowed};
377 $_->{hold_fulfillment_policy} = $rule->{hold_fulfillment_policy};
381 =head2 _checkHoldPolicy
383 _checkHoldPolicy($item, $request)
385 check if item agrees with hold policies
389 sub _checkHoldPolicy {
390 my ( $item, $request ) = @_;
392 return 0 unless $item->{holdallowed} ne 'not_allowed';
395 if $item->{holdallowed} eq 'from_home_library'
396 && $item->{homebranch} ne $request->{borrowerbranch};
399 if $item->{'holdallowed'} eq 'from_local_hold_group'
400 && !Koha::Libraries->find( $item->{homebranch} )
401 ->validate_hold_sibling( { branchcode => $request->{borrowerbranch} } );
403 my $hold_fulfillment_policy = $item->{hold_fulfillment_policy};
406 if $hold_fulfillment_policy eq 'holdgroup'
407 && !Koha::Libraries->find( $item->{homebranch} )
408 ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
411 if $hold_fulfillment_policy eq 'homebranch'
412 && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
415 if $hold_fulfillment_policy eq 'holdingbranch'
416 && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
419 if $hold_fulfillment_policy eq 'patrongroup'
420 && !Koha::Libraries->find( $request->{borrowerbranch} )
421 ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
427 =head2 MapItemsToHoldRequests
429 MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
433 sub MapItemsToHoldRequests {
434 my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
436 # handle trival cases
437 return unless scalar(@$hold_requests) > 0;
438 return unless scalar(@$available_items) > 0;
440 # identify item-level requests
441 my %specific_items_requested = map { $_->{itemnumber} => 1 }
442 grep { defined($_->{itemnumber}) }
445 map { $_->{_object} = Koha::Items->find( $_->{itemnumber} ) } @$available_items;
447 map { $libraries->{$_->id} = $_ } Koha::Libraries->search->as_list;
449 # group available items by itemnumber
450 my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
452 # items already allocated
453 my %allocated_items = ();
455 # map of items to hold requests
458 # figure out which item-level requests can be filled
459 my $num_items_remaining = scalar(@$available_items);
461 # Look for Local Holds Priority matches first
462 if ( C4::Context->preference('LocalHoldsPriority') ) {
463 my $LocalHoldsPriorityPatronControl =
464 C4::Context->preference('LocalHoldsPriorityPatronControl');
465 my $LocalHoldsPriorityItemControl =
466 C4::Context->preference('LocalHoldsPriorityItemControl');
468 foreach my $request (@$hold_requests) {
469 last if $num_items_remaining == 0;
470 my $patron = Koha::Patrons->find($request->{borrowernumber});
471 next if $patron->category->exclude_from_local_holds_priority;
473 my $local_hold_match;
474 foreach my $item (@$available_items) {
475 next if $item->{_object}->exclude_from_local_holds_priority;
477 next unless _checkHoldPolicy($item, $request);
479 next if $request->{itemnumber} && $request->{itemnumber} != $item->{itemnumber};
481 next if $request->{item_group_id} && $item->{_object}->item_group && $item->{_object}->item_group->id ne $request->{item_group_id};
483 next unless $item->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
485 my $local_holds_priority_item_branchcode =
486 $item->{$LocalHoldsPriorityItemControl};
488 my $local_holds_priority_patron_branchcode =
489 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
490 ? $request->{branchcode}
491 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
492 ? $request->{borrowerbranch}
496 $local_holds_priority_item_branchcode eq
497 $local_holds_priority_patron_branchcode;
499 if ($local_hold_match) {
500 if ( exists $items_by_itemnumber{ $item->{itemnumber} }
501 and not exists $allocated_items{ $item->{itemnumber} }
502 and not $request->{allocated})
504 $item_map{ $item->{itemnumber} } = {
505 borrowernumber => $request->{borrowernumber},
506 biblionumber => $request->{biblionumber},
507 holdingbranch => $item->{holdingbranch},
508 pickup_branch => $request->{branchcode}
509 || $request->{borrowerbranch},
510 reserve_id => $request->{reserve_id},
511 item_level => $request->{item_level_hold},
512 reservedate => $request->{reservedate},
513 reservenotes => $request->{reservenotes},
515 $allocated_items{ $item->{itemnumber} }++;
516 $request->{allocated} = 1;
517 $num_items_remaining--;
524 foreach my $request (@$hold_requests) {
525 last if $num_items_remaining == 0;
526 next if $request->{allocated};
528 # is this an item-level request?
529 if (defined($request->{itemnumber})) {
530 # fill it if possible; if not skip it
532 exists $items_by_itemnumber{ $request->{itemnumber} }
533 and not exists $allocated_items{ $request->{itemnumber} }
534 and _checkHoldPolicy($items_by_itemnumber{ $request->{itemnumber} }, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
535 and ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
536 || $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} )
537 and ( !$request->{item_group_id} # If hold item_group is set, item's item_group must match
538 || ( $items_by_itemnumber{ $request->{itemnumber} }->{_object}->item_group
539 && $items_by_itemnumber{ $request->{itemnumber} }->{_object}->item_group->id eq $request->{item_group_id} ) )
540 and $items_by_itemnumber{ $request->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } )
545 $item_map{ $request->{itemnumber} } = {
546 borrowernumber => $request->{borrowernumber},
547 biblionumber => $request->{biblionumber},
548 holdingbranch => $items_by_itemnumber{ $request->{itemnumber} }->{holdingbranch},
549 pickup_branch => $request->{branchcode} || $request->{borrowerbranch},
550 reserve_id => $request->{reserve_id},
551 item_level => $request->{item_level_hold},
552 reservedate => $request->{reservedate},
553 reservenotes => $request->{reservenotes},
555 $allocated_items{ $request->{itemnumber} }++;
556 $num_items_remaining--;
559 # it's title-level request that will take up one item
560 $num_items_remaining--;
564 # group available items by branch
565 my %items_by_branch = ();
566 foreach my $item (@$available_items) {
567 next unless $item->{holdallowed} ne 'not_allowed';
569 push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
570 unless exists $allocated_items{ $item->{itemnumber} };
572 return \%item_map unless keys %items_by_branch;
574 # now handle the title-level requests
575 $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
577 foreach my $request (@$hold_requests) {
578 last if $num_items_remaining == 0;
579 next if $request->{allocated};
580 next if defined($request->{itemnumber}); # already handled these
582 # look for local match first
583 my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
584 my ($itemnumber, $holdingbranch);
586 my $holding_branch_items = $items_by_branch{$pickup_branch};
587 my $priority_branch = C4::Context->preference('HoldsQueuePrioritizeBranch') // 'homebranch';
588 if ( $holding_branch_items ) {
589 foreach my $item (@$holding_branch_items) {
590 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
593 $request->{borrowerbranch} eq $item->{$priority_branch}
594 && _checkHoldPolicy($item, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
595 && ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
596 || ( $request->{itemnumber} && ( $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} ) ) )
597 && ( !$request->{item_group_id} # If hold item_group is set, item's item_group must match
598 || ( $item->{_object}->item_group && $item->{_object}->item_group->id eq $request->{item_group_id} ) )
601 $itemnumber = $item->{itemnumber};
605 $holdingbranch = $pickup_branch;
607 elsif ($transport_cost_matrix) {
608 $pull_branches = [keys %items_by_branch];
609 $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
610 if ( $holdingbranch ) {
612 my $holding_branch_items = $items_by_branch{$holdingbranch};
613 foreach my $item (@$holding_branch_items) {
614 next if $request->{borrowerbranch} ne $item->{$priority_branch};
615 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
617 # Don't fill item level holds that contravene the hold pickup policy at this time
618 next unless _checkHoldPolicy($item, $request);
620 # If hold itemtype is set, item's itemtype must match
621 next unless ( !$request->{itemtype}
622 || $item->{itype} eq $request->{itemtype} );
624 # If hold item_group is set, item's item_group must match
626 !$request->{item_group_id}
627 || ( $item->{_object}->item_group
628 && $item->{_object}->item_group->id eq $request->{item_group_id} )
631 $itemnumber = $item->{itemnumber};
640 unless ($itemnumber) {
641 # not found yet, fall back to basics
642 if ($branches_to_use) {
643 $pull_branches = $branches_to_use;
645 $pull_branches = [keys %items_by_branch];
648 # Try picking items where the home and pickup branch match first
650 foreach my $branch (@$pull_branches) {
651 my $holding_branch_items = $items_by_branch{$branch}
654 $holdingbranch ||= $branch;
655 foreach my $item (@$holding_branch_items) {
656 next if $pickup_branch ne $item->{homebranch};
657 next unless _checkHoldPolicy($item, $request);
658 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
660 # If hold itemtype is set, item's itemtype must match
661 next unless ( !$request->{itemtype}
662 || $item->{itype} eq $request->{itemtype} );
664 # If hold item_group is set, item's item_group must match
666 !$request->{item_group_id}
667 || ( $item->{_object}->item_group
668 && $item->{_object}->item_group->id eq $request->{item_group_id} )
671 $itemnumber = $item->{itemnumber};
672 $holdingbranch = $branch;
677 # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight
678 unless ( $itemnumber || !$holdingbranch) {
679 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
680 next unless _checkHoldPolicy($current_item, $request); # Don't fill item level holds that contravene the hold pickup policy at this time
682 # If hold itemtype is set, item's itemtype must match
683 next unless ( !$request->{itemtype}
684 || $current_item->{itype} eq $request->{itemtype} );
686 next unless $items_by_itemnumber{ $current_item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
688 # If hold item_group is set, item's item_group must match
690 !$request->{item_group_id}
691 || ( $current_item->{_object}->item_group
692 && $current_item->{_object}->item_group->id eq $request->{item_group_id} )
696 $itemnumber = $current_item->{itemnumber};
697 last; # quit this loop as soon as we have a suitable item
701 # Now try for items for any item that can fill this hold
702 unless ( $itemnumber ) {
704 foreach my $branch (@$pull_branches) {
705 my $holding_branch_items = $items_by_branch{$branch}
708 foreach my $item (@$holding_branch_items) {
709 # Don't fill item level holds that contravene the hold pickup policy at this time
710 next unless _checkHoldPolicy($item, $request);
712 # If hold itemtype is set, item's itemtype must match
713 next unless ( !$request->{itemtype}
714 || $item->{itype} eq $request->{itemtype} );
716 # If hold item_group is set, item's item_group must match
718 !$request->{item_group_id}
719 || ( $item->{_object}->item_group
720 && $item->{_object}->item_group->id eq $request->{item_group_id} )
723 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
725 $itemnumber = $item->{itemnumber};
726 $holdingbranch = $branch;
734 my $holding_branch_items = $items_by_branch{$holdingbranch}
735 or die "Have $itemnumber, $holdingbranch, but no items!";
736 @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
737 delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
739 $item_map{$itemnumber} = {
740 borrowernumber => $request->{borrowernumber},
741 biblionumber => $request->{biblionumber},
742 holdingbranch => $holdingbranch,
743 pickup_branch => $pickup_branch,
744 reserve_id => $request->{reserve_id},
745 item_level => $request->{item_level_hold},
746 reservedate => $request->{reservedate},
747 reservenotes => $request->{reservenotes},
749 $num_items_remaining--;
755 =head2 CreatePickListFromItemMap
759 sub CreatePicklistFromItemMap {
760 my $item_map = shift;
762 my $dbh = C4::Context->dbh;
764 my $sth_load=$dbh->prepare("
765 INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
766 cardnumber,reservedate,title, itemcallnumber,
767 holdingbranch,pickbranch,notes, item_level_request)
768 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
771 foreach my $itemnumber (sort keys %$item_map) {
772 my $mapped_item = $item_map->{$itemnumber};
773 my $biblionumber = $mapped_item->{biblionumber};
774 my $borrowernumber = $mapped_item->{borrowernumber};
775 my $pickbranch = $mapped_item->{pickup_branch};
776 my $holdingbranch = $mapped_item->{holdingbranch};
777 my $reservedate = $mapped_item->{reservedate};
778 my $reservenotes = $mapped_item->{reservenotes};
779 my $item_level = $mapped_item->{item_level};
781 my $item = Koha::Items->find($itemnumber);
782 my $barcode = $item->barcode;
783 my $itemcallnumber = $item->itemcallnumber;
785 my $patron = Koha::Patrons->find( $borrowernumber );
786 my $cardnumber = $patron->cardnumber;
787 my $surname = $patron->surname;
788 my $firstname = $patron->firstname;
789 my $phone = $patron->phone;
791 my $biblio = Koha::Biblios->find( $biblionumber );
792 my $title = $biblio->title;
794 $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
795 $cardnumber, $reservedate, $title, $itemcallnumber,
796 $holdingbranch, $pickbranch, $reservenotes, $item_level);
800 =head2 AddToHoldTargetMap
804 sub AddToHoldTargetMap {
805 my $item_map = shift;
807 my $dbh = C4::Context->dbh;
808 my $schema = Koha::Database->new->schema;
811 INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request, reserve_id) VALUES (?, ?, ?, ?, ?, ?)
813 my $sth_insert = $dbh->prepare($insert_sql);
815 foreach my $itemnumber ( keys %$item_map ) {
816 my $mapped_item = $item_map->{$itemnumber};
819 $dbh->do( 'DELETE FROM hold_fill_targets WHERE itemnumber = ?', {}, $itemnumber );
820 $sth_insert->execute(
821 $mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
822 $mapped_item->{holdingbranch}, $mapped_item->{item_level}, $mapped_item->{reserve_id}
829 # Helper functions, not part of any interface
832 return $_[0] unless $_[0];
838 sub load_branches_to_pull_from {
839 my $use_transport_cost_matrix = shift;
843 unless ( $use_transport_cost_matrix ) {
844 my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight");
845 @branches_to_use = map { _trim($_) } split( /,/, $static_branch_list )
846 if $static_branch_list;
850 Koha::Database->new()->schema()->resultset('Branch')
851 ->get_column('branchcode')->all()
852 unless (@branches_to_use);
854 @branches_to_use = shuffle(@branches_to_use)
855 if C4::Context->preference("RandomizeHoldsQueueWeight");
857 my $today = dt_from_string();
858 if ( C4::Context->preference('HoldsQueueSkipClosed') ) {
859 @branches_to_use = grep {
860 !Koha::Calendar->new( branchcode => $_ )
861 ->is_holiday( $today )
865 return \@branches_to_use;
868 sub least_cost_branch {
871 my ($to, $from, $transport_cost_matrix) = @_;
873 # Nothing really spectacular: supply to branch, a list of potential from branches
874 # and find the minimum from - to value from the transport_cost_matrix
875 return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{$from->[0]}->{disable_transfer} != 1 );
877 # If the pickup library is in the list of libraries to pull from,
878 # return that library right away, it is obviously the least costly
879 return ($to) if any { $_ eq $to } @$from;
881 my ($least_cost, @branch);
883 my $cell = $transport_cost_matrix->{$to}{$_};
884 next if $cell->{disable_transfer};
886 my $cost = $cell->{cost};
887 next unless defined $cost; # XXX should this be reported?
889 unless (defined $least_cost) {
895 next if $cost > $least_cost;
897 if ($cost == $least_cost) {
908 # XXX return a random @branch with minimum cost instead of the first one;
909 # return $branch[0] if @branch == 1;
912 =head3 update_queue_for_biblio
914 my $result = update_queue_for_biblio(
916 biblio_id => $biblio_id,
917 [ branches_to_use => $branches_to_use,
918 transport_cost_matrix => $transport_cost_matrix,
920 unallocated => $unallocated, ]
924 Given a I<biblio_id>, this method calculates and sets the holds queue entries
925 for the biblio's holds, and the hold fill targets (items).
929 It return a hashref containing:
933 =item I<requests>: the pending holds count for the biblio.
935 =item I<available_items> the count of items that are available to fill holds for the biblio.
937 =item I<mapped_items> the total items that got mapped.
941 =head4 Optional parameters
945 =item I<branches_to_use> a list of branchcodes to be used to restrict which items can be used.
947 =item I<transport_cost_matrix> is the output of C<TransportCostMatrix>.
949 =item I<delete> tells the method to delete prior entries on the related tables for the biblio_id.
951 =item I<unallocated> tells the method to limit the holds to those not in the holds queue, should not
952 be passed at the same time as delete.
956 Note: All the optional parameters will be calculated in the method if omitted. They
957 are allowed to be passed to avoid calculating them many times inside loops.
961 sub update_queue_for_biblio {
963 my $biblio_id = $args->{biblio_id};
966 # We need to empty the queue for this biblio unless CreateQueue has emptied the entire queue for rebuilding
967 if ( $args->{delete} ) {
968 my $dbh = C4::Context->dbh;
970 $dbh->do("DELETE FROM tmp_holdsqueue WHERE biblionumber=$biblio_id");
971 $dbh->do("DELETE FROM hold_fill_targets WHERE biblionumber=$biblio_id");
974 my $hold_requests = GetPendingHoldRequestsForBib({ biblionumber => $biblio_id, unallocated => $args->{unallocated} });
975 $result->{requests} = scalar( @{$hold_requests} );
976 # No need to check anything else if there are no holds to fill
977 return $result unless $result->{requests};
979 my $branches_to_use = $args->{branches_to_use} // load_branches_to_pull_from( C4::Context->preference('UseTransportCostMatrix') );
980 my $transport_cost_matrix;
982 if ( !exists $args->{transport_cost_matrix}
983 && C4::Context->preference('UseTransportCostMatrix') ) {
984 $transport_cost_matrix = TransportCostMatrix();
986 $transport_cost_matrix = $args->{transport_cost_matrix};
989 my $available_items = GetItemsAvailableToFillHoldRequestsForBib( $biblio_id, $branches_to_use );
991 $result->{available_items} = scalar( @{$available_items} );
993 my $item_map = MapItemsToHoldRequests( $hold_requests, $available_items, $branches_to_use, $transport_cost_matrix );
994 $result->{mapped_items} = scalar( keys %{$item_map} );
997 CreatePicklistFromItemMap($item_map);
998 AddToHoldTargetMap($item_map);