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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 # FIXME: expand perldoc, explain intended logic
32 use C4
::Dates qw
/format_date/;
34 use List
::Util
qw(shuffle);
37 use vars
qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
47 &UpdateTransportCostMatrix
54 =head2 TransportCostMatrix
56 TransportCostMatrix();
58 Returns Transport Cost Matrix as a hashref <to branch code> => <from branch code> => cost
62 sub TransportCostMatrix
{
63 my $dbh = C4
::Context
->dbh;
64 my $transport_costs = $dbh->selectall_arrayref("SELECT * FROM transport_cost",{ Slice
=> {} });
66 my %transport_cost_matrix;
67 foreach (@
$transport_costs) {
68 my $from = $_->{frombranch
};
69 my $to = $_->{tobranch
};
70 my $cost = $_->{cost
};
71 my $disabled = $_->{disable_transfer
};
72 $transport_cost_matrix{$to}{$from} = { cost
=> $cost, disable_transfer
=> $disabled };
74 return \
%transport_cost_matrix;
77 =head2 UpdateTransportCostMatrix
79 UpdateTransportCostMatrix($records);
81 Updates full Transport Cost Matrix table. $records is an arrayref of records.
82 Records: { frombranch => <code>, tobranch => <code>, cost => <figure>, disable_transfer => <0,1> }
86 sub UpdateTransportCostMatrix
{
88 my $dbh = C4
::Context
->dbh;
90 my $sth = $dbh->prepare("INSERT INTO transport_cost (frombranch, tobranch, cost, disable_transfer) VALUES (?, ?, ?, ?)");
92 $dbh->do("TRUNCATE TABLE transport_cost");
94 my $cost = $_->{cost
};
95 my $from = $_->{frombranch
};
96 my $to = $_->{tobranch
};
97 if ($_->{disable_transfer
}) {
100 elsif ( !defined ($cost) || ($cost !~ m/(0|[1-9][0-9]*)(\.[0-9]*)?/o) ) {
101 warn "Invalid $from -> $to cost $cost - must be a number >= 0, disablig";
103 $_->{disable_transfer
} = 1;
105 $sth->execute( $from, $to, $cost, $_->{disable_transfer
} ?
1 : 0 );
109 =head2 GetHoldsQueueItems
111 GetHoldsQueueItems($branch);
113 Returns hold queue for a holding branch. If branch is omitted, then whole queue is returned
117 sub GetHoldsQueueItems
{
118 my ($branchlimit) = @_;
119 my $dbh = C4
::Context
->dbh;
121 my @bind_params = ();
122 my $query = q
/SELECT tmp_holdsqueue
.*, biblio
.author
, items
.ccode
, items
.location
, items
.enumchron
, items
.cn_sort
, biblioitems
.publishercode
,biblio
.copyrightdate
,biblioitems
.publicationyear
,biblioitems
.pages
,biblioitems
.size
,biblioitems
.publicationyear
,biblioitems
.isbn
,items
.copynumber
124 JOIN biblio USING
(biblionumber
)
125 LEFT JOIN biblioitems USING
(biblionumber
)
126 LEFT JOIN items USING
( itemnumber
)
129 $query .=" WHERE tmp_holdsqueue.holdingbranch = ?";
130 push @bind_params, $branchlimit;
132 $query .= " ORDER BY ccode, location, cn_sort, author, title, pickbranch, reservedate";
133 my $sth = $dbh->prepare($query);
134 $sth->execute(@bind_params);
136 while ( my $row = $sth->fetchrow_hashref ){
137 $row->{reservedate
} = format_date
($row->{reservedate
});
138 my $record = GetMarcBiblio
($row->{biblionumber
});
140 $row->{subtitle
} = GetRecordValue
('subtitle',$record,'')->[0]->{subfield
};
141 $row->{parts
} = GetRecordValue
('parts',$record,'')->[0]->{subfield
};
142 $row->{numbers
} = GetRecordValue
('numbers',$record,'')->[0]->{subfield
};
153 Top level function that turns reserves into tmp_holdsqueue and hold_fill_targets.
158 my $dbh = C4
::Context
->dbh;
160 $dbh->do("DELETE FROM tmp_holdsqueue"); # clear the old table for new info
161 $dbh->do("DELETE FROM hold_fill_targets");
164 my $total_requests = 0;
165 my $total_available_items = 0;
166 my $num_items_mapped = 0;
169 my $transport_cost_matrix;
170 my $use_transport_cost_matrix = C4
::Context
->preference("UseTransportCostMatrix");
171 if ($use_transport_cost_matrix) {
172 $transport_cost_matrix = TransportCostMatrix
();
173 unless (keys %$transport_cost_matrix) {
174 warn "UseTransportCostMatrix set to yes, but matrix not populated";
175 undef $transport_cost_matrix;
178 unless ($transport_cost_matrix) {
179 $branches_to_use = load_branches_to_pull_from
();
182 my $bibs_with_pending_requests = GetBibsWithPendingHoldRequests
();
184 foreach my $biblionumber (@
$bibs_with_pending_requests) {
186 my $hold_requests = GetPendingHoldRequestsForBib
($biblionumber);
187 my $available_items = GetItemsAvailableToFillHoldRequestsForBib
($biblionumber, $branches_to_use);
188 $total_requests += scalar(@
$hold_requests);
189 $total_available_items += scalar(@
$available_items);
191 my $item_map = MapItemsToHoldRequests
($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix);
193 my $item_map_size = scalar(keys %$item_map)
196 $num_items_mapped += $item_map_size;
197 CreatePicklistFromItemMap
($item_map);
198 AddToHoldTargetMap
($item_map);
199 if (($item_map_size < scalar(@
$hold_requests )) and
200 ($item_map_size < scalar(@
$available_items))) {
201 # DOUBLE CHECK, but this is probably OK - unfilled item-level requests
203 #warn "unfilled requests for $biblionumber";
204 #warn Dumper($hold_requests), Dumper($available_items), Dumper($item_map);
209 =head2 GetBibsWithPendingHoldRequests
211 my $biblionumber_aref = GetBibsWithPendingHoldRequests();
213 Return an arrayref of the biblionumbers of all bibs
214 that have one or more unfilled hold requests.
218 sub GetBibsWithPendingHoldRequests
{
219 my $dbh = C4
::Context
->dbh;
221 my $bib_query = "SELECT DISTINCT biblionumber
225 AND reservedate <= CURRENT_DATE()";
226 my $sth = $dbh->prepare($bib_query);
229 my $biblionumbers = $sth->fetchall_arrayref();
231 return [ map { $_->[0] } @
$biblionumbers ];
234 =head2 GetPendingHoldRequestsForBib
236 my $requests = GetPendingHoldRequestsForBib($biblionumber);
238 Returns an arrayref of hashrefs to pending, unfilled hold requests
239 on the bib identified by $biblionumber. The following keys
240 are present in each hashref:
251 The arrayref is sorted in order of increasing priority.
255 sub GetPendingHoldRequestsForBib
{
256 my $biblionumber = shift;
258 my $dbh = C4
::Context
->dbh;
260 my $request_query = "SELECT biblionumber, borrowernumber, itemnumber, priority, reserves.branchcode,
261 reservedate, reservenotes, borrowers.branchcode AS borrowerbranch
263 JOIN borrowers USING (borrowernumber)
264 WHERE biblionumber = ?
267 AND reservedate <= CURRENT_DATE()
269 my $sth = $dbh->prepare($request_query);
270 $sth->execute($biblionumber);
272 my $requests = $sth->fetchall_arrayref({});
277 =head2 GetItemsAvailableToFillHoldRequestsForBib
279 my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_ar);
281 Returns an arrayref of items available to fill hold requests
282 for the bib identified by C<$biblionumber>. An item is available
283 to fill a hold request if and only if:
286 * it is not withdrawn
287 * it is not marked notforloan
288 * it is not currently in transit
290 * it is not sitting on the hold shelf
294 sub GetItemsAvailableToFillHoldRequestsForBib
{
295 my ($biblionumber, $branches_to_use) = @_;
297 my $dbh = C4
::Context
->dbh;
298 my $items_query = "SELECT itemnumber, homebranch, holdingbranch, itemtypes.itemtype AS itype
301 if (C4
::Context
->preference('item-level_itypes')) {
302 $items_query .= "LEFT JOIN itemtypes ON (itemtypes.itemtype = items.itype) ";
304 $items_query .= "JOIN biblioitems USING (biblioitemnumber)
305 LEFT JOIN itemtypes USING (itemtype) ";
307 $items_query .= "WHERE items.notforloan = 0
308 AND holdingbranch IS NOT NULL
311 $items_query .= " AND damaged = 0" unless C4
::Context
->preference('AllowHoldsOnDamagedItems');
312 $items_query .= " AND items.onloan IS NULL
313 AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
314 AND itemnumber NOT IN (
317 WHERE biblionumber = ?
318 AND itemnumber IS NOT NULL
319 AND (found IS NOT NULL OR priority = 0)
321 AND items.biblionumber = ?";
322 $items_query .= " AND damaged = 0 "
323 unless C4
::Context
->preference('AllowHoldsOnDamagedItems');
325 my @params = ($biblionumber, $biblionumber);
326 if ($branches_to_use && @
$branches_to_use) {
327 $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @
$branches_to_use) . ")";
328 push @params, @
$branches_to_use;
330 my $sth = $dbh->prepare($items_query);
331 $sth->execute(@params);
333 my $itm = $sth->fetchall_arrayref({});
334 my @items = grep { ! scalar GetTransfers
($_->{itemnumber
}) } @
$itm;
336 my $rule = GetBranchItemRule
($_->{homebranch
}, $_->{itype
});
337 $_->{holdallowed
} = $rule->{holdallowed
} != 0
341 =head2 MapItemsToHoldRequests
343 MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
347 sub MapItemsToHoldRequests
{
348 my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
350 # handle trival cases
351 return unless scalar(@
$hold_requests) > 0;
352 return unless scalar(@
$available_items) > 0;
354 my $automatic_return = C4
::Context
->preference("AutomaticItemReturn");
356 # identify item-level requests
357 my %specific_items_requested = map { $_->{itemnumber
} => 1 }
358 grep { defined($_->{itemnumber
}) }
361 # group available items by itemnumber
362 my %items_by_itemnumber = map { $_->{itemnumber
} => $_ } @
$available_items;
364 # items already allocated
365 my %allocated_items = ();
367 # map of items to hold requests
370 # figure out which item-level requests can be filled
371 my $num_items_remaining = scalar(@
$available_items);
372 foreach my $request (@
$hold_requests) {
373 last if $num_items_remaining == 0;
375 # is this an item-level request?
376 if (defined($request->{itemnumber
})) {
377 # fill it if possible; if not skip it
378 if (exists $items_by_itemnumber{$request->{itemnumber
}} and
379 not exists $allocated_items{$request->{itemnumber
}}) {
380 $item_map{$request->{itemnumber
}} = {
381 borrowernumber
=> $request->{borrowernumber
},
382 biblionumber
=> $request->{biblionumber
},
383 holdingbranch
=> $items_by_itemnumber{$request->{itemnumber
}}->{holdingbranch
},
384 pickup_branch
=> $request->{branchcode
} || $request->{borrowerbranch
},
386 reservedate
=> $request->{reservedate
},
387 reservenotes
=> $request->{reservenotes
},
389 $allocated_items{$request->{itemnumber
}}++;
390 $num_items_remaining--;
393 # it's title-level request that will take up one item
394 $num_items_remaining--;
398 # group available items by branch
399 my %items_by_branch = ();
400 foreach my $item (@
$available_items) {
401 next unless $item->{holdallowed
};
403 push @
{ $items_by_branch{ $automatic_return ?
$item->{homebranch
}
404 : $item->{holdingbranch
} } }, $item
405 unless exists $allocated_items{ $item->{itemnumber
} };
407 return unless keys %items_by_branch;
409 # now handle the title-level requests
410 $num_items_remaining = scalar(@
$available_items) - scalar(keys %allocated_items);
412 foreach my $request (@
$hold_requests) {
413 last if $num_items_remaining == 0;
414 next if defined($request->{itemnumber
}); # already handled these
416 # look for local match first
417 my $pickup_branch = $request->{branchcode
} || $request->{borrowerbranch
};
418 my ($itemnumber, $holdingbranch);
420 my $holding_branch_items = $automatic_return ?
undef : $items_by_branch{$pickup_branch};
421 if ( $holding_branch_items ) {
422 foreach my $item (@
$holding_branch_items) {
423 if ( $request->{borrowerbranch
} eq $item->{homebranch
} ) {
424 $itemnumber = $item->{itemnumber
};
428 $holdingbranch = $pickup_branch;
429 $itemnumber ||= $holding_branch_items->[0]->{itemnumber
};
431 elsif ($transport_cost_matrix) {
432 $pull_branches = [keys %items_by_branch];
433 $holdingbranch = least_cost_branch
( $pickup_branch, $pull_branches, $transport_cost_matrix );
434 if ( $holdingbranch ) {
436 my $holding_branch_items = $items_by_branch{$holdingbranch};
437 foreach my $item (@
$holding_branch_items) {
438 next if $request->{borrowerbranch
} ne $item->{homebranch
};
440 $itemnumber = $item->{itemnumber
};
443 $itemnumber ||= $holding_branch_items->[0]->{itemnumber
};
446 warn "No transport costs for $pickup_branch";
450 unless ($itemnumber) {
451 # not found yet, fall back to basics
452 if ($branches_to_use) {
453 $pull_branches = $branches_to_use;
455 $pull_branches = [keys %items_by_branch];
458 foreach my $branch (@
$pull_branches) {
459 my $holding_branch_items = $items_by_branch{$branch}
462 $holdingbranch ||= $branch;
463 foreach my $item (@
$holding_branch_items) {
464 next if $pickup_branch ne $item->{homebranch
};
466 $itemnumber = $item->{itemnumber
};
467 $holdingbranch = $branch;
471 $itemnumber ||= $items_by_branch{$holdingbranch}->[0]->{itemnumber
}
476 my $holding_branch_items = $items_by_branch{$holdingbranch}
477 or die "Have $itemnumber, $holdingbranch, but no items!";
478 @
$holding_branch_items = grep { $_->{itemnumber
} != $itemnumber } @
$holding_branch_items;
479 delete $items_by_branch{$holdingbranch} unless @
$holding_branch_items;
481 $item_map{$itemnumber} = {
482 borrowernumber
=> $request->{borrowernumber
},
483 biblionumber
=> $request->{biblionumber
},
484 holdingbranch
=> $holdingbranch,
485 pickup_branch
=> $pickup_branch,
487 reservedate
=> $request->{reservedate
},
488 reservenotes
=> $request->{reservenotes
},
490 $num_items_remaining--;
496 =head2 CreatePickListFromItemMap
500 sub CreatePicklistFromItemMap
{
501 my $item_map = shift;
503 my $dbh = C4
::Context
->dbh;
505 my $sth_load=$dbh->prepare("
506 INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
507 cardnumber,reservedate,title, itemcallnumber,
508 holdingbranch,pickbranch,notes, item_level_request)
509 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
512 foreach my $itemnumber (sort keys %$item_map) {
513 my $mapped_item = $item_map->{$itemnumber};
514 my $biblionumber = $mapped_item->{biblionumber
};
515 my $borrowernumber = $mapped_item->{borrowernumber
};
516 my $pickbranch = $mapped_item->{pickup_branch
};
517 my $holdingbranch = $mapped_item->{holdingbranch
};
518 my $reservedate = $mapped_item->{reservedate
};
519 my $reservenotes = $mapped_item->{reservenotes
};
520 my $item_level = $mapped_item->{item_level
};
522 my $item = GetItem
($itemnumber);
523 my $barcode = $item->{barcode
};
524 my $itemcallnumber = $item->{itemcallnumber
};
526 my $borrower = GetMember
('borrowernumber'=>$borrowernumber);
527 my $cardnumber = $borrower->{'cardnumber'};
528 my $surname = $borrower->{'surname'};
529 my $firstname = $borrower->{'firstname'};
530 my $phone = $borrower->{'phone'};
532 my $bib = GetBiblioData
($biblionumber);
533 my $title = $bib->{title
};
535 $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
536 $cardnumber, $reservedate, $title, $itemcallnumber,
537 $holdingbranch, $pickbranch, $reservenotes, $item_level);
541 =head2 AddToHoldTargetMap
545 sub AddToHoldTargetMap
{
546 my $item_map = shift;
548 my $dbh = C4
::Context
->dbh;
551 INSERT INTO hold_fill_targets
(borrowernumber
, biblionumber
, itemnumber
, source_branchcode
, item_level_request
)
552 VALUES
(?
, ?
, ?
, ?
, ?
)
554 my $sth_insert = $dbh->prepare($insert_sql);
556 foreach my $itemnumber (keys %$item_map) {
557 my $mapped_item = $item_map->{$itemnumber};
558 $sth_insert->execute($mapped_item->{borrowernumber
}, $mapped_item->{biblionumber
}, $itemnumber,
559 $mapped_item->{holdingbranch
}, $mapped_item->{item_level
});
563 # Helper functions, not part of any interface
566 return $_[0] unless $_[0];
572 sub load_branches_to_pull_from
{
573 my $static_branch_list = C4
::Context
->preference("StaticHoldsQueueWeight")
576 my @branches_to_use = map _trim
($_), split /,/, $static_branch_list;
578 @branches_to_use = shuffle
(@branches_to_use) if C4
::Context
->preference("RandomizeHoldsQueueWeight");
580 return \
@branches_to_use;
583 sub least_cost_branch
{
586 my ($to, $from, $transport_cost_matrix) = @_;
588 # Nothing really spectacular: supply to branch, a list of potential from branches
589 # and find the minimum from - to value from the transport_cost_matrix
590 return $from->[0] if @
$from == 1;
592 my ($least_cost, @branch);
594 my $cell = $transport_cost_matrix->{$to}{$_};
595 next if $cell->{disable_transfer
};
597 my $cost = $cell->{cost
};
598 next unless defined $cost; # XXX should this be reported?
600 unless (defined $least_cost) {
606 next if $cost > $least_cost;
608 if ($cost == $least_cost) {
619 # XXX return a random @branch with minimum cost instead of the first one;
620 # return $branch[0] if @branch == 1;