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( GetTransfers 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
136 JOIN biblio USING (biblionumber)
137 LEFT JOIN biblioitems USING (biblionumber)
138 LEFT JOIN items USING ( itemnumber)
141 if ($params->{branchlimit}) {
142 $query .="AND tmp_holdsqueue.holdingbranch = ? ";
143 push @bind_params, $params->{branchlimit};
145 if( $params->{itemtypeslimit} ) {
146 $query .=" AND items.itype = ? ";
147 push @bind_params, $params->{itemtypeslimit};
149 if( $params->{ccodeslimit} ) {
150 $query .=" AND items.ccode = ? ";
151 push @bind_params, $params->{ccodeslimit};
153 if( $params->{locationslimit} ) {
154 $query .=" AND items.location = ? ";
155 push @bind_params, $params->{locationslimit};
157 $query .= " ORDER BY ccode, location, cn_sort, author, title, pickbranch, reservedate";
158 my $sth = $dbh->prepare($query);
159 $sth->execute(@bind_params);
161 while ( my $row = $sth->fetchrow_hashref ){
162 # return the bib-level or item-level itype per syspref
163 if (!C4::Context->preference('item-level_itypes')) {
164 $row->{itype} = $row->{itemtype};
166 delete $row->{itemtype};
177 Top level function that turns reserves into tmp_holdsqueue and hold_fill_targets.
182 my $dbh = C4::Context->dbh;
184 $dbh->do("DELETE FROM tmp_holdsqueue"); # clear the old table for new info
185 $dbh->do("DELETE FROM hold_fill_targets");
188 my $total_requests = 0;
189 my $total_available_items = 0;
190 my $num_items_mapped = 0;
193 my $transport_cost_matrix;
194 my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix");
195 if ($use_transport_cost_matrix) {
196 $transport_cost_matrix = TransportCostMatrix();
197 unless (keys %$transport_cost_matrix) {
198 warn "UseTransportCostMatrix set to yes, but matrix not populated";
199 undef $transport_cost_matrix;
203 $branches_to_use = load_branches_to_pull_from($use_transport_cost_matrix);
205 my $bibs_with_pending_requests = GetBibsWithPendingHoldRequests();
207 foreach my $biblionumber (@$bibs_with_pending_requests) {
211 my $result = update_queue_for_biblio(
212 { biblio_id => $biblionumber,
213 branches_to_use => $branches_to_use,
214 transport_cost_matrix => $transport_cost_matrix,
218 $total_requests += $result->{requests};
219 $total_available_items += $result->{available_items};
220 $num_items_mapped += $result->{mapped_items};
224 =head2 GetBibsWithPendingHoldRequests
226 my $biblionumber_aref = GetBibsWithPendingHoldRequests();
228 Return an arrayref of the biblionumbers of all bibs
229 that have one or more unfilled hold requests.
233 sub GetBibsWithPendingHoldRequests {
234 my $dbh = C4::Context->dbh;
236 my $bib_query = "SELECT DISTINCT biblionumber
240 AND reservedate <= CURRENT_DATE()
243 my $sth = $dbh->prepare($bib_query);
246 my $biblionumbers = $sth->fetchall_arrayref();
248 return [ map { $_->[0] } @$biblionumbers ];
251 =head2 GetPendingHoldRequestsForBib
253 my $requests = GetPendingHoldRequestsForBib($biblionumber);
255 Returns an arrayref of hashrefs to pending, unfilled hold requests
256 on the bib identified by $biblionumber. The following keys
257 are present in each hashref:
268 The arrayref is sorted in order of increasing priority.
272 sub GetPendingHoldRequestsForBib {
273 my $biblionumber = shift;
275 my $dbh = C4::Context->dbh;
277 my $request_query = "SELECT biblionumber, borrowernumber, itemnumber, priority, reserve_id, reserves.branchcode,
278 reservedate, reservenotes, borrowers.branchcode AS borrowerbranch, itemtype, item_level_hold
280 JOIN borrowers USING (borrowernumber)
281 WHERE biblionumber = ?
284 AND reservedate <= CURRENT_DATE()
287 my $sth = $dbh->prepare($request_query);
288 $sth->execute($biblionumber);
290 my $requests = $sth->fetchall_arrayref({});
295 =head2 GetItemsAvailableToFillHoldRequestsForBib
297 my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_ar);
299 Returns an arrayref of items available to fill hold requests
300 for the bib identified by C<$biblionumber>. An item is available
301 to fill a hold request if and only if:
304 * it is not withdrawn
305 * it is not marked notforloan
306 * it is not currently in transit
308 * it is not sitting on the hold shelf
309 * it is not damaged (unless AllowHoldsOnDamagedItems is on)
313 sub GetItemsAvailableToFillHoldRequestsForBib {
314 my ($biblionumber, $branches_to_use) = @_;
316 my $dbh = C4::Context->dbh;
317 my $items_query = "SELECT itemnumber, homebranch, holdingbranch, itemtypes.itemtype AS itype
320 if (C4::Context->preference('item-level_itypes')) {
321 $items_query .= "LEFT JOIN itemtypes ON (itemtypes.itemtype = items.itype) ";
323 $items_query .= "JOIN biblioitems USING (biblioitemnumber)
324 LEFT JOIN itemtypes USING (itemtype) ";
326 $items_query .= "WHERE items.notforloan = 0
327 AND holdingbranch IS NOT NULL
330 $items_query .= " AND damaged = 0" unless C4::Context->preference('AllowHoldsOnDamagedItems');
331 $items_query .= " AND items.onloan IS NULL
332 AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
333 AND itemnumber NOT IN (
336 WHERE biblionumber = ?
337 AND itemnumber IS NOT NULL
338 AND (found IS NOT NULL OR priority = 0)
340 AND items.biblionumber = ?";
342 my @params = ($biblionumber, $biblionumber);
343 if ($branches_to_use && @$branches_to_use) {
344 $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
345 push @params, @$branches_to_use;
347 my $sth = $dbh->prepare($items_query);
348 $sth->execute(@params);
350 my $itm = $sth->fetchall_arrayref({});
351 my @items = grep { ! scalar C4::Circulation::GetTransfers($_->{itemnumber}) } @$itm;
353 my $rule = C4::Circulation::GetBranchItemRule($_->{homebranch}, $_->{itype});
354 $_->{holdallowed} = $rule->{holdallowed};
355 $_->{hold_fulfillment_policy} = $rule->{hold_fulfillment_policy};
359 =head2 _checkHoldPolicy
361 _checkHoldPolicy($item, $request)
363 check if item agrees with hold policies
367 sub _checkHoldPolicy {
368 my ( $item, $request ) = @_;
370 return 0 unless $item->{holdallowed} ne 'not_allowed';
373 if $item->{holdallowed} eq 'from_home_library'
374 && $item->{homebranch} ne $request->{borrowerbranch};
377 if $item->{'holdallowed'} eq 'from_local_hold_group'
378 && !Koha::Libraries->find( $item->{homebranch} )
379 ->validate_hold_sibling( { branchcode => $request->{borrowerbranch} } );
381 my $hold_fulfillment_policy = $item->{hold_fulfillment_policy};
384 if $hold_fulfillment_policy eq 'holdgroup'
385 && !Koha::Libraries->find( $item->{homebranch} )
386 ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
389 if $hold_fulfillment_policy eq 'homebranch'
390 && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
393 if $hold_fulfillment_policy eq 'holdingbranch'
394 && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
397 if $hold_fulfillment_policy eq 'patrongroup'
398 && !Koha::Libraries->find( $request->{borrowerbranch} )
399 ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
405 =head2 MapItemsToHoldRequests
407 MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
411 sub MapItemsToHoldRequests {
412 my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
414 # handle trival cases
415 return unless scalar(@$hold_requests) > 0;
416 return unless scalar(@$available_items) > 0;
418 # identify item-level requests
419 my %specific_items_requested = map { $_->{itemnumber} => 1 }
420 grep { defined($_->{itemnumber}) }
423 map { $_->{_object} = Koha::Items->find( $_->{itemnumber} ) } @$available_items;
425 map { $libraries->{$_->id} = $_ } Koha::Libraries->search->as_list;
427 # group available items by itemnumber
428 my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
430 # items already allocated
431 my %allocated_items = ();
433 # map of items to hold requests
436 # figure out which item-level requests can be filled
437 my $num_items_remaining = scalar(@$available_items);
439 # Look for Local Holds Priority matches first
440 if ( C4::Context->preference('LocalHoldsPriority') ) {
441 my $LocalHoldsPriorityPatronControl =
442 C4::Context->preference('LocalHoldsPriorityPatronControl');
443 my $LocalHoldsPriorityItemControl =
444 C4::Context->preference('LocalHoldsPriorityItemControl');
446 foreach my $request (@$hold_requests) {
447 last if $num_items_remaining == 0;
448 my $patron = Koha::Patrons->find($request->{borrowernumber});
449 next if $patron->category->exclude_from_local_holds_priority;
451 my $local_hold_match;
452 foreach my $item (@$available_items) {
453 next if $item->{_object}->exclude_from_local_holds_priority;
455 next unless _checkHoldPolicy($item, $request);
457 next if $request->{itemnumber} && $request->{itemnumber} != $item->{itemnumber};
459 next unless $item->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
461 my $local_holds_priority_item_branchcode =
462 $item->{$LocalHoldsPriorityItemControl};
464 my $local_holds_priority_patron_branchcode =
465 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
466 ? $request->{branchcode}
467 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
468 ? $request->{borrowerbranch}
472 $local_holds_priority_item_branchcode eq
473 $local_holds_priority_patron_branchcode;
475 if ($local_hold_match) {
476 if ( exists $items_by_itemnumber{ $item->{itemnumber} }
477 and not exists $allocated_items{ $item->{itemnumber} }
478 and not $request->{allocated})
480 $item_map{ $item->{itemnumber} } = {
481 borrowernumber => $request->{borrowernumber},
482 biblionumber => $request->{biblionumber},
483 holdingbranch => $item->{holdingbranch},
484 pickup_branch => $request->{branchcode}
485 || $request->{borrowerbranch},
486 reserve_id => $request->{reserve_id},
487 item_level => $request->{item_level_hold},
488 reservedate => $request->{reservedate},
489 reservenotes => $request->{reservenotes},
491 $allocated_items{ $item->{itemnumber} }++;
492 $request->{allocated} = 1;
493 $num_items_remaining--;
500 foreach my $request (@$hold_requests) {
501 last if $num_items_remaining == 0;
502 next if $request->{allocated};
504 # is this an item-level request?
505 if (defined($request->{itemnumber})) {
506 # fill it if possible; if not skip it
508 exists $items_by_itemnumber{ $request->{itemnumber} }
509 and not exists $allocated_items{ $request->{itemnumber} }
510 and _checkHoldPolicy($items_by_itemnumber{ $request->{itemnumber} }, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
511 and ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
512 || $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} )
514 and $items_by_itemnumber{ $request->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } )
519 $item_map{ $request->{itemnumber} } = {
520 borrowernumber => $request->{borrowernumber},
521 biblionumber => $request->{biblionumber},
522 holdingbranch => $items_by_itemnumber{ $request->{itemnumber} }->{holdingbranch},
523 pickup_branch => $request->{branchcode} || $request->{borrowerbranch},
524 reserve_id => $request->{reserve_id},
525 item_level => $request->{item_level_hold},
526 reservedate => $request->{reservedate},
527 reservenotes => $request->{reservenotes},
529 $allocated_items{ $request->{itemnumber} }++;
530 $num_items_remaining--;
533 # it's title-level request that will take up one item
534 $num_items_remaining--;
538 # group available items by branch
539 my %items_by_branch = ();
540 foreach my $item (@$available_items) {
541 next unless $item->{holdallowed} ne 'not_allowed';
543 push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
544 unless exists $allocated_items{ $item->{itemnumber} };
546 return \%item_map unless keys %items_by_branch;
548 # now handle the title-level requests
549 $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
551 foreach my $request (@$hold_requests) {
552 last if $num_items_remaining == 0;
553 next if $request->{allocated};
554 next if defined($request->{itemnumber}); # already handled these
556 # look for local match first
557 my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
558 my ($itemnumber, $holdingbranch);
560 my $holding_branch_items = $items_by_branch{$pickup_branch};
561 if ( $holding_branch_items ) {
562 foreach my $item (@$holding_branch_items) {
563 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
566 $request->{borrowerbranch} eq $item->{homebranch}
567 && _checkHoldPolicy($item, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
568 && ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
569 || ( $request->{itemnumber} && ( $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} ) ) )
572 $itemnumber = $item->{itemnumber};
576 $holdingbranch = $pickup_branch;
578 elsif ($transport_cost_matrix) {
579 $pull_branches = [keys %items_by_branch];
580 $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
581 if ( $holdingbranch ) {
583 my $holding_branch_items = $items_by_branch{$holdingbranch};
584 foreach my $item (@$holding_branch_items) {
585 next if $request->{borrowerbranch} ne $item->{homebranch};
586 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
588 # Don't fill item level holds that contravene the hold pickup policy at this time
589 next unless _checkHoldPolicy($item, $request);
591 # If hold itemtype is set, item's itemtype must match
592 next unless ( !$request->{itemtype}
593 || $item->{itype} eq $request->{itemtype} );
595 $itemnumber = $item->{itemnumber};
604 unless ($itemnumber) {
605 # not found yet, fall back to basics
606 if ($branches_to_use) {
607 $pull_branches = $branches_to_use;
609 $pull_branches = [keys %items_by_branch];
612 # Try picking items where the home and pickup branch match first
614 foreach my $branch (@$pull_branches) {
615 my $holding_branch_items = $items_by_branch{$branch}
618 $holdingbranch ||= $branch;
619 foreach my $item (@$holding_branch_items) {
620 next if $pickup_branch ne $item->{homebranch};
621 next unless _checkHoldPolicy($item, $request);
622 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
624 # Don't fill item level holds that contravene the hold pickup policy at this time
625 next unless $item->{hold_fulfillment_policy} eq 'any'
626 || $request->{branchcode} eq $item->{ $item->{hold_fulfillment_policy} };
628 # If hold itemtype is set, item's itemtype must match
629 next unless ( !$request->{itemtype}
630 || $item->{itype} eq $request->{itemtype} );
632 $itemnumber = $item->{itemnumber};
633 $holdingbranch = $branch;
638 # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight
639 unless ( $itemnumber || !$holdingbranch) {
640 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
641 next unless _checkHoldPolicy($current_item, $request); # Don't fill item level holds that contravene the hold pickup policy at this time
643 # If hold itemtype is set, item's itemtype must match
644 next unless ( !$request->{itemtype}
645 || $current_item->{itype} eq $request->{itemtype} );
647 next unless $items_by_itemnumber{ $current_item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
649 $itemnumber = $current_item->{itemnumber};
650 last; # quit this loop as soon as we have a suitable item
654 # Now try for items for any item that can fill this hold
655 unless ( $itemnumber ) {
657 foreach my $branch (@$pull_branches) {
658 my $holding_branch_items = $items_by_branch{$branch}
661 foreach my $item (@$holding_branch_items) {
662 # Don't fill item level holds that contravene the hold pickup policy at this time
663 next unless _checkHoldPolicy($item, $request);
665 # If hold itemtype is set, item's itemtype must match
666 next unless ( !$request->{itemtype}
667 || $item->{itype} eq $request->{itemtype} );
669 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
671 $itemnumber = $item->{itemnumber};
672 $holdingbranch = $branch;
680 my $holding_branch_items = $items_by_branch{$holdingbranch}
681 or die "Have $itemnumber, $holdingbranch, but no items!";
682 @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
683 delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
685 $item_map{$itemnumber} = {
686 borrowernumber => $request->{borrowernumber},
687 biblionumber => $request->{biblionumber},
688 holdingbranch => $holdingbranch,
689 pickup_branch => $pickup_branch,
690 reserve_id => $request->{reserve_id},
691 item_level => $request->{item_level_hold},
692 reservedate => $request->{reservedate},
693 reservenotes => $request->{reservenotes},
695 $num_items_remaining--;
701 =head2 CreatePickListFromItemMap
705 sub CreatePicklistFromItemMap {
706 my $item_map = shift;
708 my $dbh = C4::Context->dbh;
710 my $sth_load=$dbh->prepare("
711 INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
712 cardnumber,reservedate,title, itemcallnumber,
713 holdingbranch,pickbranch,notes, item_level_request)
714 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
717 foreach my $itemnumber (sort keys %$item_map) {
718 my $mapped_item = $item_map->{$itemnumber};
719 my $biblionumber = $mapped_item->{biblionumber};
720 my $borrowernumber = $mapped_item->{borrowernumber};
721 my $pickbranch = $mapped_item->{pickup_branch};
722 my $holdingbranch = $mapped_item->{holdingbranch};
723 my $reservedate = $mapped_item->{reservedate};
724 my $reservenotes = $mapped_item->{reservenotes};
725 my $item_level = $mapped_item->{item_level};
727 my $item = Koha::Items->find($itemnumber);
728 my $barcode = $item->barcode;
729 my $itemcallnumber = $item->itemcallnumber;
731 my $patron = Koha::Patrons->find( $borrowernumber );
732 my $cardnumber = $patron->cardnumber;
733 my $surname = $patron->surname;
734 my $firstname = $patron->firstname;
735 my $phone = $patron->phone;
737 my $biblio = Koha::Biblios->find( $biblionumber );
738 my $title = $biblio->title;
740 $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
741 $cardnumber, $reservedate, $title, $itemcallnumber,
742 $holdingbranch, $pickbranch, $reservenotes, $item_level);
746 =head2 AddToHoldTargetMap
750 sub AddToHoldTargetMap {
751 my $item_map = shift;
753 my $dbh = C4::Context->dbh;
756 INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request, reserve_id)
757 VALUES (?, ?, ?, ?, ?, ?)
759 my $sth_insert = $dbh->prepare($insert_sql);
761 foreach my $itemnumber (keys %$item_map) {
762 my $mapped_item = $item_map->{$itemnumber};
763 $sth_insert->execute($mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
764 $mapped_item->{holdingbranch}, $mapped_item->{item_level}, $mapped_item->{reserve_id});
768 # Helper functions, not part of any interface
771 return $_[0] unless $_[0];
777 sub load_branches_to_pull_from {
778 my $use_transport_cost_matrix = shift;
782 unless ( $use_transport_cost_matrix ) {
783 my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight");
784 @branches_to_use = map { _trim($_) } split( /,/, $static_branch_list )
785 if $static_branch_list;
789 Koha::Database->new()->schema()->resultset('Branch')
790 ->get_column('branchcode')->all()
791 unless (@branches_to_use);
793 @branches_to_use = shuffle(@branches_to_use)
794 if C4::Context->preference("RandomizeHoldsQueueWeight");
796 my $today = dt_from_string();
797 if ( C4::Context->preference('HoldsQueueSkipClosed') ) {
798 @branches_to_use = grep {
799 !Koha::Calendar->new( branchcode => $_ )
800 ->is_holiday( $today )
804 return \@branches_to_use;
807 sub least_cost_branch {
810 my ($to, $from, $transport_cost_matrix) = @_;
812 # Nothing really spectacular: supply to branch, a list of potential from branches
813 # and find the minimum from - to value from the transport_cost_matrix
814 return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{$from->[0]}->{disable_transfer} != 1 );
816 # If the pickup library is in the list of libraries to pull from,
817 # return that library right away, it is obviously the least costly
818 return ($to) if any { $_ eq $to } @$from;
820 my ($least_cost, @branch);
822 my $cell = $transport_cost_matrix->{$to}{$_};
823 next if $cell->{disable_transfer};
825 my $cost = $cell->{cost};
826 next unless defined $cost; # XXX should this be reported?
828 unless (defined $least_cost) {
834 next if $cost > $least_cost;
836 if ($cost == $least_cost) {
847 # XXX return a random @branch with minimum cost instead of the first one;
848 # return $branch[0] if @branch == 1;
851 =head3 update_queue_for_biblio
853 my $result = update_queue_for_biblio(
855 biblio_id => $biblio_id,
856 [ branches_to_use => $branches_to_use,
857 transport_cost_matrix => $transport_cost_matrix,
862 Given a I<biblio_id>, this method calculates and sets the holds queue entries
863 for the biblio's holds, and the hold fill targets (items).
867 It return a hashref containing:
871 =item I<requests>: the pending holds count for the biblio.
873 =item I<available_items> the count of items that are available to fill holds for the biblio.
875 =item I<mapped_items> the total items that got mapped.
879 =head4 Optional parameters
883 =item I<branches_to_use> a list of branchcodes to be used to restrict which items can be used.
885 =item I<transport_cost_matrix> is the output of C<TransportCostMatrix>.
887 =item I<delete> tells the method to delete prior entries on the related tables for the biblio_id.
891 Note: All the optional parameters will be calculated in the method if omitted. They
892 are allowed to be passed to avoid calculating them many times inside loops.
896 sub update_queue_for_biblio {
899 my $biblio_id = $args->{biblio_id};
901 my $branches_to_use = $args->{branches_to_use} // load_branches_to_pull_from( C4::Context->preference('UseTransportCostMatrix') );
902 my $transport_cost_matrix;
904 if ( !exists $args->{transport_cost_matrix}
905 && C4::Context->preference('UseTransportCostMatrix') ) {
906 $transport_cost_matrix = TransportCostMatrix();
908 $transport_cost_matrix = $args->{transport_cost_matrix};
911 if ( $args->{delete} ) {
912 my $dbh = C4::Context->dbh;
914 $dbh->do("DELETE FROM tmp_holdsqueue WHERE biblionumber=$biblio_id");
915 $dbh->do("DELETE FROM hold_fill_targets WHERE biblionumber=$biblio_id");
918 my $hold_requests = GetPendingHoldRequestsForBib($biblio_id);
919 my $available_items = GetItemsAvailableToFillHoldRequestsForBib( $biblio_id, $branches_to_use );
922 requests => scalar( @{$hold_requests} ),
923 available_items => scalar( @{$available_items} ),
926 my $item_map = MapItemsToHoldRequests( $hold_requests, $available_items, $branches_to_use, $transport_cost_matrix );
927 $result->{mapped_items} = scalar( keys %{$item_map} );
930 CreatePicklistFromItemMap($item_map);
931 AddToHoldTargetMap($item_map);