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::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;
129 my @bind_params = ();
130 my $query = q/SELECT tmp_holdsqueue.*, biblio.author, items.ccode, items.itype, biblioitems.itemtype, items.location,
131 items.enumchron, items.cn_sort, biblioitems.publishercode,
132 biblio.copyrightdate, biblio.subtitle, biblio.medium,
133 biblio.part_number, biblio.part_name,
134 biblioitems.publicationyear, biblioitems.pages, biblioitems.size,
135 biblioitems.isbn, biblioitems.editionstatement, items.copynumber,
136 item_groups.item_group_id, item_groups.description AS item_group_description
138 JOIN biblio USING (biblionumber)
139 LEFT JOIN biblioitems USING (biblionumber)
140 LEFT JOIN items USING ( itemnumber)
141 LEFT JOIN item_group_items ON ( items.itemnumber = item_group_items.item_id )
142 LEFT JOIN item_groups ON ( item_group_items.item_group_id = item_groups.item_group_id )
145 if ($params->{branchlimit}) {
146 $query .="AND tmp_holdsqueue.holdingbranch = ? ";
147 push @bind_params, $params->{branchlimit};
149 if( $params->{itemtypeslimit} ) {
150 $query .=" AND items.itype = ? ";
151 push @bind_params, $params->{itemtypeslimit};
153 if( $params->{ccodeslimit} ) {
154 $query .=" AND items.ccode = ? ";
155 push @bind_params, $params->{ccodeslimit};
157 if( $params->{locationslimit} ) {
158 $query .=" AND items.location = ? ";
159 push @bind_params, $params->{locationslimit};
161 $query .= " ORDER BY ccode, location, cn_sort, author, title, pickbranch, reservedate";
162 my $sth = $dbh->prepare($query);
163 $sth->execute(@bind_params);
165 while ( my $row = $sth->fetchrow_hashref ){
166 # return the bib-level or item-level itype per syspref
167 if (!C4::Context->preference('item-level_itypes')) {
168 $row->{itype} = $row->{itemtype};
170 delete $row->{itemtype};
181 Top level function that turns reserves into tmp_holdsqueue and hold_fill_targets.
186 my $dbh = C4::Context->dbh;
188 $dbh->do("DELETE FROM tmp_holdsqueue"); # clear the old table for new info
189 $dbh->do("DELETE FROM hold_fill_targets");
192 my $total_requests = 0;
193 my $total_available_items = 0;
194 my $num_items_mapped = 0;
197 my $transport_cost_matrix;
198 my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix");
199 if ($use_transport_cost_matrix) {
200 $transport_cost_matrix = TransportCostMatrix();
201 unless (keys %$transport_cost_matrix) {
202 warn "UseTransportCostMatrix set to yes, but matrix not populated";
203 undef $transport_cost_matrix;
207 $branches_to_use = load_branches_to_pull_from($use_transport_cost_matrix);
209 my $bibs_with_pending_requests = GetBibsWithPendingHoldRequests();
211 foreach my $biblionumber (@$bibs_with_pending_requests) {
215 my $result = update_queue_for_biblio(
216 { biblio_id => $biblionumber,
217 branches_to_use => $branches_to_use,
218 transport_cost_matrix => $transport_cost_matrix,
222 $total_requests += $result->{requests};
223 $total_available_items += $result->{available_items};
224 $num_items_mapped += $result->{mapped_items};
228 =head2 GetBibsWithPendingHoldRequests
230 my $biblionumber_aref = GetBibsWithPendingHoldRequests();
232 Return an arrayref of the biblionumbers of all bibs
233 that have one or more unfilled hold requests.
237 sub GetBibsWithPendingHoldRequests {
238 my $dbh = C4::Context->dbh;
240 my $bib_query = "SELECT DISTINCT biblionumber
244 AND reservedate <= CURRENT_DATE()
247 my $sth = $dbh->prepare($bib_query);
250 my $biblionumbers = $sth->fetchall_arrayref();
252 return [ map { $_->[0] } @$biblionumbers ];
255 =head2 GetPendingHoldRequestsForBib
257 my $requests = GetPendingHoldRequestsForBib($biblionumber);
259 Returns an arrayref of hashrefs to pending, unfilled hold requests
260 on the bib identified by $biblionumber. The following keys
261 are present in each hashref:
272 The arrayref is sorted in order of increasing priority.
276 sub GetPendingHoldRequestsForBib {
277 my $biblionumber = shift;
279 my $dbh = C4::Context->dbh;
281 my $request_query = "SELECT biblionumber, borrowernumber, itemnumber, priority, reserve_id, reserves.branchcode,
282 reservedate, reservenotes, borrowers.branchcode AS borrowerbranch, itemtype, item_level_hold, item_group_id
284 JOIN borrowers USING (borrowernumber)
285 WHERE biblionumber = ?
288 AND reservedate <= CURRENT_DATE()
291 my $sth = $dbh->prepare($request_query);
292 $sth->execute($biblionumber);
294 my $requests = $sth->fetchall_arrayref({});
299 =head2 GetItemsAvailableToFillHoldRequestsForBib
301 my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_ar);
303 Returns an arrayref of items available to fill hold requests
304 for the bib identified by C<$biblionumber>. An item is available
305 to fill a hold request if and only if:
308 * it is not withdrawn
309 * it is not marked notforloan
310 * it is not currently in transit
312 * it is not sitting on the hold shelf
313 * it is not damaged (unless AllowHoldsOnDamagedItems is on)
317 sub GetItemsAvailableToFillHoldRequestsForBib {
318 my ($biblionumber, $branches_to_use) = @_;
320 my $dbh = C4::Context->dbh;
321 my $items_query = "SELECT items.itemnumber, homebranch, holdingbranch, itemtypes.itemtype AS itype
324 if (C4::Context->preference('item-level_itypes')) {
325 $items_query .= "LEFT JOIN itemtypes ON (itemtypes.itemtype = items.itype) ";
327 $items_query .= "JOIN biblioitems USING (biblioitemnumber)
328 LEFT JOIN itemtypes USING (itemtype) ";
330 $items_query .= " LEFT JOIN branchtransfers ON (
331 items.itemnumber = branchtransfers.itemnumber
332 AND branchtransfers.datearrived IS NULL AND branchtransfers.datecancelled IS NULL
334 $items_query .= " WHERE items.notforloan = 0
335 AND holdingbranch IS NOT NULL
338 $items_query .= " AND damaged = 0" unless C4::Context->preference('AllowHoldsOnDamagedItems');
339 $items_query .= " AND items.onloan IS NULL
340 AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
341 AND items.itemnumber NOT IN (
344 WHERE biblionumber = ?
345 AND itemnumber IS NOT NULL
346 AND (found IS NOT NULL OR priority = 0)
348 AND items.biblionumber = ?
349 AND branchtransfers.itemnumber IS NULL";
351 my @params = ($biblionumber, $biblionumber);
352 if ($branches_to_use && @$branches_to_use) {
353 $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
354 push @params, @$branches_to_use;
356 my $sth = $dbh->prepare($items_query);
357 $sth->execute(@params);
359 my $itm = $sth->fetchall_arrayref({});
361 my $rule = C4::Circulation::GetBranchItemRule($_->{homebranch}, $_->{itype});
362 $_->{holdallowed} = $rule->{holdallowed};
363 $_->{hold_fulfillment_policy} = $rule->{hold_fulfillment_policy};
367 =head2 _checkHoldPolicy
369 _checkHoldPolicy($item, $request)
371 check if item agrees with hold policies
375 sub _checkHoldPolicy {
376 my ( $item, $request ) = @_;
378 return 0 unless $item->{holdallowed} ne 'not_allowed';
381 if $item->{holdallowed} eq 'from_home_library'
382 && $item->{homebranch} ne $request->{borrowerbranch};
385 if $item->{'holdallowed'} eq 'from_local_hold_group'
386 && !Koha::Libraries->find( $item->{homebranch} )
387 ->validate_hold_sibling( { branchcode => $request->{borrowerbranch} } );
389 my $hold_fulfillment_policy = $item->{hold_fulfillment_policy};
392 if $hold_fulfillment_policy eq 'holdgroup'
393 && !Koha::Libraries->find( $item->{homebranch} )
394 ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
397 if $hold_fulfillment_policy eq 'homebranch'
398 && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
401 if $hold_fulfillment_policy eq 'holdingbranch'
402 && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
405 if $hold_fulfillment_policy eq 'patrongroup'
406 && !Koha::Libraries->find( $request->{borrowerbranch} )
407 ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
413 =head2 MapItemsToHoldRequests
415 MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
419 sub MapItemsToHoldRequests {
420 my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
422 # handle trival cases
423 return unless scalar(@$hold_requests) > 0;
424 return unless scalar(@$available_items) > 0;
426 # identify item-level requests
427 my %specific_items_requested = map { $_->{itemnumber} => 1 }
428 grep { defined($_->{itemnumber}) }
431 map { $_->{_object} = Koha::Items->find( $_->{itemnumber} ) } @$available_items;
433 map { $libraries->{$_->id} = $_ } Koha::Libraries->search->as_list;
435 # group available items by itemnumber
436 my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
438 # items already allocated
439 my %allocated_items = ();
441 # map of items to hold requests
444 # figure out which item-level requests can be filled
445 my $num_items_remaining = scalar(@$available_items);
447 # Look for Local Holds Priority matches first
448 if ( C4::Context->preference('LocalHoldsPriority') ) {
449 my $LocalHoldsPriorityPatronControl =
450 C4::Context->preference('LocalHoldsPriorityPatronControl');
451 my $LocalHoldsPriorityItemControl =
452 C4::Context->preference('LocalHoldsPriorityItemControl');
454 foreach my $request (@$hold_requests) {
455 last if $num_items_remaining == 0;
456 my $patron = Koha::Patrons->find($request->{borrowernumber});
457 next if $patron->category->exclude_from_local_holds_priority;
459 my $local_hold_match;
460 foreach my $item (@$available_items) {
461 next if $item->{_object}->exclude_from_local_holds_priority;
463 next unless _checkHoldPolicy($item, $request);
465 next if $request->{itemnumber} && $request->{itemnumber} != $item->{itemnumber};
467 next if $request->{item_group_id} && $item->{_object}->item_group && $item->{_object}->item_group->id ne $request->{item_group_id};
469 next unless $item->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
471 my $local_holds_priority_item_branchcode =
472 $item->{$LocalHoldsPriorityItemControl};
474 my $local_holds_priority_patron_branchcode =
475 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
476 ? $request->{branchcode}
477 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
478 ? $request->{borrowerbranch}
482 $local_holds_priority_item_branchcode eq
483 $local_holds_priority_patron_branchcode;
485 if ($local_hold_match) {
486 if ( exists $items_by_itemnumber{ $item->{itemnumber} }
487 and not exists $allocated_items{ $item->{itemnumber} }
488 and not $request->{allocated})
490 $item_map{ $item->{itemnumber} } = {
491 borrowernumber => $request->{borrowernumber},
492 biblionumber => $request->{biblionumber},
493 holdingbranch => $item->{holdingbranch},
494 pickup_branch => $request->{branchcode}
495 || $request->{borrowerbranch},
496 reserve_id => $request->{reserve_id},
497 item_level => $request->{item_level_hold},
498 reservedate => $request->{reservedate},
499 reservenotes => $request->{reservenotes},
501 $allocated_items{ $item->{itemnumber} }++;
502 $request->{allocated} = 1;
503 $num_items_remaining--;
510 foreach my $request (@$hold_requests) {
511 last if $num_items_remaining == 0;
512 next if $request->{allocated};
514 # is this an item-level request?
515 if (defined($request->{itemnumber})) {
516 # fill it if possible; if not skip it
518 exists $items_by_itemnumber{ $request->{itemnumber} }
519 and not exists $allocated_items{ $request->{itemnumber} }
520 and _checkHoldPolicy($items_by_itemnumber{ $request->{itemnumber} }, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
521 and ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
522 || $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} )
523 and ( !$request->{item_group_id} # If hold item_group is set, item's item_group must match
524 || ( $items_by_itemnumber{ $request->{itemnumber} }->{_object}->item_group
525 && $items_by_itemnumber{ $request->{itemnumber} }->{_object}->item_group->id eq $request->{item_group_id} ) )
526 and $items_by_itemnumber{ $request->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } )
531 $item_map{ $request->{itemnumber} } = {
532 borrowernumber => $request->{borrowernumber},
533 biblionumber => $request->{biblionumber},
534 holdingbranch => $items_by_itemnumber{ $request->{itemnumber} }->{holdingbranch},
535 pickup_branch => $request->{branchcode} || $request->{borrowerbranch},
536 reserve_id => $request->{reserve_id},
537 item_level => $request->{item_level_hold},
538 reservedate => $request->{reservedate},
539 reservenotes => $request->{reservenotes},
541 $allocated_items{ $request->{itemnumber} }++;
542 $num_items_remaining--;
545 # it's title-level request that will take up one item
546 $num_items_remaining--;
550 # group available items by branch
551 my %items_by_branch = ();
552 foreach my $item (@$available_items) {
553 next unless $item->{holdallowed} ne 'not_allowed';
555 push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
556 unless exists $allocated_items{ $item->{itemnumber} };
558 return \%item_map unless keys %items_by_branch;
560 # now handle the title-level requests
561 $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
563 foreach my $request (@$hold_requests) {
564 last if $num_items_remaining == 0;
565 next if $request->{allocated};
566 next if defined($request->{itemnumber}); # already handled these
568 # look for local match first
569 my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
570 my ($itemnumber, $holdingbranch);
572 my $holding_branch_items = $items_by_branch{$pickup_branch};
573 my $priority_branch = C4::Context->preference('HoldsQueuePrioritizeBranch') // 'homebranch';
574 if ( $holding_branch_items ) {
575 foreach my $item (@$holding_branch_items) {
576 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
579 $request->{borrowerbranch} eq $item->{$priority_branch}
580 && _checkHoldPolicy($item, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
581 && ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
582 || ( $request->{itemnumber} && ( $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} ) ) )
583 && ( !$request->{item_group_id} # If hold item_group is set, item's item_group must match
584 || ( $item->{_object}->item_group && $item->{_object}->item_group->id eq $request->{item_group_id} ) )
587 $itemnumber = $item->{itemnumber};
591 $holdingbranch = $pickup_branch;
593 elsif ($transport_cost_matrix) {
594 $pull_branches = [keys %items_by_branch];
595 $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
596 if ( $holdingbranch ) {
598 my $holding_branch_items = $items_by_branch{$holdingbranch};
599 foreach my $item (@$holding_branch_items) {
600 next if $request->{borrowerbranch} ne $item->{$priority_branch};
601 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
603 # Don't fill item level holds that contravene the hold pickup policy at this time
604 next unless _checkHoldPolicy($item, $request);
606 # If hold itemtype is set, item's itemtype must match
607 next unless ( !$request->{itemtype}
608 || $item->{itype} eq $request->{itemtype} );
610 # If hold item_group is set, item's item_group must match
612 !$request->{item_group_id}
613 || ( $item->{_object}->item_group
614 && $item->{_object}->item_group->id eq $request->{item_group_id} )
617 $itemnumber = $item->{itemnumber};
626 unless ($itemnumber) {
627 # not found yet, fall back to basics
628 if ($branches_to_use) {
629 $pull_branches = $branches_to_use;
631 $pull_branches = [keys %items_by_branch];
634 # Try picking items where the home and pickup branch match first
636 foreach my $branch (@$pull_branches) {
637 my $holding_branch_items = $items_by_branch{$branch}
640 $holdingbranch ||= $branch;
641 foreach my $item (@$holding_branch_items) {
642 next if $pickup_branch ne $item->{homebranch};
643 next unless _checkHoldPolicy($item, $request);
644 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
646 # If hold itemtype is set, item's itemtype must match
647 next unless ( !$request->{itemtype}
648 || $item->{itype} eq $request->{itemtype} );
650 # If hold item_group is set, item's item_group must match
652 !$request->{item_group_id}
653 || ( $item->{_object}->item_group
654 && $item->{_object}->item_group->id eq $request->{item_group_id} )
657 $itemnumber = $item->{itemnumber};
658 $holdingbranch = $branch;
663 # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight
664 unless ( $itemnumber || !$holdingbranch) {
665 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
666 next unless _checkHoldPolicy($current_item, $request); # Don't fill item level holds that contravene the hold pickup policy at this time
668 # If hold itemtype is set, item's itemtype must match
669 next unless ( !$request->{itemtype}
670 || $current_item->{itype} eq $request->{itemtype} );
672 next unless $items_by_itemnumber{ $current_item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
674 # If hold item_group is set, item's item_group must match
676 !$request->{item_group_id}
677 || ( $current_item->{_object}->item_group
678 && $current_item->{_object}->item_group->id eq $request->{item_group_id} )
682 $itemnumber = $current_item->{itemnumber};
683 last; # quit this loop as soon as we have a suitable item
687 # Now try for items for any item that can fill this hold
688 unless ( $itemnumber ) {
690 foreach my $branch (@$pull_branches) {
691 my $holding_branch_items = $items_by_branch{$branch}
694 foreach my $item (@$holding_branch_items) {
695 # Don't fill item level holds that contravene the hold pickup policy at this time
696 next unless _checkHoldPolicy($item, $request);
698 # If hold itemtype is set, item's itemtype must match
699 next unless ( !$request->{itemtype}
700 || $item->{itype} eq $request->{itemtype} );
702 # If hold item_group is set, item's item_group must match
704 !$request->{item_group_id}
705 || ( $item->{_object}->item_group
706 && $item->{_object}->item_group->id eq $request->{item_group_id} )
709 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
711 $itemnumber = $item->{itemnumber};
712 $holdingbranch = $branch;
720 my $holding_branch_items = $items_by_branch{$holdingbranch}
721 or die "Have $itemnumber, $holdingbranch, but no items!";
722 @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
723 delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
725 $item_map{$itemnumber} = {
726 borrowernumber => $request->{borrowernumber},
727 biblionumber => $request->{biblionumber},
728 holdingbranch => $holdingbranch,
729 pickup_branch => $pickup_branch,
730 reserve_id => $request->{reserve_id},
731 item_level => $request->{item_level_hold},
732 reservedate => $request->{reservedate},
733 reservenotes => $request->{reservenotes},
735 $num_items_remaining--;
741 =head2 CreatePickListFromItemMap
745 sub CreatePicklistFromItemMap {
746 my $item_map = shift;
748 my $dbh = C4::Context->dbh;
750 my $sth_load=$dbh->prepare("
751 INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
752 cardnumber,reservedate,title, itemcallnumber,
753 holdingbranch,pickbranch,notes, item_level_request)
754 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
757 foreach my $itemnumber (sort keys %$item_map) {
758 my $mapped_item = $item_map->{$itemnumber};
759 my $biblionumber = $mapped_item->{biblionumber};
760 my $borrowernumber = $mapped_item->{borrowernumber};
761 my $pickbranch = $mapped_item->{pickup_branch};
762 my $holdingbranch = $mapped_item->{holdingbranch};
763 my $reservedate = $mapped_item->{reservedate};
764 my $reservenotes = $mapped_item->{reservenotes};
765 my $item_level = $mapped_item->{item_level};
767 my $item = Koha::Items->find($itemnumber);
768 my $barcode = $item->barcode;
769 my $itemcallnumber = $item->itemcallnumber;
771 my $patron = Koha::Patrons->find( $borrowernumber );
772 my $cardnumber = $patron->cardnumber;
773 my $surname = $patron->surname;
774 my $firstname = $patron->firstname;
775 my $phone = $patron->phone;
777 my $biblio = Koha::Biblios->find( $biblionumber );
778 my $title = $biblio->title;
780 $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
781 $cardnumber, $reservedate, $title, $itemcallnumber,
782 $holdingbranch, $pickbranch, $reservenotes, $item_level);
786 =head2 AddToHoldTargetMap
790 sub AddToHoldTargetMap {
791 my $item_map = shift;
793 my $dbh = C4::Context->dbh;
796 INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request, reserve_id)
797 VALUES (?, ?, ?, ?, ?, ?)
799 my $sth_insert = $dbh->prepare($insert_sql);
801 foreach my $itemnumber (keys %$item_map) {
802 my $mapped_item = $item_map->{$itemnumber};
803 $sth_insert->execute($mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
804 $mapped_item->{holdingbranch}, $mapped_item->{item_level}, $mapped_item->{reserve_id});
808 # Helper functions, not part of any interface
811 return $_[0] unless $_[0];
817 sub load_branches_to_pull_from {
818 my $use_transport_cost_matrix = shift;
822 unless ( $use_transport_cost_matrix ) {
823 my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight");
824 @branches_to_use = map { _trim($_) } split( /,/, $static_branch_list )
825 if $static_branch_list;
829 Koha::Database->new()->schema()->resultset('Branch')
830 ->get_column('branchcode')->all()
831 unless (@branches_to_use);
833 @branches_to_use = shuffle(@branches_to_use)
834 if C4::Context->preference("RandomizeHoldsQueueWeight");
836 my $today = dt_from_string();
837 if ( C4::Context->preference('HoldsQueueSkipClosed') ) {
838 @branches_to_use = grep {
839 !Koha::Calendar->new( branchcode => $_ )
840 ->is_holiday( $today )
844 return \@branches_to_use;
847 sub least_cost_branch {
850 my ($to, $from, $transport_cost_matrix) = @_;
852 # Nothing really spectacular: supply to branch, a list of potential from branches
853 # and find the minimum from - to value from the transport_cost_matrix
854 return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{$from->[0]}->{disable_transfer} != 1 );
856 # If the pickup library is in the list of libraries to pull from,
857 # return that library right away, it is obviously the least costly
858 return ($to) if any { $_ eq $to } @$from;
860 my ($least_cost, @branch);
862 my $cell = $transport_cost_matrix->{$to}{$_};
863 next if $cell->{disable_transfer};
865 my $cost = $cell->{cost};
866 next unless defined $cost; # XXX should this be reported?
868 unless (defined $least_cost) {
874 next if $cost > $least_cost;
876 if ($cost == $least_cost) {
887 # XXX return a random @branch with minimum cost instead of the first one;
888 # return $branch[0] if @branch == 1;
891 =head3 update_queue_for_biblio
893 my $result = update_queue_for_biblio(
895 biblio_id => $biblio_id,
896 [ branches_to_use => $branches_to_use,
897 transport_cost_matrix => $transport_cost_matrix,
902 Given a I<biblio_id>, this method calculates and sets the holds queue entries
903 for the biblio's holds, and the hold fill targets (items).
907 It return a hashref containing:
911 =item I<requests>: the pending holds count for the biblio.
913 =item I<available_items> the count of items that are available to fill holds for the biblio.
915 =item I<mapped_items> the total items that got mapped.
919 =head4 Optional parameters
923 =item I<branches_to_use> a list of branchcodes to be used to restrict which items can be used.
925 =item I<transport_cost_matrix> is the output of C<TransportCostMatrix>.
927 =item I<delete> tells the method to delete prior entries on the related tables for the biblio_id.
931 Note: All the optional parameters will be calculated in the method if omitted. They
932 are allowed to be passed to avoid calculating them many times inside loops.
936 sub update_queue_for_biblio {
938 my $biblio_id = $args->{biblio_id};
941 # We need to empty the queue for this biblio unless CreateQueue has emptied the entire queue for rebuilding
942 if ( $args->{delete} ) {
943 my $dbh = C4::Context->dbh;
945 $dbh->do("DELETE FROM tmp_holdsqueue WHERE biblionumber=$biblio_id");
946 $dbh->do("DELETE FROM hold_fill_targets WHERE biblionumber=$biblio_id");
949 my $hold_requests = GetPendingHoldRequestsForBib($biblio_id);
950 $result->{requests} = scalar( @{$hold_requests} );
951 # No need to check anything else if there are no holds to fill
952 return $result unless $result->{requests};
954 my $branches_to_use = $args->{branches_to_use} // load_branches_to_pull_from( C4::Context->preference('UseTransportCostMatrix') );
955 my $transport_cost_matrix;
957 if ( !exists $args->{transport_cost_matrix}
958 && C4::Context->preference('UseTransportCostMatrix') ) {
959 $transport_cost_matrix = TransportCostMatrix();
961 $transport_cost_matrix = $args->{transport_cost_matrix};
964 my $available_items = GetItemsAvailableToFillHoldRequestsForBib( $biblio_id, $branches_to_use );
966 $result->{available_items} = scalar( @{$available_items} );
968 my $item_map = MapItemsToHoldRequests( $hold_requests, $available_items, $branches_to_use, $transport_cost_matrix );
969 $result->{mapped_items} = scalar( keys %{$item_map} );
972 CreatePicklistFromItemMap($item_map);
973 AddToHoldTargetMap($item_map);