Bug 16011: $VERSION - remove use vars $VERSION
[koha.git] / C4 / HoldsQueue.pm
1 package C4::HoldsQueue;
2
3 # Copyright 2011 Catalyst IT
4 #
5 # This file is part of Koha.
6 #
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.
11 #
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.
16 #
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>.
19
20 # FIXME: expand perldoc, explain intended logic
21
22 use strict;
23 use warnings;
24
25 use C4::Context;
26 use C4::Search;
27 use C4::Items;
28 use C4::Branch;
29 use C4::Circulation;
30 use C4::Members;
31 use C4::Biblio;
32 use Koha::DateUtils;
33
34 use List::Util qw(shuffle);
35 use List::MoreUtils qw(any);
36 use Data::Dumper;
37
38 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
39 BEGIN {
40     $VERSION = 3.03;
41     require Exporter;
42     @ISA = qw(Exporter);
43     @EXPORT_OK = qw(
44         &CreateQueue
45         &GetHoldsQueueItems
46
47         &TransportCostMatrix
48         &UpdateTransportCostMatrix
49      );
50 }
51
52
53 =head1 FUNCTIONS
54
55 =head2 TransportCostMatrix
56
57   TransportCostMatrix();
58
59 Returns Transport Cost Matrix as a hashref <to branch code> => <from branch code> => cost
60
61 =cut
62
63 sub TransportCostMatrix {
64     my $dbh   = C4::Context->dbh;
65     my $transport_costs = $dbh->selectall_arrayref("SELECT * FROM transport_cost",{ Slice => {} });
66
67     my $today = dt_from_string();
68     my $calendars;
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} = {
76             cost             => $cost,
77             disable_transfer => $disabled
78         };
79
80         if ( C4::Context->preference("HoldsQueueSkipClosed") ) {
81             $calendars->{$from} ||= Koha::Calendar->new( branchcode => $from );
82             $transport_cost_matrix{$to}{$from}{disable_transfer} ||=
83               $calendars->{$from}->is_holiday( $today );
84         }
85
86     }
87     return \%transport_cost_matrix;
88 }
89
90 =head2 UpdateTransportCostMatrix
91
92   UpdateTransportCostMatrix($records);
93
94 Updates full Transport Cost Matrix table. $records is an arrayref of records.
95 Records: { frombranch => <code>, tobranch => <code>, cost => <figure>, disable_transfer => <0,1> }
96
97 =cut
98
99 sub UpdateTransportCostMatrix {
100     my ($records) = @_;
101     my $dbh   = C4::Context->dbh;
102
103     my $sth = $dbh->prepare("INSERT INTO transport_cost (frombranch, tobranch, cost, disable_transfer) VALUES (?, ?, ?, ?)");
104
105     $dbh->do("TRUNCATE TABLE transport_cost");
106     foreach (@$records) {
107         my $cost = $_->{cost};
108         my $from = $_->{frombranch};
109         my $to = $_->{tobranch};
110         if ($_->{disable_transfer}) {
111             $cost ||= 0;
112         }
113         elsif ( !defined ($cost) || ($cost !~ m/(0|[1-9][0-9]*)(\.[0-9]*)?/o) ) {
114             warn  "Invalid $from -> $to cost $cost - must be a number >= 0, disablig";
115             $cost = 0;
116             $_->{disable_transfer} = 1;
117         }
118         $sth->execute( $from, $to, $cost, $_->{disable_transfer} ? 1 : 0 );
119     }
120 }
121
122 =head2 GetHoldsQueueItems
123
124   GetHoldsQueueItems($branch);
125
126 Returns hold queue for a holding branch. If branch is omitted, then whole queue is returned
127
128 =cut
129
130 sub GetHoldsQueueItems {
131     my ($branchlimit) = @_;
132     my $dbh   = C4::Context->dbh;
133
134     my @bind_params = ();
135     my $query = q/SELECT tmp_holdsqueue.*, biblio.author, items.ccode, items.itype, biblioitems.itemtype, items.location, items.enumchron, items.cn_sort, biblioitems.publishercode,biblio.copyrightdate,biblioitems.publicationyear,biblioitems.pages,biblioitems.size,biblioitems.publicationyear,biblioitems.isbn,items.copynumber
136                   FROM tmp_holdsqueue
137                        JOIN biblio      USING (biblionumber)
138                   LEFT JOIN biblioitems USING (biblionumber)
139                   LEFT JOIN items       USING (  itemnumber)
140                 /;
141     if ($branchlimit) {
142         $query .=" WHERE tmp_holdsqueue.holdingbranch = ?";
143         push @bind_params, $branchlimit;
144     }
145     $query .= " ORDER BY ccode, location, cn_sort, author, title, pickbranch, reservedate";
146     my $sth = $dbh->prepare($query);
147     $sth->execute(@bind_params);
148     my $items = [];
149     while ( my $row = $sth->fetchrow_hashref ){
150         my $record = GetMarcBiblio($row->{biblionumber});
151         if ($record){
152             $row->{subtitle} = [ map { $_->{subfield} } @{ GetRecordValue( 'subtitle', $record, '' ) } ];
153             $row->{parts} = GetRecordValue('parts',$record,'')->[0]->{subfield};
154             $row->{numbers} = GetRecordValue('numbers',$record,'')->[0]->{subfield};
155         }
156
157         # return the bib-level or item-level itype per syspref
158         if (!C4::Context->preference('item-level_itypes')) {
159             $row->{itype} = $row->{itemtype};
160         }
161         delete $row->{itemtype};
162
163         push @$items, $row;
164     }
165     return $items;
166 }
167
168 =head2 CreateQueue
169
170   CreateQueue();
171
172 Top level function that turns reserves into tmp_holdsqueue and hold_fill_targets.
173
174 =cut
175
176 sub CreateQueue {
177     my $dbh   = C4::Context->dbh;
178
179     $dbh->do("DELETE FROM tmp_holdsqueue");  # clear the old table for new info
180     $dbh->do("DELETE FROM hold_fill_targets");
181
182     my $total_bibs            = 0;
183     my $total_requests        = 0;
184     my $total_available_items = 0;
185     my $num_items_mapped      = 0;
186
187     my $branches_to_use;
188     my $transport_cost_matrix;
189     my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix");
190     if ($use_transport_cost_matrix) {
191         $transport_cost_matrix = TransportCostMatrix();
192         unless (keys %$transport_cost_matrix) {
193             warn "UseTransportCostMatrix set to yes, but matrix not populated";
194             undef $transport_cost_matrix;
195         }
196     }
197     unless ($transport_cost_matrix) {
198         $branches_to_use = load_branches_to_pull_from();
199     }
200
201     my $bibs_with_pending_requests = GetBibsWithPendingHoldRequests();
202
203     foreach my $biblionumber (@$bibs_with_pending_requests) {
204         $total_bibs++;
205         my $hold_requests   = GetPendingHoldRequestsForBib($biblionumber);
206         my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_to_use);
207         $total_requests        += scalar(@$hold_requests);
208         $total_available_items += scalar(@$available_items);
209
210         my $item_map = MapItemsToHoldRequests($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix);
211         $item_map  or next;
212         my $item_map_size = scalar(keys %$item_map)
213           or next;
214
215         $num_items_mapped += $item_map_size;
216         CreatePicklistFromItemMap($item_map);
217         AddToHoldTargetMap($item_map);
218         if (($item_map_size < scalar(@$hold_requests  )) and
219             ($item_map_size < scalar(@$available_items))) {
220             # DOUBLE CHECK, but this is probably OK - unfilled item-level requests
221             # FIXME
222             #warn "unfilled requests for $biblionumber";
223             #warn Dumper($hold_requests), Dumper($available_items), Dumper($item_map);
224         }
225     }
226 }
227
228 =head2 GetBibsWithPendingHoldRequests
229
230   my $biblionumber_aref = GetBibsWithPendingHoldRequests();
231
232 Return an arrayref of the biblionumbers of all bibs
233 that have one or more unfilled hold requests.
234
235 =cut
236
237 sub GetBibsWithPendingHoldRequests {
238     my $dbh = C4::Context->dbh;
239
240     my $bib_query = "SELECT DISTINCT biblionumber
241                      FROM reserves
242                      WHERE found IS NULL
243                      AND priority > 0
244                      AND reservedate <= CURRENT_DATE()
245                      AND suspend = 0
246                      ";
247     my $sth = $dbh->prepare($bib_query);
248
249     $sth->execute();
250     my $biblionumbers = $sth->fetchall_arrayref();
251
252     return [ map { $_->[0] } @$biblionumbers ];
253 }
254
255 =head2 GetPendingHoldRequestsForBib
256
257   my $requests = GetPendingHoldRequestsForBib($biblionumber);
258
259 Returns an arrayref of hashrefs to pending, unfilled hold requests
260 on the bib identified by $biblionumber.  The following keys
261 are present in each hashref:
262
263     biblionumber
264     borrowernumber
265     itemnumber
266     priority
267     branchcode
268     reservedate
269     reservenotes
270     borrowerbranch
271
272 The arrayref is sorted in order of increasing priority.
273
274 =cut
275
276 sub GetPendingHoldRequestsForBib {
277     my $biblionumber = shift;
278
279     my $dbh = C4::Context->dbh;
280
281     my $request_query = "SELECT biblionumber, borrowernumber, itemnumber, priority, reserves.branchcode,
282                                 reservedate, reservenotes, borrowers.branchcode AS borrowerbranch
283                          FROM reserves
284                          JOIN borrowers USING (borrowernumber)
285                          WHERE biblionumber = ?
286                          AND found IS NULL
287                          AND priority > 0
288                          AND reservedate <= CURRENT_DATE()
289                          AND suspend = 0
290                          ORDER BY priority";
291     my $sth = $dbh->prepare($request_query);
292     $sth->execute($biblionumber);
293
294     my $requests = $sth->fetchall_arrayref({});
295     return $requests;
296
297 }
298
299 =head2 GetItemsAvailableToFillHoldRequestsForBib
300
301   my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_ar);
302
303 Returns an arrayref of items available to fill hold requests
304 for the bib identified by C<$biblionumber>.  An item is available
305 to fill a hold request if and only if:
306
307     * it is not on loan
308     * it is not withdrawn
309     * it is not marked notforloan
310     * it is not currently in transit
311     * it is not lost
312     * it is not sitting on the hold shelf
313     * it is not damaged (unless AllowHoldsOnDamagedItems is on)
314
315 =cut
316
317 sub GetItemsAvailableToFillHoldRequestsForBib {
318     my ($biblionumber, $branches_to_use) = @_;
319
320     my $dbh = C4::Context->dbh;
321     my $items_query = "SELECT itemnumber, homebranch, holdingbranch, itemtypes.itemtype AS itype
322                        FROM items ";
323
324     if (C4::Context->preference('item-level_itypes')) {
325         $items_query .=   "LEFT JOIN itemtypes ON (itemtypes.itemtype = items.itype) ";
326     } else {
327         $items_query .=   "JOIN biblioitems USING (biblioitemnumber)
328                            LEFT JOIN itemtypes USING (itemtype) ";
329     }
330     $items_query .=   "WHERE items.notforloan = 0
331                        AND holdingbranch IS NOT NULL
332                        AND itemlost = 0
333                        AND withdrawn = 0";
334     $items_query .= "  AND damaged = 0" unless C4::Context->preference('AllowHoldsOnDamagedItems');
335     $items_query .= "  AND items.onloan IS NULL
336                        AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
337                        AND itemnumber NOT IN (
338                            SELECT itemnumber
339                            FROM reserves
340                            WHERE biblionumber = ?
341                            AND itemnumber IS NOT NULL
342                            AND (found IS NOT NULL OR priority = 0)
343                         )
344                        AND items.biblionumber = ?";
345
346     my @params = ($biblionumber, $biblionumber);
347     if ($branches_to_use && @$branches_to_use) {
348         $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
349         push @params, @$branches_to_use;
350     }
351     my $sth = $dbh->prepare($items_query);
352     $sth->execute(@params);
353
354     my $itm = $sth->fetchall_arrayref({});
355     my @items = grep { ! scalar GetTransfers($_->{itemnumber}) } @$itm;
356     return [ grep {
357         my $rule = GetBranchItemRule($_->{homebranch}, $_->{itype});
358         $_->{holdallowed} = $rule->{holdallowed};
359     } @items ];
360 }
361
362 =head2 MapItemsToHoldRequests
363
364   MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
365
366 =cut
367
368 sub MapItemsToHoldRequests {
369     my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
370
371     # handle trival cases
372     return unless scalar(@$hold_requests) > 0;
373     return unless scalar(@$available_items) > 0;
374
375     # identify item-level requests
376     my %specific_items_requested = map { $_->{itemnumber} => 1 }
377                                    grep { defined($_->{itemnumber}) }
378                                    @$hold_requests;
379
380     # group available items by itemnumber
381     my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
382
383     # items already allocated
384     my %allocated_items = ();
385
386     # map of items to hold requests
387     my %item_map = ();
388
389     # figure out which item-level requests can be filled
390     my $num_items_remaining = scalar(@$available_items);
391     foreach my $request (@$hold_requests) {
392         last if $num_items_remaining == 0;
393
394         # is this an item-level request?
395         if (defined($request->{itemnumber})) {
396             # fill it if possible; if not skip it
397             if (exists $items_by_itemnumber{$request->{itemnumber}} and
398                 not exists $allocated_items{$request->{itemnumber}}) {
399                 $item_map{$request->{itemnumber}} = {
400                     borrowernumber => $request->{borrowernumber},
401                     biblionumber => $request->{biblionumber},
402                     holdingbranch =>  $items_by_itemnumber{$request->{itemnumber}}->{holdingbranch},
403                     pickup_branch => $request->{branchcode} || $request->{borrowerbranch},
404                     item_level => 1,
405                     reservedate => $request->{reservedate},
406                     reservenotes => $request->{reservenotes},
407                 };
408                 $allocated_items{$request->{itemnumber}}++;
409                 $num_items_remaining--;
410             }
411         } else {
412             # it's title-level request that will take up one item
413             $num_items_remaining--;
414         }
415     }
416
417     # group available items by branch
418     my %items_by_branch = ();
419     foreach my $item (@$available_items) {
420         next unless $item->{holdallowed};
421
422         push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
423           unless exists $allocated_items{ $item->{itemnumber} };
424     }
425     return \%item_map unless keys %items_by_branch;
426
427     # now handle the title-level requests
428     $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
429     my $pull_branches;
430     foreach my $request (@$hold_requests) {
431         last if $num_items_remaining == 0;
432         next if defined($request->{itemnumber}); # already handled these
433
434         # look for local match first
435         my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
436         my ($itemnumber, $holdingbranch);
437
438         my $holding_branch_items = $items_by_branch{$pickup_branch};
439         if ( $holding_branch_items ) {
440             foreach my $item (@$holding_branch_items) {
441                 if ( $request->{borrowerbranch} eq $item->{homebranch} ) {
442                     $itemnumber = $item->{itemnumber};
443                     last;
444                 }
445             }
446             $holdingbranch = $pickup_branch;
447         }
448         elsif ($transport_cost_matrix) {
449             $pull_branches = [keys %items_by_branch];
450             $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
451             if ( $holdingbranch ) {
452
453                 my $holding_branch_items = $items_by_branch{$holdingbranch};
454                 foreach my $item (@$holding_branch_items) {
455                     next if $request->{borrowerbranch} ne $item->{homebranch};
456
457                     $itemnumber = $item->{itemnumber};
458                     last;
459                 }
460             }
461             else {
462                 next;
463             }
464         }
465
466         unless ($itemnumber) {
467             # not found yet, fall back to basics
468             if ($branches_to_use) {
469                 $pull_branches = $branches_to_use;
470             } else {
471                 $pull_branches = [keys %items_by_branch];
472             }
473
474             # Try picking items where the home and pickup branch match first
475             PULL_BRANCHES:
476             foreach my $branch (@$pull_branches) {
477                 my $holding_branch_items = $items_by_branch{$branch}
478                   or next;
479
480                 $holdingbranch ||= $branch;
481                 foreach my $item (@$holding_branch_items) {
482                     next if $pickup_branch ne $item->{homebranch};
483                     next if ( $item->{holdallowed} == 1 && $item->{homebranch} ne $request->{borrowerbranch} );
484
485                     $itemnumber = $item->{itemnumber};
486                     $holdingbranch = $branch;
487                     last PULL_BRANCHES;
488                 }
489             }
490
491             # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight
492             unless ( $itemnumber ) {
493                 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
494                     if ( $holdingbranch && ( $current_item->{holdallowed} == 2 || $request->{borrowerbranch} eq $current_item->{homebranch} ) ) {
495                         $itemnumber = $current_item->{itemnumber};
496                         last; # quit this loop as soon as we have a suitable item
497                     }
498                 }
499             }
500
501             # Now try for items for any item that can fill this hold
502             unless ( $itemnumber ) {
503                 PULL_BRANCHES2:
504                 foreach my $branch (@$pull_branches) {
505                     my $holding_branch_items = $items_by_branch{$branch}
506                       or next;
507
508                     foreach my $item (@$holding_branch_items) {
509                         next if ( $item->{holdallowed} == 1 && $item->{homebranch} ne $request->{borrowerbranch} );
510
511                         $itemnumber = $item->{itemnumber};
512                         $holdingbranch = $branch;
513                         last PULL_BRANCHES2;
514                     }
515                 }
516             }
517         }
518
519         if ($itemnumber) {
520             my $holding_branch_items = $items_by_branch{$holdingbranch}
521               or die "Have $itemnumber, $holdingbranch, but no items!";
522             @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
523             delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
524
525             $item_map{$itemnumber} = {
526                 borrowernumber => $request->{borrowernumber},
527                 biblionumber => $request->{biblionumber},
528                 holdingbranch => $holdingbranch,
529                 pickup_branch => $pickup_branch,
530                 item_level => 0,
531                 reservedate => $request->{reservedate},
532                 reservenotes => $request->{reservenotes},
533             };
534             $num_items_remaining--;
535         }
536     }
537     return \%item_map;
538 }
539
540 =head2 CreatePickListFromItemMap
541
542 =cut
543
544 sub CreatePicklistFromItemMap {
545     my $item_map = shift;
546
547     my $dbh = C4::Context->dbh;
548
549     my $sth_load=$dbh->prepare("
550         INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
551                                     cardnumber,reservedate,title, itemcallnumber,
552                                     holdingbranch,pickbranch,notes, item_level_request)
553         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
554     ");
555
556     foreach my $itemnumber  (sort keys %$item_map) {
557         my $mapped_item = $item_map->{$itemnumber};
558         my $biblionumber = $mapped_item->{biblionumber};
559         my $borrowernumber = $mapped_item->{borrowernumber};
560         my $pickbranch = $mapped_item->{pickup_branch};
561         my $holdingbranch = $mapped_item->{holdingbranch};
562         my $reservedate = $mapped_item->{reservedate};
563         my $reservenotes = $mapped_item->{reservenotes};
564         my $item_level = $mapped_item->{item_level};
565
566         my $item = GetItem($itemnumber);
567         my $barcode = $item->{barcode};
568         my $itemcallnumber = $item->{itemcallnumber};
569
570         my $borrower = GetMember('borrowernumber'=>$borrowernumber);
571         my $cardnumber = $borrower->{'cardnumber'};
572         my $surname = $borrower->{'surname'};
573         my $firstname = $borrower->{'firstname'};
574         my $phone = $borrower->{'phone'};
575
576         my $bib = GetBiblioData($biblionumber);
577         my $title = $bib->{title};
578
579         $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
580                            $cardnumber, $reservedate, $title, $itemcallnumber,
581                            $holdingbranch, $pickbranch, $reservenotes, $item_level);
582     }
583 }
584
585 =head2 AddToHoldTargetMap
586
587 =cut
588
589 sub AddToHoldTargetMap {
590     my $item_map = shift;
591
592     my $dbh = C4::Context->dbh;
593
594     my $insert_sql = q(
595         INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request)
596                                VALUES (?, ?, ?, ?, ?)
597     );
598     my $sth_insert = $dbh->prepare($insert_sql);
599
600     foreach my $itemnumber (keys %$item_map) {
601         my $mapped_item = $item_map->{$itemnumber};
602         $sth_insert->execute($mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
603                              $mapped_item->{holdingbranch}, $mapped_item->{item_level});
604     }
605 }
606
607 # Helper functions, not part of any interface
608
609 sub _trim {
610     return $_[0] unless $_[0];
611     $_[0] =~ s/^\s+//;
612     $_[0] =~ s/\s+$//;
613     $_[0];
614 }
615
616 sub load_branches_to_pull_from {
617     my @branches_to_use;
618
619     my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight");
620     @branches_to_use = map { _trim($_) } split( /,/, $static_branch_list )
621       if $static_branch_list;
622
623     @branches_to_use =
624       Koha::Database->new()->schema()->resultset('Branch')
625       ->get_column('branchcode')->all()
626       unless (@branches_to_use);
627
628     @branches_to_use = shuffle(@branches_to_use)
629       if C4::Context->preference("RandomizeHoldsQueueWeight");
630
631     my $today = dt_from_string();
632     if ( C4::Context->preference('HoldsQueueSkipClosed') ) {
633         @branches_to_use = grep {
634             !Koha::Calendar->new( branchcode => $_ )
635               ->is_holiday( $today )
636         } @branches_to_use;
637     }
638
639     return \@branches_to_use;
640 }
641
642 sub least_cost_branch {
643
644     #$from - arrayref
645     my ($to, $from, $transport_cost_matrix) = @_;
646
647     # Nothing really spectacular: supply to branch, a list of potential from branches
648     # and find the minimum from - to value from the transport_cost_matrix
649     return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{$from->[0]}->{disable_transfer} != 1 );
650
651     # If the pickup library is in the list of libraries to pull from,
652     # return that library right away, it is obviously the least costly
653     return ($to) if any { $_ eq $to } @$from;
654
655     my ($least_cost, @branch);
656     foreach (@$from) {
657         my $cell = $transport_cost_matrix->{$to}{$_};
658         next if $cell->{disable_transfer};
659
660         my $cost = $cell->{cost};
661         next unless defined $cost; # XXX should this be reported?
662
663         unless (defined $least_cost) {
664             $least_cost = $cost;
665             push @branch, $_;
666             next;
667         }
668
669         next if $cost > $least_cost;
670
671         if ($cost == $least_cost) {
672             push @branch, $_;
673             next;
674         }
675
676         @branch = ($_);
677         $least_cost = $cost;
678     }
679
680     return $branch[0];
681
682     # XXX return a random @branch with minimum cost instead of the first one;
683     # return $branch[0] if @branch == 1;
684 }
685
686
687 1;