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