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
27 use C4::Circulation qw( GetTransfers GetBranchItemRule );
28 use Koha::DateUtils qw( dt_from_string );
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
137 JOIN biblio USING (biblionumber)
138 LEFT JOIN biblioitems USING (biblionumber)
139 LEFT JOIN items USING ( itemnumber)
142 if ($params->{branchlimit}) {
143 $query .="AND tmp_holdsqueue.holdingbranch = ? ";
144 push @bind_params, $params->{branchlimit};
146 if( $params->{itemtypeslimit} ) {
147 $query .=" AND items.itype = ? ";
148 push @bind_params, $params->{itemtypeslimit};
150 if( $params->{ccodeslimit} ) {
151 $query .=" AND items.ccode = ? ";
152 push @bind_params, $params->{ccodeslimit};
154 if( $params->{locationslimit} ) {
155 $query .=" AND items.location = ? ";
156 push @bind_params, $params->{locationslimit};
158 $query .= " ORDER BY ccode, location, cn_sort, author, title, pickbranch, reservedate";
159 my $sth = $dbh->prepare($query);
160 $sth->execute(@bind_params);
162 while ( my $row = $sth->fetchrow_hashref ){
163 # return the bib-level or item-level itype per syspref
164 if (!C4::Context->preference('item-level_itypes')) {
165 $row->{itype} = $row->{itemtype};
167 delete $row->{itemtype};
178 Top level function that turns reserves into tmp_holdsqueue and hold_fill_targets.
183 my $dbh = C4::Context->dbh;
185 $dbh->do("DELETE FROM tmp_holdsqueue"); # clear the old table for new info
186 $dbh->do("DELETE FROM hold_fill_targets");
189 my $total_requests = 0;
190 my $total_available_items = 0;
191 my $num_items_mapped = 0;
194 my $transport_cost_matrix;
195 my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix");
196 if ($use_transport_cost_matrix) {
197 $transport_cost_matrix = TransportCostMatrix();
198 unless (keys %$transport_cost_matrix) {
199 warn "UseTransportCostMatrix set to yes, but matrix not populated";
200 undef $transport_cost_matrix;
204 $branches_to_use = load_branches_to_pull_from($use_transport_cost_matrix);
206 my $bibs_with_pending_requests = GetBibsWithPendingHoldRequests();
208 foreach my $biblionumber (@$bibs_with_pending_requests) {
212 my $result = update_queue_for_biblio(
213 { biblio_id => $biblionumber,
214 branches_to_use => $branches_to_use,
215 transport_cost_matrix => $transport_cost_matrix,
219 $total_requests += $result->{requests};
220 $total_available_items += $result->{available_items};
221 $num_items_mapped += $result->{mapped_items};
225 =head2 GetBibsWithPendingHoldRequests
227 my $biblionumber_aref = GetBibsWithPendingHoldRequests();
229 Return an arrayref of the biblionumbers of all bibs
230 that have one or more unfilled hold requests.
234 sub GetBibsWithPendingHoldRequests {
235 my $dbh = C4::Context->dbh;
237 my $bib_query = "SELECT DISTINCT biblionumber
241 AND reservedate <= CURRENT_DATE()
244 my $sth = $dbh->prepare($bib_query);
247 my $biblionumbers = $sth->fetchall_arrayref();
249 return [ map { $_->[0] } @$biblionumbers ];
252 =head2 GetPendingHoldRequestsForBib
254 my $requests = GetPendingHoldRequestsForBib($biblionumber);
256 Returns an arrayref of hashrefs to pending, unfilled hold requests
257 on the bib identified by $biblionumber. The following keys
258 are present in each hashref:
269 The arrayref is sorted in order of increasing priority.
273 sub GetPendingHoldRequestsForBib {
274 my $biblionumber = shift;
276 my $dbh = C4::Context->dbh;
278 my $request_query = "SELECT biblionumber, borrowernumber, itemnumber, priority, reserve_id, reserves.branchcode,
279 reservedate, reservenotes, borrowers.branchcode AS borrowerbranch, itemtype, item_level_hold
281 JOIN borrowers USING (borrowernumber)
282 WHERE biblionumber = ?
285 AND reservedate <= CURRENT_DATE()
288 my $sth = $dbh->prepare($request_query);
289 $sth->execute($biblionumber);
291 my $requests = $sth->fetchall_arrayref({});
296 =head2 GetItemsAvailableToFillHoldRequestsForBib
298 my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_ar);
300 Returns an arrayref of items available to fill hold requests
301 for the bib identified by C<$biblionumber>. An item is available
302 to fill a hold request if and only if:
305 * it is not withdrawn
306 * it is not marked notforloan
307 * it is not currently in transit
309 * it is not sitting on the hold shelf
310 * it is not damaged (unless AllowHoldsOnDamagedItems is on)
314 sub GetItemsAvailableToFillHoldRequestsForBib {
315 my ($biblionumber, $branches_to_use) = @_;
317 my $dbh = C4::Context->dbh;
318 my $items_query = "SELECT itemnumber, homebranch, holdingbranch, itemtypes.itemtype AS itype
321 if (C4::Context->preference('item-level_itypes')) {
322 $items_query .= "LEFT JOIN itemtypes ON (itemtypes.itemtype = items.itype) ";
324 $items_query .= "JOIN biblioitems USING (biblioitemnumber)
325 LEFT JOIN itemtypes USING (itemtype) ";
327 $items_query .= "WHERE items.notforloan = 0
328 AND holdingbranch IS NOT NULL
331 $items_query .= " AND damaged = 0" unless C4::Context->preference('AllowHoldsOnDamagedItems');
332 $items_query .= " AND items.onloan IS NULL
333 AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
334 AND itemnumber NOT IN (
337 WHERE biblionumber = ?
338 AND itemnumber IS NOT NULL
339 AND (found IS NOT NULL OR priority = 0)
341 AND items.biblionumber = ?";
343 my @params = ($biblionumber, $biblionumber);
344 if ($branches_to_use && @$branches_to_use) {
345 $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
346 push @params, @$branches_to_use;
348 my $sth = $dbh->prepare($items_query);
349 $sth->execute(@params);
351 my $itm = $sth->fetchall_arrayref({});
352 my @items = grep { ! scalar GetTransfers($_->{itemnumber}) } @$itm;
354 my $rule = GetBranchItemRule($_->{homebranch}, $_->{itype});
355 $_->{holdallowed} = $rule->{holdallowed};
356 $_->{hold_fulfillment_policy} = $rule->{hold_fulfillment_policy};
360 =head2 _checkHoldPolicy
362 _checkHoldPolicy($item, $request)
364 check if item agrees with hold policies
368 sub _checkHoldPolicy {
369 my ( $item, $request ) = @_;
371 return 0 unless $item->{holdallowed} ne 'not_allowed';
374 if $item->{holdallowed} eq 'from_home_library'
375 && $item->{homebranch} ne $request->{borrowerbranch};
378 if $item->{'holdallowed'} eq 'from_local_hold_group'
379 && !Koha::Libraries->find( $item->{homebranch} )
380 ->validate_hold_sibling( { branchcode => $request->{borrowerbranch} } );
382 my $hold_fulfillment_policy = $item->{hold_fulfillment_policy};
385 if $hold_fulfillment_policy eq 'holdgroup'
386 && !Koha::Libraries->find( $item->{homebranch} )
387 ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
390 if $hold_fulfillment_policy eq 'homebranch'
391 && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
394 if $hold_fulfillment_policy eq 'holdingbranch'
395 && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
398 if $hold_fulfillment_policy eq 'patrongroup'
399 && !Koha::Libraries->find( $request->{borrowerbranch} )
400 ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
406 =head2 MapItemsToHoldRequests
408 MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
412 sub MapItemsToHoldRequests {
413 my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
415 # handle trival cases
416 return unless scalar(@$hold_requests) > 0;
417 return unless scalar(@$available_items) > 0;
419 # identify item-level requests
420 my %specific_items_requested = map { $_->{itemnumber} => 1 }
421 grep { defined($_->{itemnumber}) }
424 map { $_->{_object} = Koha::Items->find( $_->{itemnumber} ) } @$available_items;
426 map { $libraries->{$_->id} = $_ } Koha::Libraries->search->as_list;
428 # group available items by itemnumber
429 my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
431 # items already allocated
432 my %allocated_items = ();
434 # map of items to hold requests
437 # figure out which item-level requests can be filled
438 my $num_items_remaining = scalar(@$available_items);
440 # Look for Local Holds Priority matches first
441 if ( C4::Context->preference('LocalHoldsPriority') ) {
442 my $LocalHoldsPriorityPatronControl =
443 C4::Context->preference('LocalHoldsPriorityPatronControl');
444 my $LocalHoldsPriorityItemControl =
445 C4::Context->preference('LocalHoldsPriorityItemControl');
447 foreach my $request (@$hold_requests) {
448 last if $num_items_remaining == 0;
449 my $patron = Koha::Patrons->find($request->{borrowernumber});
450 next if $patron->category->exclude_from_local_holds_priority;
452 my $local_hold_match;
453 foreach my $item (@$available_items) {
454 next if $item->{_object}->exclude_from_local_holds_priority;
456 next unless _checkHoldPolicy($item, $request);
458 next if $request->{itemnumber} && $request->{itemnumber} != $item->{itemnumber};
460 next unless $item->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
462 my $local_holds_priority_item_branchcode =
463 $item->{$LocalHoldsPriorityItemControl};
465 my $local_holds_priority_patron_branchcode =
466 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
467 ? $request->{branchcode}
468 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
469 ? $request->{borrowerbranch}
473 $local_holds_priority_item_branchcode eq
474 $local_holds_priority_patron_branchcode;
476 if ($local_hold_match) {
477 if ( exists $items_by_itemnumber{ $item->{itemnumber} }
478 and not exists $allocated_items{ $item->{itemnumber} }
479 and not $request->{allocated})
481 $item_map{ $item->{itemnumber} } = {
482 borrowernumber => $request->{borrowernumber},
483 biblionumber => $request->{biblionumber},
484 holdingbranch => $item->{holdingbranch},
485 pickup_branch => $request->{branchcode}
486 || $request->{borrowerbranch},
487 reserve_id => $request->{reserve_id},
488 item_level => $request->{item_level_hold},
489 reservedate => $request->{reservedate},
490 reservenotes => $request->{reservenotes},
492 $allocated_items{ $item->{itemnumber} }++;
493 $request->{allocated} = 1;
494 $num_items_remaining--;
501 foreach my $request (@$hold_requests) {
502 last if $num_items_remaining == 0;
503 next if $request->{allocated};
505 # is this an item-level request?
506 if (defined($request->{itemnumber})) {
507 # fill it if possible; if not skip it
509 exists $items_by_itemnumber{ $request->{itemnumber} }
510 and not exists $allocated_items{ $request->{itemnumber} }
511 and _checkHoldPolicy($items_by_itemnumber{ $request->{itemnumber} }, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
512 and ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
513 || $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} )
515 and $items_by_itemnumber{ $request->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } )
520 $item_map{ $request->{itemnumber} } = {
521 borrowernumber => $request->{borrowernumber},
522 biblionumber => $request->{biblionumber},
523 holdingbranch => $items_by_itemnumber{ $request->{itemnumber} }->{holdingbranch},
524 pickup_branch => $request->{branchcode} || $request->{borrowerbranch},
525 reserve_id => $request->{reserve_id},
526 item_level => $request->{item_level_hold},
527 reservedate => $request->{reservedate},
528 reservenotes => $request->{reservenotes},
530 $allocated_items{ $request->{itemnumber} }++;
531 $num_items_remaining--;
534 # it's title-level request that will take up one item
535 $num_items_remaining--;
539 # group available items by branch
540 my %items_by_branch = ();
541 foreach my $item (@$available_items) {
542 next unless $item->{holdallowed} ne 'not_allowed';
544 push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
545 unless exists $allocated_items{ $item->{itemnumber} };
547 return \%item_map unless keys %items_by_branch;
549 # now handle the title-level requests
550 $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
552 foreach my $request (@$hold_requests) {
553 last if $num_items_remaining == 0;
554 next if $request->{allocated};
555 next if defined($request->{itemnumber}); # already handled these
557 # look for local match first
558 my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
559 my ($itemnumber, $holdingbranch);
561 my $holding_branch_items = $items_by_branch{$pickup_branch};
562 if ( $holding_branch_items ) {
563 foreach my $item (@$holding_branch_items) {
564 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
567 $request->{borrowerbranch} eq $item->{homebranch}
568 && _checkHoldPolicy($item, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
569 && ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
570 || ( $request->{itemnumber} && ( $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} ) ) )
573 $itemnumber = $item->{itemnumber};
577 $holdingbranch = $pickup_branch;
579 elsif ($transport_cost_matrix) {
580 $pull_branches = [keys %items_by_branch];
581 $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
582 if ( $holdingbranch ) {
584 my $holding_branch_items = $items_by_branch{$holdingbranch};
585 foreach my $item (@$holding_branch_items) {
586 next if $request->{borrowerbranch} ne $item->{homebranch};
587 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
589 # Don't fill item level holds that contravene the hold pickup policy at this time
590 next unless _checkHoldPolicy($item, $request);
592 # If hold itemtype is set, item's itemtype must match
593 next unless ( !$request->{itemtype}
594 || $item->{itype} eq $request->{itemtype} );
596 $itemnumber = $item->{itemnumber};
605 unless ($itemnumber) {
606 # not found yet, fall back to basics
607 if ($branches_to_use) {
608 $pull_branches = $branches_to_use;
610 $pull_branches = [keys %items_by_branch];
613 # Try picking items where the home and pickup branch match first
615 foreach my $branch (@$pull_branches) {
616 my $holding_branch_items = $items_by_branch{$branch}
619 $holdingbranch ||= $branch;
620 foreach my $item (@$holding_branch_items) {
621 next if $pickup_branch ne $item->{homebranch};
622 next unless _checkHoldPolicy($item, $request);
623 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
625 # Don't fill item level holds that contravene the hold pickup policy at this time
626 next unless $item->{hold_fulfillment_policy} eq 'any'
627 || $request->{branchcode} eq $item->{ $item->{hold_fulfillment_policy} };
629 # If hold itemtype is set, item's itemtype must match
630 next unless ( !$request->{itemtype}
631 || $item->{itype} eq $request->{itemtype} );
633 $itemnumber = $item->{itemnumber};
634 $holdingbranch = $branch;
639 # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight
640 unless ( $itemnumber || !$holdingbranch) {
641 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
642 next unless _checkHoldPolicy($current_item, $request); # Don't fill item level holds that contravene the hold pickup policy at this time
644 # If hold itemtype is set, item's itemtype must match
645 next unless ( !$request->{itemtype}
646 || $current_item->{itype} eq $request->{itemtype} );
648 next unless $items_by_itemnumber{ $current_item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
650 $itemnumber = $current_item->{itemnumber};
651 last; # quit this loop as soon as we have a suitable item
655 # Now try for items for any item that can fill this hold
656 unless ( $itemnumber ) {
658 foreach my $branch (@$pull_branches) {
659 my $holding_branch_items = $items_by_branch{$branch}
662 foreach my $item (@$holding_branch_items) {
663 # Don't fill item level holds that contravene the hold pickup policy at this time
664 next unless _checkHoldPolicy($item, $request);
666 # If hold itemtype is set, item's itemtype must match
667 next unless ( !$request->{itemtype}
668 || $item->{itype} eq $request->{itemtype} );
670 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
672 $itemnumber = $item->{itemnumber};
673 $holdingbranch = $branch;
681 my $holding_branch_items = $items_by_branch{$holdingbranch}
682 or die "Have $itemnumber, $holdingbranch, but no items!";
683 @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
684 delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
686 $item_map{$itemnumber} = {
687 borrowernumber => $request->{borrowernumber},
688 biblionumber => $request->{biblionumber},
689 holdingbranch => $holdingbranch,
690 pickup_branch => $pickup_branch,
691 reserve_id => $request->{reserve_id},
692 item_level => $request->{item_level_hold},
693 reservedate => $request->{reservedate},
694 reservenotes => $request->{reservenotes},
696 $num_items_remaining--;
702 =head2 CreatePickListFromItemMap
706 sub CreatePicklistFromItemMap {
707 my $item_map = shift;
709 my $dbh = C4::Context->dbh;
711 my $sth_load=$dbh->prepare("
712 INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
713 cardnumber,reservedate,title, itemcallnumber,
714 holdingbranch,pickbranch,notes, item_level_request)
715 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
718 foreach my $itemnumber (sort keys %$item_map) {
719 my $mapped_item = $item_map->{$itemnumber};
720 my $biblionumber = $mapped_item->{biblionumber};
721 my $borrowernumber = $mapped_item->{borrowernumber};
722 my $pickbranch = $mapped_item->{pickup_branch};
723 my $holdingbranch = $mapped_item->{holdingbranch};
724 my $reservedate = $mapped_item->{reservedate};
725 my $reservenotes = $mapped_item->{reservenotes};
726 my $item_level = $mapped_item->{item_level};
728 my $item = Koha::Items->find($itemnumber);
729 my $barcode = $item->barcode;
730 my $itemcallnumber = $item->itemcallnumber;
732 my $patron = Koha::Patrons->find( $borrowernumber );
733 my $cardnumber = $patron->cardnumber;
734 my $surname = $patron->surname;
735 my $firstname = $patron->firstname;
736 my $phone = $patron->phone;
738 my $biblio = Koha::Biblios->find( $biblionumber );
739 my $title = $biblio->title;
741 $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
742 $cardnumber, $reservedate, $title, $itemcallnumber,
743 $holdingbranch, $pickbranch, $reservenotes, $item_level);
747 =head2 AddToHoldTargetMap
751 sub AddToHoldTargetMap {
752 my $item_map = shift;
754 my $dbh = C4::Context->dbh;
757 INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request, reserve_id)
758 VALUES (?, ?, ?, ?, ?, ?)
760 my $sth_insert = $dbh->prepare($insert_sql);
762 foreach my $itemnumber (keys %$item_map) {
763 my $mapped_item = $item_map->{$itemnumber};
764 $sth_insert->execute($mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
765 $mapped_item->{holdingbranch}, $mapped_item->{item_level}, $mapped_item->{reserve_id});
769 # Helper functions, not part of any interface
772 return $_[0] unless $_[0];
778 sub load_branches_to_pull_from {
779 my $use_transport_cost_matrix = shift;
783 unless ( $use_transport_cost_matrix ) {
784 my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight");
785 @branches_to_use = map { _trim($_) } split( /,/, $static_branch_list )
786 if $static_branch_list;
790 Koha::Database->new()->schema()->resultset('Branch')
791 ->get_column('branchcode')->all()
792 unless (@branches_to_use);
794 @branches_to_use = shuffle(@branches_to_use)
795 if C4::Context->preference("RandomizeHoldsQueueWeight");
797 my $today = dt_from_string();
798 if ( C4::Context->preference('HoldsQueueSkipClosed') ) {
799 @branches_to_use = grep {
800 !Koha::Calendar->new( branchcode => $_ )
801 ->is_holiday( $today )
805 return \@branches_to_use;
808 sub least_cost_branch {
811 my ($to, $from, $transport_cost_matrix) = @_;
813 # Nothing really spectacular: supply to branch, a list of potential from branches
814 # and find the minimum from - to value from the transport_cost_matrix
815 return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{$from->[0]}->{disable_transfer} != 1 );
817 # If the pickup library is in the list of libraries to pull from,
818 # return that library right away, it is obviously the least costly
819 return ($to) if any { $_ eq $to } @$from;
821 my ($least_cost, @branch);
823 my $cell = $transport_cost_matrix->{$to}{$_};
824 next if $cell->{disable_transfer};
826 my $cost = $cell->{cost};
827 next unless defined $cost; # XXX should this be reported?
829 unless (defined $least_cost) {
835 next if $cost > $least_cost;
837 if ($cost == $least_cost) {
848 # XXX return a random @branch with minimum cost instead of the first one;
849 # return $branch[0] if @branch == 1;
852 =head3 update_queue_for_biblio
854 my $result = update_queue_for_biblio(
856 biblio_id => $biblio_id,
857 [ branches_to_use => $branches_to_use,
858 transport_cost_matrix => $transport_cost_matrix,
863 Given a I<biblio_id>, this method calculates and sets the holds queue entries
864 for the biblio's holds, and the hold fill targets (items).
868 It return a hashref containing:
872 =item I<requests>: the pending holds count for the biblio.
874 =item I<available_items> the count of items that are available to fill holds for the biblio.
876 =item I<mapped_items> the total items that got mapped.
880 =head4 Optional parameters
884 =item I<branches_to_use> a list of branchcodes to be used to restrict which items can be used.
886 =item I<transport_cost_matrix> is the output of C<TransportCostMatrix>.
888 =item I<delete> tells the method to delete prior entries on the related tables for the biblio_id.
892 Note: All the optional parameters will be calculated in the method if omitted. They
893 are allowed to be passed to avoid calculating them many times inside loops.
897 sub update_queue_for_biblio {
900 my $biblio_id = $args->{biblio_id};
902 my $branches_to_use = $args->{branches_to_use} // load_branches_to_pull_from( C4::Context->preference('UseTransportCostMatrix') );
903 my $transport_cost_matrix;
905 if ( !exists $args->{transport_cost_matrix}
906 && C4::Context->preference('UseTransportCostMatrix') ) {
907 $transport_cost_matrix = TransportCostMatrix();
909 $transport_cost_matrix = $args->{transport_cost_matrix};
912 if ( $args->{delete} ) {
913 my $dbh = C4::Context->dbh;
915 $dbh->do("DELETE FROM tmp_holdsqueue WHERE biblionumber=$biblio_id");
916 $dbh->do("DELETE FROM hold_fill_targets WHERE biblionumber=$biblio_id");
919 my $hold_requests = GetPendingHoldRequestsForBib($biblio_id);
920 my $available_items = GetItemsAvailableToFillHoldRequestsForBib( $biblio_id, $branches_to_use );
923 requests => scalar( @{$hold_requests} ),
924 available_items => scalar( @{$available_items} ),
927 my $item_map = MapItemsToHoldRequests( $hold_requests, $available_items, $branches_to_use, $transport_cost_matrix );
928 $result->{mapped_items} = scalar( keys %{$item_map} );
931 CreatePicklistFromItemMap($item_map);
932 AddToHoldTargetMap($item_map);