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
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 items.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 .= " LEFT JOIN branchtransfers ON (items.itemnumber = branchtransfers.itemnumber)";
327 $items_query .= " WHERE items.notforloan = 0
328 AND holdingbranch IS NOT NULL
331 $items_query .= " AND branchtransfers.datearrived IS NULL
332 AND branchtransfers.datecancelled IS NULL";
333 $items_query .= " AND damaged = 0" unless C4::Context->preference('AllowHoldsOnDamagedItems');
334 $items_query .= " AND items.onloan IS NULL
335 AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
336 AND items.itemnumber NOT IN (
339 WHERE biblionumber = ?
340 AND itemnumber IS NOT NULL
341 AND (found IS NOT NULL OR priority = 0)
343 AND items.biblionumber = ?";
345 my @params = ($biblionumber, $biblionumber);
346 if ($branches_to_use && @$branches_to_use) {
347 $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
348 push @params, @$branches_to_use;
350 my $sth = $dbh->prepare($items_query);
351 $sth->execute(@params);
353 my $itm = $sth->fetchall_arrayref({});
355 my $rule = C4::Circulation::GetBranchItemRule($_->{homebranch}, $_->{itype});
356 $_->{holdallowed} = $rule->{holdallowed};
357 $_->{hold_fulfillment_policy} = $rule->{hold_fulfillment_policy};
361 =head2 _checkHoldPolicy
363 _checkHoldPolicy($item, $request)
365 check if item agrees with hold policies
369 sub _checkHoldPolicy {
370 my ( $item, $request ) = @_;
372 return 0 unless $item->{holdallowed} ne 'not_allowed';
375 if $item->{holdallowed} eq 'from_home_library'
376 && $item->{homebranch} ne $request->{borrowerbranch};
379 if $item->{'holdallowed'} eq 'from_local_hold_group'
380 && !Koha::Libraries->find( $item->{homebranch} )
381 ->validate_hold_sibling( { branchcode => $request->{borrowerbranch} } );
383 my $hold_fulfillment_policy = $item->{hold_fulfillment_policy};
386 if $hold_fulfillment_policy eq 'holdgroup'
387 && !Koha::Libraries->find( $item->{homebranch} )
388 ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
391 if $hold_fulfillment_policy eq 'homebranch'
392 && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
395 if $hold_fulfillment_policy eq 'holdingbranch'
396 && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
399 if $hold_fulfillment_policy eq 'patrongroup'
400 && !Koha::Libraries->find( $request->{borrowerbranch} )
401 ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
407 =head2 MapItemsToHoldRequests
409 MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
413 sub MapItemsToHoldRequests {
414 my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
416 # handle trival cases
417 return unless scalar(@$hold_requests) > 0;
418 return unless scalar(@$available_items) > 0;
420 # identify item-level requests
421 my %specific_items_requested = map { $_->{itemnumber} => 1 }
422 grep { defined($_->{itemnumber}) }
425 map { $_->{_object} = Koha::Items->find( $_->{itemnumber} ) } @$available_items;
427 map { $libraries->{$_->id} = $_ } Koha::Libraries->search->as_list;
429 # group available items by itemnumber
430 my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
432 # items already allocated
433 my %allocated_items = ();
435 # map of items to hold requests
438 # figure out which item-level requests can be filled
439 my $num_items_remaining = scalar(@$available_items);
441 # Look for Local Holds Priority matches first
442 if ( C4::Context->preference('LocalHoldsPriority') ) {
443 my $LocalHoldsPriorityPatronControl =
444 C4::Context->preference('LocalHoldsPriorityPatronControl');
445 my $LocalHoldsPriorityItemControl =
446 C4::Context->preference('LocalHoldsPriorityItemControl');
448 foreach my $request (@$hold_requests) {
449 last if $num_items_remaining == 0;
450 my $patron = Koha::Patrons->find($request->{borrowernumber});
451 next if $patron->category->exclude_from_local_holds_priority;
453 my $local_hold_match;
454 foreach my $item (@$available_items) {
455 next if $item->{_object}->exclude_from_local_holds_priority;
457 next unless _checkHoldPolicy($item, $request);
459 next if $request->{itemnumber} && $request->{itemnumber} != $item->{itemnumber};
461 next unless $item->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
463 my $local_holds_priority_item_branchcode =
464 $item->{$LocalHoldsPriorityItemControl};
466 my $local_holds_priority_patron_branchcode =
467 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
468 ? $request->{branchcode}
469 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
470 ? $request->{borrowerbranch}
474 $local_holds_priority_item_branchcode eq
475 $local_holds_priority_patron_branchcode;
477 if ($local_hold_match) {
478 if ( exists $items_by_itemnumber{ $item->{itemnumber} }
479 and not exists $allocated_items{ $item->{itemnumber} }
480 and not $request->{allocated})
482 $item_map{ $item->{itemnumber} } = {
483 borrowernumber => $request->{borrowernumber},
484 biblionumber => $request->{biblionumber},
485 holdingbranch => $item->{holdingbranch},
486 pickup_branch => $request->{branchcode}
487 || $request->{borrowerbranch},
488 reserve_id => $request->{reserve_id},
489 item_level => $request->{item_level_hold},
490 reservedate => $request->{reservedate},
491 reservenotes => $request->{reservenotes},
493 $allocated_items{ $item->{itemnumber} }++;
494 $request->{allocated} = 1;
495 $num_items_remaining--;
502 foreach my $request (@$hold_requests) {
503 last if $num_items_remaining == 0;
504 next if $request->{allocated};
506 # is this an item-level request?
507 if (defined($request->{itemnumber})) {
508 # fill it if possible; if not skip it
510 exists $items_by_itemnumber{ $request->{itemnumber} }
511 and not exists $allocated_items{ $request->{itemnumber} }
512 and _checkHoldPolicy($items_by_itemnumber{ $request->{itemnumber} }, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
513 and ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
514 || $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} )
516 and $items_by_itemnumber{ $request->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } )
521 $item_map{ $request->{itemnumber} } = {
522 borrowernumber => $request->{borrowernumber},
523 biblionumber => $request->{biblionumber},
524 holdingbranch => $items_by_itemnumber{ $request->{itemnumber} }->{holdingbranch},
525 pickup_branch => $request->{branchcode} || $request->{borrowerbranch},
526 reserve_id => $request->{reserve_id},
527 item_level => $request->{item_level_hold},
528 reservedate => $request->{reservedate},
529 reservenotes => $request->{reservenotes},
531 $allocated_items{ $request->{itemnumber} }++;
532 $num_items_remaining--;
535 # it's title-level request that will take up one item
536 $num_items_remaining--;
540 # group available items by branch
541 my %items_by_branch = ();
542 foreach my $item (@$available_items) {
543 next unless $item->{holdallowed} ne 'not_allowed';
545 push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
546 unless exists $allocated_items{ $item->{itemnumber} };
548 return \%item_map unless keys %items_by_branch;
550 # now handle the title-level requests
551 $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
553 foreach my $request (@$hold_requests) {
554 last if $num_items_remaining == 0;
555 next if $request->{allocated};
556 next if defined($request->{itemnumber}); # already handled these
558 # look for local match first
559 my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
560 my ($itemnumber, $holdingbranch);
562 my $holding_branch_items = $items_by_branch{$pickup_branch};
563 if ( $holding_branch_items ) {
564 foreach my $item (@$holding_branch_items) {
565 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
568 $request->{borrowerbranch} eq $item->{homebranch}
569 && _checkHoldPolicy($item, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
570 && ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
571 || ( $request->{itemnumber} && ( $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} ) ) )
574 $itemnumber = $item->{itemnumber};
578 $holdingbranch = $pickup_branch;
580 elsif ($transport_cost_matrix) {
581 $pull_branches = [keys %items_by_branch];
582 $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
583 if ( $holdingbranch ) {
585 my $holding_branch_items = $items_by_branch{$holdingbranch};
586 foreach my $item (@$holding_branch_items) {
587 next if $request->{borrowerbranch} ne $item->{homebranch};
588 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
590 # Don't fill item level holds that contravene the hold pickup policy at this time
591 next unless _checkHoldPolicy($item, $request);
593 # If hold itemtype is set, item's itemtype must match
594 next unless ( !$request->{itemtype}
595 || $item->{itype} eq $request->{itemtype} );
597 $itemnumber = $item->{itemnumber};
606 unless ($itemnumber) {
607 # not found yet, fall back to basics
608 if ($branches_to_use) {
609 $pull_branches = $branches_to_use;
611 $pull_branches = [keys %items_by_branch];
614 # Try picking items where the home and pickup branch match first
616 foreach my $branch (@$pull_branches) {
617 my $holding_branch_items = $items_by_branch{$branch}
620 $holdingbranch ||= $branch;
621 foreach my $item (@$holding_branch_items) {
622 next if $pickup_branch ne $item->{homebranch};
623 next unless _checkHoldPolicy($item, $request);
624 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
626 # If hold itemtype is set, item's itemtype must match
627 next unless ( !$request->{itemtype}
628 || $item->{itype} eq $request->{itemtype} );
630 $itemnumber = $item->{itemnumber};
631 $holdingbranch = $branch;
636 # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight
637 unless ( $itemnumber || !$holdingbranch) {
638 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
639 next unless _checkHoldPolicy($current_item, $request); # Don't fill item level holds that contravene the hold pickup policy at this time
641 # If hold itemtype is set, item's itemtype must match
642 next unless ( !$request->{itemtype}
643 || $current_item->{itype} eq $request->{itemtype} );
645 next unless $items_by_itemnumber{ $current_item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
647 $itemnumber = $current_item->{itemnumber};
648 last; # quit this loop as soon as we have a suitable item
652 # Now try for items for any item that can fill this hold
653 unless ( $itemnumber ) {
655 foreach my $branch (@$pull_branches) {
656 my $holding_branch_items = $items_by_branch{$branch}
659 foreach my $item (@$holding_branch_items) {
660 # Don't fill item level holds that contravene the hold pickup policy at this time
661 next unless _checkHoldPolicy($item, $request);
663 # If hold itemtype is set, item's itemtype must match
664 next unless ( !$request->{itemtype}
665 || $item->{itype} eq $request->{itemtype} );
667 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
669 $itemnumber = $item->{itemnumber};
670 $holdingbranch = $branch;
678 my $holding_branch_items = $items_by_branch{$holdingbranch}
679 or die "Have $itemnumber, $holdingbranch, but no items!";
680 @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
681 delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
683 $item_map{$itemnumber} = {
684 borrowernumber => $request->{borrowernumber},
685 biblionumber => $request->{biblionumber},
686 holdingbranch => $holdingbranch,
687 pickup_branch => $pickup_branch,
688 reserve_id => $request->{reserve_id},
689 item_level => $request->{item_level_hold},
690 reservedate => $request->{reservedate},
691 reservenotes => $request->{reservenotes},
693 $num_items_remaining--;
699 =head2 CreatePickListFromItemMap
703 sub CreatePicklistFromItemMap {
704 my $item_map = shift;
706 my $dbh = C4::Context->dbh;
708 my $sth_load=$dbh->prepare("
709 INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
710 cardnumber,reservedate,title, itemcallnumber,
711 holdingbranch,pickbranch,notes, item_level_request)
712 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
715 foreach my $itemnumber (sort keys %$item_map) {
716 my $mapped_item = $item_map->{$itemnumber};
717 my $biblionumber = $mapped_item->{biblionumber};
718 my $borrowernumber = $mapped_item->{borrowernumber};
719 my $pickbranch = $mapped_item->{pickup_branch};
720 my $holdingbranch = $mapped_item->{holdingbranch};
721 my $reservedate = $mapped_item->{reservedate};
722 my $reservenotes = $mapped_item->{reservenotes};
723 my $item_level = $mapped_item->{item_level};
725 my $item = Koha::Items->find($itemnumber);
726 my $barcode = $item->barcode;
727 my $itemcallnumber = $item->itemcallnumber;
729 my $patron = Koha::Patrons->find( $borrowernumber );
730 my $cardnumber = $patron->cardnumber;
731 my $surname = $patron->surname;
732 my $firstname = $patron->firstname;
733 my $phone = $patron->phone;
735 my $biblio = Koha::Biblios->find( $biblionumber );
736 my $title = $biblio->title;
738 $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
739 $cardnumber, $reservedate, $title, $itemcallnumber,
740 $holdingbranch, $pickbranch, $reservenotes, $item_level);
744 =head2 AddToHoldTargetMap
748 sub AddToHoldTargetMap {
749 my $item_map = shift;
751 my $dbh = C4::Context->dbh;
754 INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request, reserve_id)
755 VALUES (?, ?, ?, ?, ?, ?)
757 my $sth_insert = $dbh->prepare($insert_sql);
759 foreach my $itemnumber (keys %$item_map) {
760 my $mapped_item = $item_map->{$itemnumber};
761 $sth_insert->execute($mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
762 $mapped_item->{holdingbranch}, $mapped_item->{item_level}, $mapped_item->{reserve_id});
766 # Helper functions, not part of any interface
769 return $_[0] unless $_[0];
775 sub load_branches_to_pull_from {
776 my $use_transport_cost_matrix = shift;
780 unless ( $use_transport_cost_matrix ) {
781 my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight");
782 @branches_to_use = map { _trim($_) } split( /,/, $static_branch_list )
783 if $static_branch_list;
787 Koha::Database->new()->schema()->resultset('Branch')
788 ->get_column('branchcode')->all()
789 unless (@branches_to_use);
791 @branches_to_use = shuffle(@branches_to_use)
792 if C4::Context->preference("RandomizeHoldsQueueWeight");
794 my $today = dt_from_string();
795 if ( C4::Context->preference('HoldsQueueSkipClosed') ) {
796 @branches_to_use = grep {
797 !Koha::Calendar->new( branchcode => $_ )
798 ->is_holiday( $today )
802 return \@branches_to_use;
805 sub least_cost_branch {
808 my ($to, $from, $transport_cost_matrix) = @_;
810 # Nothing really spectacular: supply to branch, a list of potential from branches
811 # and find the minimum from - to value from the transport_cost_matrix
812 return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{$from->[0]}->{disable_transfer} != 1 );
814 # If the pickup library is in the list of libraries to pull from,
815 # return that library right away, it is obviously the least costly
816 return ($to) if any { $_ eq $to } @$from;
818 my ($least_cost, @branch);
820 my $cell = $transport_cost_matrix->{$to}{$_};
821 next if $cell->{disable_transfer};
823 my $cost = $cell->{cost};
824 next unless defined $cost; # XXX should this be reported?
826 unless (defined $least_cost) {
832 next if $cost > $least_cost;
834 if ($cost == $least_cost) {
845 # XXX return a random @branch with minimum cost instead of the first one;
846 # return $branch[0] if @branch == 1;
849 =head3 update_queue_for_biblio
851 my $result = update_queue_for_biblio(
853 biblio_id => $biblio_id,
854 [ branches_to_use => $branches_to_use,
855 transport_cost_matrix => $transport_cost_matrix,
860 Given a I<biblio_id>, this method calculates and sets the holds queue entries
861 for the biblio's holds, and the hold fill targets (items).
865 It return a hashref containing:
869 =item I<requests>: the pending holds count for the biblio.
871 =item I<available_items> the count of items that are available to fill holds for the biblio.
873 =item I<mapped_items> the total items that got mapped.
877 =head4 Optional parameters
881 =item I<branches_to_use> a list of branchcodes to be used to restrict which items can be used.
883 =item I<transport_cost_matrix> is the output of C<TransportCostMatrix>.
885 =item I<delete> tells the method to delete prior entries on the related tables for the biblio_id.
889 Note: All the optional parameters will be calculated in the method if omitted. They
890 are allowed to be passed to avoid calculating them many times inside loops.
894 sub update_queue_for_biblio {
897 my $biblio_id = $args->{biblio_id};
899 my $branches_to_use = $args->{branches_to_use} // load_branches_to_pull_from( C4::Context->preference('UseTransportCostMatrix') );
900 my $transport_cost_matrix;
902 if ( !exists $args->{transport_cost_matrix}
903 && C4::Context->preference('UseTransportCostMatrix') ) {
904 $transport_cost_matrix = TransportCostMatrix();
906 $transport_cost_matrix = $args->{transport_cost_matrix};
909 if ( $args->{delete} ) {
910 my $dbh = C4::Context->dbh;
912 $dbh->do("DELETE FROM tmp_holdsqueue WHERE biblionumber=$biblio_id");
913 $dbh->do("DELETE FROM hold_fill_targets WHERE biblionumber=$biblio_id");
916 my $hold_requests = GetPendingHoldRequestsForBib($biblio_id);
917 my $available_items = GetItemsAvailableToFillHoldRequestsForBib( $biblio_id, $branches_to_use );
920 requests => scalar( @{$hold_requests} ),
921 available_items => scalar( @{$available_items} ),
924 my $item_map = MapItemsToHoldRequests( $hold_requests, $available_items, $branches_to_use, $transport_cost_matrix );
925 $result->{mapped_items} = scalar( keys %{$item_map} );
928 CreatePicklistFromItemMap($item_map);
929 AddToHoldTargetMap($item_map);