3 This is part of the YARRG website. YARRG is a tool and website
4 for assisting players of Yohoho Puzzle Pirates.
6 Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
7 Copyright (C) 2009 Clare Boothby
9 YARRG's client code etc. is covered by the ordinary GNU GPL (v3 or later).
10 The YARRG website is covered by the GNU Affero GPL v3 or later, which
11 basically means that every installation of the website will let you
14 This program is free software: you can redistribute it and/or modify
15 it under the terms of the GNU Affero General Public License as
16 published by the Free Software Foundation, either version 3 of the
17 License, or (at your option) any later version.
19 This program is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 GNU Affero General Public License for more details.
24 You should have received a copy of the GNU Affero General Public License
25 along with this program. If not, see <http://www.gnu.org/licenses/>.
27 Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
28 are used without permission. This program is not endorsed or
29 sponsored by Three Rings.
32 This Mason component is the core trade planner for a specific route.
43 <& query_age:pageload &>
47 my $loss_per_league= defined $routeparams->{LossPerLeaguePct}
48 ? $routeparams->{LossPerLeaguePct}*0.01 : 1e-7;
49 my $loss_per_delay_slot= 1e-8;
56 my $expected_total_profit;
58 my $sd_condition= sub {
60 my $islandid= $islandids[$ix];
61 if (defined $islandid) {
62 return "${bs}.islandid = $islandid";
64 push @query_params, $archipelagoes[$ix];
65 return "${bs}_islands.archipelago = ?";
69 my $specific= !grep { !defined $_ } @islandids;
71 my %ipair2subflowinfs;
72 # $ipair2subflowinfs{$orgi,$dsti}= [ [$orgix,$distix], ... ]
75 # $subflows[0]{Flow} = { ... }
76 # $subflows[0]{Org} = $orgix
77 # $subflows[0]{Dst} = $dstix
79 foreach my $org_i (0..$#islandids) {
80 my $org_isle= $islandids[$org_i];
81 my $org_cond= $sd_condition->('sell',$org_i);
83 foreach my $dst_i ($org_i..$#islandids) {
84 my $dst_isle= $islandids[$dst_i];
85 # Don't ever consider sailing things round the houses:
86 next if defined $dst_isle and
87 grep { $dst_isle == $_ } @islandids[$org_i..$dst_i-1];
88 next if defined $org_isle and
89 grep { $org_isle == $_ } @islandids[$org_i+1..$dst_i];
91 if ($dst_i==$org_i and !defined $org_isle) {
92 # we always want arbitrage, but mentioning an arch
93 # once shouldn't produce intra-arch trades
94 $dst_cond= "sell.islandid = buy.islandid";
96 $dst_cond= $sd_condition->('buy',$dst_i);
98 push @dst_conds, $dst_cond;
101 push @{ $ipair2subflowinfs{$org_isle,$dst_isle} },
105 push @flow_conds, "$org_cond AND (
112 SELECT sell_islands.islandname org_name,
113 sell_islands.islandid org_id,
114 sell.price org_price,
115 sell.qty org_qty_stall,
116 sell_stalls.stallname org_stallname,
117 sell.stallid org_stallid,
118 sell_uploads.timestamp org_timestamp,
119 buy_islands.islandname dst_name,
120 buy_islands.islandid dst_id,
122 buy.qty dst_qty_stall,
123 buy_stalls.stallname dst_stallname,
124 buy.stallid dst_stallid,
125 buy_uploads.timestamp dst_timestamp,
126 ".($qa->{ShowStalls} ? "
127 sell.qty org_qty_agg,
130 (SELECT sum(qty) FROM sell AS sell_agg
131 WHERE sell_agg.commodid = commods.commodid
132 AND sell_agg.islandid = sell.islandid
133 AND sell_agg.price = sell.price) org_qty_agg,
134 (SELECT sum(qty) FROM buy AS buy_agg
135 WHERE buy_agg.commodid = commods.commodid
136 AND buy_agg.islandid = buy.islandid
137 AND buy_agg.price = buy.price) dst_qty_agg,
139 commods.commodname commodname,
140 commods.commodid commodid,
141 commods.unitmass unitmass,
142 commods.unitvolume unitvolume,
143 commods.ordval ordval,
144 commods.posinclass posinclass,
145 commods.commodclassid commodclassid,
147 buy.price - sell.price unitprofit
149 JOIN sell ON commods.commodid = sell.commodid
150 JOIN buy ON commods.commodid = buy.commodid
151 JOIN islands AS sell_islands ON sell.islandid = sell_islands.islandid
152 JOIN islands AS buy_islands ON buy.islandid = buy_islands.islandid
153 JOIN uploads AS sell_uploads ON sell.islandid = sell_uploads.islandid
154 JOIN uploads AS buy_uploads ON buy.islandid = buy_uploads.islandid
155 JOIN stalls AS sell_stalls ON sell.stallid = sell_stalls.stallid
156 JOIN stalls AS buy_stalls ON buy.stallid = buy_stalls.stallid
157 JOIN dists ON aiid = sell.islandid AND biid = buy.islandid
162 AND buy.price > sell.price
163 ORDER BY org_name, dst_name, commodname, unitprofit DESC,
164 org_price, dst_price DESC,
165 org_stallname, dst_stallname
168 my $sth= $dbh->prepare($stmt);
169 $sth->execute(@query_params);
172 my $distquery= $dbh->prepare("
173 SELECT dist FROM dists WHERE aiid = ? AND biid = ?
177 my $d= $dists{$from}{$to};
178 return $d if defined $d;
179 $distquery->execute($from,$to);
180 $d = $distquery->fetchrow_array();
181 defined $d or die "$from $to ?";
182 $dists{$from}{$to}= $d;
186 my @cols= ({ NoSort => 1 });
190 foreach my $name (@_) {
191 my $col= { Name => $name, %$base };
192 $col->{Numeric}=1 if !$col->{Text};
197 if ($qa->{ShowStalls}) {
198 $addcols->({ Text => 1 }, qw(
199 org_name org_stallname
200 dst_name dst_stallname
203 $addcols->({Text => 1 }, qw(
207 $addcols->({ Text => 1 }, qw(commodname));
208 $addcols->({ DoReverse => 1 },
209 qw( org_price org_qty_agg dst_price dst_qty_agg
211 $addcols->({ DoReverse => 1, SortColKey => 'MarginSortKey' },
214 $addcols->({ DoReverse => 1 },
215 qw( unitprofit MaxQty MaxCapital MaxProfit dist
217 foreach my $v (qw(MaxMass MaxVolume)) {
219 DoReverse => 1, Total => 0, SortColKey => "${v}SortKey" }, $v);
224 % if ($qa->{'debug'}) {
227 <% join(' | ',@query_params) |h %>
231 <& dumptable:start, qa => $qa, sth => $sth &>
234 % while ($got= $sth->fetchrow_hashref()) {
237 my $f= $flows[$#flows];
240 grep { $f->{$_} ne $got->{$_} }
241 qw(org_id org_price dst_id dst_price commodid)
243 # Make a new flow rather than adding to the existing one
246 Ix => scalar(@flows),
249 $f->{"org_stallid"}= $f->{"dst_stallid"}= 'all'
250 if !$qa->{ShowStalls};
253 foreach my $od (qw(org dst)) {
255 $got->{"${od}_stallname"}
257 $got->{"${od}_qty_stall"}
262 <& dumptable:row, qa => $qa, sth => $sth, row => $f &>
264 <& dumptable:end, qa => $qa &>
267 % if (@islandids==1) {
268 % if (defined $islandids[0]) {
269 Searched for arbitrage trades only.
271 Searched for arbitrage trades only, in <% $archipelagoes[0] |h %>
272 <a href="docs#arbitrage">[?]</a>.
281 print 'No profitable trading opportunities were found.';
285 foreach my $f (@flows) {
287 $f->{MaxQty}= $f->{'org_qty_agg'} < $f->{'dst_qty_agg'}
288 ? $f->{'org_qty_agg'} : $f->{'dst_qty_agg'};
289 $f->{MaxProfit}= $f->{MaxQty} * $f->{'unitprofit'};
290 $f->{MaxCapital}= $f->{MaxQty} * $f->{'org_price'};
292 $f->{MaxMassSortKey}= $f->{MaxQty} * $f->{'unitmass'};
293 $f->{MaxVolumeSortKey}= $f->{MaxQty} * $f->{'unitvolume'};
294 foreach my $v (qw(Mass Volume)) {
295 $f->{"Max$v"}= sprintf "%.1f", $f->{"Max${v}SortKey"} * 1e-6;
298 $f->{MarginSortKey}= sprintf "%d",
299 $f->{'dst_price'} * 10000 / $f->{'org_price'};
300 $f->{Margin}= sprintf "%3.1f%%",
301 $f->{'dst_price'} * 100.0 / $f->{'org_price'} - 100.0;
303 $f->{ExpectedUnitProfit}=
304 $f->{'dst_price'} * (1.0 - $loss_per_league) ** $f->{'dist'}
307 $dists{'org_id'}{'dst_id'}= $f->{'dist'};
309 my @uid= $f->{commodid};
310 foreach my $od (qw(org dst)) {
315 $f->{"${od}_stallid"}
316 if $qa->{ShowStalls};
318 $f->{UidLong}= join '_', @uid;
326 my $this= $uue % $base;
327 #print STDERR "uue=$uue this=$this ";
332 $cmpu .= chr($this + ($this < 26 ? ord('a') :
333 $this < 52 ? ord('A')-26
335 #print STDERR " uue=$uue this=$this cmpu=$cmpu\n";
336 die "$cmpu $uue ?" if length $cmpu > 20;
340 $f->{UidShort}= $cmpu;
342 if ($qa->{'debug'}) {
347 my $v= m/^[a-z]/ ? ord($&)-ord('a') :
348 m/^[A-Z]/ ? ord($&)-ord('A')+26 :
349 m/^[0-9]/ ? ord($&)-ord('0')+52 :
355 #print STDERR "(next)\n";
357 die "$f->{UidShort} $_ ?" unless defined $mul;
358 $outuid[$#outuid] += $v * $mul;
360 #print STDERR "$f->{UidShort} $_ $& v=$v mul=$mul ord()=".ord($&).
361 # "[vs.".ord('a').",".ord('A').",".ord('0')."]".
362 # " outuid=@outuid\n";
367 my $recons_long= join '_', @outuid;
368 $f->{UidLong} eq $recons_long or
369 die "$f->{UidLong} = $f->{UidShort} = $recons_long ?";
372 if (defined $qa->{"R$f->{UidShort}"} &&
373 !defined $qa->{"T$f->{UidShort}"}) {
376 my $sfis= $ipair2subflowinfs{$f->{'org_id'},$f->{'dst_id'}};
377 foreach my $sfi (@$sfis) {
382 Var => sprintf "f%ss%s_c%d_p%d_%d_p%d_%d",
385 $sfi->[0], $f->{'org_price'},
386 $sfi->[1], $f->{'dst_price'}
388 push @{ $f->{Subflows} }, $subflow;
389 push @subflows, $subflow;
395 % my $optimise= $specific;
400 Route contains archipelago(es), not just specific islands.
402 Therefore, optimal voyage trade plan not calculated.
404 % } else { # ========== OPTMISATION ==========
413 foreach my $sf (@subflows) {
414 my $eup= $sf->{Flow}{ExpectedUnitProfit};
415 $eup *= (1.0-$loss_per_delay_slot) ** $sf->{Org};
417 %+.20f %s", $eup, $sf->{Var};
425 foreach my $flow (@flows) {
426 next if $flow->{Suppress};
427 foreach my $od (qw(org dst)) {
428 my $limname= join '_', (
430 'i'.$flow->{"${od}_id"},
431 'c'.$flow->{'commodid'},
432 $flow->{"${od}_price"},
433 $flow->{"${od}_stallid"},
436 push @{ $avail_lims{$limname}{SubflowVars} },
437 map { $_->{Var} } @{ $flow->{Subflows} };
438 $avail_lims{$limname}{Qty}= $flow->{"${od}_qty_agg"};
441 foreach my $limname (sort keys %avail_lims) {
442 my $c= $avail_lims{$limname};
444 sprintf(" %-30s","$limname:")." ".
445 join("+", @{ $c->{SubflowVars} }).
446 " <= ".$c->{Qty}."\n";
449 foreach my $ci (0..($#islandids-1)) {
452 foreach my $f (@flows) {
453 next if $f->{Suppress};
454 my @relsubflow= grep {
457 } @{ $f->{Subflows} };
458 next unless @relsubflow;
459 die unless @relsubflow == 1;
460 push @rel_subflows, @relsubflow;
461 #print " RELEVANT $ci $relsubflow[0]->{Var} ";
463 #print " RELEVANT $ci COUNT ".scalar(@rel_subflows)." ";
464 if (!@rel_subflows) {
465 foreach my $mv (qw(mass volume)) {
466 $sail_total[$ci]{$mv}= 0;
471 my $applylimit= sub {
472 my ($mv, $f2val) = @_;
473 my $max= $routeparams->{"Max".ucfirst $mv};
474 $max= 1e9 unless defined $max;
475 #print " DEFINED MAX $mv $max ";
477 ". sprintf("%-10s","${mv}_$ci:")." ".
479 #print " PART MAX $_->{Var} $_->{Flow}{Ix} ";
480 $f2val->($_->{Flow}) .' '. $_->{Var};
485 $applylimit->('mass', sub { $_[0]{'unitmass'} *1e-3 });
486 $applylimit->('volume', sub { $_[0]{'unitvolume'}*1e-3 });
487 $applylimit->('capital', sub { $_[0]{'org_price'} });
494 ", map { "$_->{Var} >= 0" } @subflows)."
501 ", map { $_->{Var} } @subflows)."
506 if ($qa->{'debug'}) {
515 my $input= pipethrough_prep();
516 print $input $cplex or die $!;
517 my $output= pipethrough_run_along($input, undef, 'glpsol',
518 qw(glpsol --tmlim 2 --memlim 5 --intopt --cuts --bfs
519 --cpxlp /dev/stdin -o /dev/stdout));
520 print "<pre>\n" if $qa->{'debug'};
521 my $found_section= 0;
526 print encode_entities($_) if $qa->{'debug'};
527 if (m/^\s*No\.\s+(Row|Column) name\s+(?:St\s+)?Activity\s/) {
528 die "$_ $found_section ?" if $found_section>0;
532 if (m/^Objective:\s+totalprofit = (\d+(?:\.\d*)?) /) {
533 $expected_total_profit= $1;
535 next unless $found_section==1;
536 if (!length $continuation) {
537 next if !$continuation && m/^[- ]+$/;
542 if (m/^ \s* \d+ \s+ \w+ $/x) {
547 $_= $continuation.$_;
549 my ($varname, $qty) = m/^
551 (\w+) \s+ (?: [A-Z*]+ \s+ )?
553 /x or die "$cplex \n==\n $glpsol_out $_ ?";
554 if ($varname =~ m/^f(\d+)s(\d+)_/) {
555 my ($ix,$orgix) = ($1,$2);
556 my $flow= $flows[$ix] or die;
557 my @relsubflow= grep { $_->{Org} == $orgix }
558 @{ $flow->{Subflows} };
559 die "$ix $orgix @relsubflow" unless @relsubflow == 1;
560 my $sf= $relsubflow[0];
562 $sf->{OptProfit}= $qty * $flow->{'unitprofit'};
563 $sf->{OptCapital}= $qty * $flow->{'org_price'};
564 } elsif ($varname =~ m/^(mass|volume)_(\d+)$/) {
565 my ($mv,$ix) = ($1,$2);
566 $sail_total[$ix]{$mv}= $qty;
569 print "</pre>\n" if $qa->{'debug'};
570 my $prerr= "\n=====\n$cplex\n=====\n$glpsol_out\n=====\n ";
571 pipethrough_run_finish($output,$prerr);
572 map { defined $_->{OptQty} or die "$prerr $_->{Flow}{Ix}" } @subflows;
573 defined $expected_total_profit or die "$prerr ?";
576 $addcols->({ DoReverse => 1, TotalSubflows => 1, Special => sub {
577 my ($flow,$col,$v,$spec) = @_;
578 if ($flow->{ExpectedUnitProfit} < 0) {
580 $spec->{String}= '(Small margin)';
581 $spec->{Align}= 'align=center';
586 $addcols->({ Total => 0, DoReverse => 1, TotalSubflows => 1 }, qw(
592 % } # ========== OPTIMISATION ==========
594 % if (!printable($m)) {
598 <li><a href="#plan">Voyage trading plan</a>
600 <li><a href="#summary">Summary statistics</a>
602 <input type=submit name=printable_pdf value="PDF">
603 <input type=submit name=printable_html value="HTML">
604 <input type=submit name=printable_ps value="PostScript">
605 <input type=submit name=printable_pdf2 value="PDF 2-up">
606 <input type=submit name=printable_ps2 value="PostScript 2-up">
609 <li><a href="#dataage">Data age summary</a>
610 <li><a href="#trades">Relevant trades</a>
613 % my @tl= gmtime $now or die $!;
615 Generated by YARRG at <strong><%
616 sprintf "%04d-%02d-%02d %02d:%02d:%02d UTC",
617 $tl[5]+1900, @tl[4,3,2,1,0]
621 % if ($optimise) { # ========== TRADING PLAN ==========
623 % my $iquery= $dbh->prepare('SELECT islandname FROM islands
624 % WHERE islandid = ?');
626 % my $total_total= 0;
629 <h2><a name="plan">Voyage trading plan</a></h2>
631 <table class="data" rules=groups <% printable($m) ? 'width=100%' : '' %> >
633 % if (!printable($m)) { return '<tbody>'; }
634 %# return "<tr><td colspan=7><hr>";
635 % my ($c)= qw(40 00)[$_[0]];
636 % return "<tr><td bgcolor=\"#${c}${c}${c}\" height=1 colspan=7>";
639 % foreach my $i (0..$#islandids) {
642 % $iquery->execute($islandids[$i]);
643 % my ($islandname) = $iquery->fetchrow_array();
646 <strong>Start at <% $islandname |h %></strong>
647 <td><a href="docs#posinclass">[?]</a>
650 % my $this_dist= $distance->($islandids[$i-1],$islandids[$i]);
651 % $total_dist += $this_dist;
655 foreach my $sf (@subflows) {
656 next unless $sf->{Org} < $i && $sf->{Dst} >= $i;
658 $sf->{OptQty} * $sf->{Flow}{'dst_price'};
661 <strong>Sail to <% $islandname |h %></strong>
662 - <% $this_dist |h %> leagues,
663 <% $total_value %>poe at risk
669 #print "<tr><td colspan=7>" if $qa->{'debug'};
670 foreach my $od (qw(org dst)) {
671 #print " [[ i $i od $od " if $qa->{'debug'};
672 foreach my $sf (@subflows) {
674 next unless $sf->{ucfirst $od} == $i;
675 #print " FLOW $f->{Ix} SUB #$sf->{Org}..$sf->{Dst} "
677 next unless $sf->{OptQty};
678 my $arbitrage= $f->{'org_id'} == $f->{'dst_id'};
679 die if $arbitrage and $sf->{Org} != $sf->{Dst};
680 my $price= $f->{"${od}_price"};
681 my $stallname= $f->{"${od}_stallname"};
682 my $todo= \$flowlists{$od}{
683 (sprintf "%010d", $f->{'ordval'}),
685 (sprintf "%07d", ($od eq 'dst' ?
686 9999999-$price : $price)),
694 $$todo->{'commodname'}= $f->{'commodname'};
695 $$todo->{'posinclass'}= '';
696 my $incl= $f->{'posinclass'};
698 my $findclass= $dbh->prepare(<<END);
699 SELECT commodclass, maxposinclass FROM commodclasses WHERE commodclassid = ?
701 $findclass->execute($f->{'commodclassid'});
702 my $classinfo= $findclass->fetchrow_hashref();
704 my $clname= $classinfo->{'commodclass'};
705 my $desc= encode_entities(sprintf "%s is under %s",
706 $f->{'commodname'}, $clname);
707 my $abbrev= substr($clname,0,1);
709 my $maxpic= $classinfo->{'maxposinclass'};
710 $desc.= (sprintf ", commodity %d of %d",
712 if ($classinfo->{'maxposinclass'} >= 8) {
713 my @tmbs= qw(tt t m b bb);
714 my $tmbi= ($incl+0.5)*$#tmbs/$maxpic;
715 $abbrev.= " ".$tmbs[$tmbi];
718 $$todo->{'posinclass'}=
719 "<div class=mouseover title=\"$desc\">"
722 $$todo->{'stallname'}= $stallname;
723 $$todo->{Price}= $price;
724 $$todo->{Timestamp}= $f->{"${od}_timestamp"};
725 $$todo->{Qty} += $sf->{OptQty};
726 $$todo->{Total}= $$todo->{Price} * $$todo->{Qty};
727 $$todo->{Stalls}= $f->{"${od}Stalls"};
728 $$todo->{"${od}Arbitrage"}= 1 if $arbitrage;
730 #print "]] " if $qa->{'debug'};
732 #print "</tr>" if $qa->{'debug'};
734 my ($total, $total_to_show);
736 my $show_total= sub {
737 my ($totaldesc, $sign) = @_;
738 if (defined $total) {
739 die if defined $total_to_show;
740 $total_total += $sign * $total;
741 $total_to_show= [ $totaldesc, $total ];
746 my $show_total_now= sub {
748 return unless defined $total_to_show;
749 my ($totaldesc,$totalwas) = @$total_to_show;
753 <td colspan=3><% $xinfo %>
754 <td colspan=2 align=right><% $totaldesc %>
755 <td align=right><% $totalwas |h %> total
757 $total_to_show= undef;
760 % my $show_flows= sub {
761 % my ($od,$arbitrage,$collectdeliver) = @_;
762 % my $todo= $flowlists{$od};
763 % return unless $todo;
764 % foreach my $tkey (sort keys %$todo) {
765 % my $t= $todo->{$tkey};
766 % next if $t->{"${od}Arbitrage"} != $arbitrage;
767 % $show_total_now->('');
768 % if (!$age_reported++) {
769 % my $age= $now - $t->{Timestamp};
770 % my $cellid= "da_${i}";
771 % $da_ages{$cellid}= $age;
773 (Data age: <span id="<% $cellid %>"><% prettyprint_age($age) %></span>)
774 % } elsif (!defined $total) {
778 % $total += $t->{Total};
779 % my $span= 0 + keys %{ $t->{Stalls} };
780 % my $td= "td rowspan=$span";
781 % tr_datarow($m,$dline);
782 <<% $td %>><% $collectdeliver %>
783 <<% $td %>><% $t->{'commodname'} |h %>
784 <<% $td %>><% $t->{'posinclass'} %>
786 % my @stalls= sort keys %{ $t->{Stalls} };
788 % my $name= $stalls[$_[0]];
793 <<% $td %> align=right><% $t->{Price} |h %> poe ea.
794 <<% $td %> align=right><% $t->{Qty} |h %> unit(s)
795 <<% $td %> align=right><% $t->{Total} |h %> total
797 % foreach my $stallix (1..$#stalls) {
798 % tr_datarow($m,$dline);
799 % $pstall->($stallix);
807 $show_flows->('dst',0,'Deliver'); $show_total->('Proceeds',1);
808 $show_flows->('org',1,'Collect'); $show_total->('(Arbitrage) outlay',-1);
809 $show_flows->('dst',1,'Deliver'); $show_total->('(Arbitrage) proceeds',1);
810 $show_flows->('org',0,'Collect'); $show_total->('Outlay',-1);
812 if ($i < $#islandids) {
813 $totals .= "In hold $sail_total[$i]{mass}kg,".
814 " $sail_total[$i]{volume} l";
815 my $delim= '; spare ';
817 my ($max, $got, $units) = @_;
818 return unless defined $max;
820 $totals .= sprintf "%g %s", ($max-$got), $units;
823 $domv->($routeparams->{MaxMass}, $sail_total[$i]{mass}, 'kg');
824 $domv->($routeparams->{MaxVolume}, $sail_total[$i]{volume}, 'l');
827 $show_total_now->($totals);
829 </%perl><a name="summary"></a>
830 <% $tbody->(1) %><tr>
831 <td colspan=3>Total distance: <% $total_dist %> leagues.
832 <td colspan=3 align=right>Overall net cash flow
833 <td align=right><strong><%
834 $total_total < 0 ? -$total_total." loss" : $total_total." gain"
837 <& query_age:dataages, id2age => \%da_ages &>
838 Expected average profit:
839 approx. <strong><% sprintf "%d", $expected_total_profit %></strong> poe
840 (considering expected losses, but ignoring rum consumed)
842 % } # ========== TRADING PLAN ==========
844 % if (!printable($m)) {
845 <h2><a name="dataage">Data age summary</a></h2>
847 my $sth_i= $dbh->prepare(<<END);
848 SELECT archipelago, islandid, islandname, timestamp
849 FROM uploads NATURAL JOIN islands
852 my $sth_a= $dbh->prepare(<<END);
853 SELECT archipelago, islandid, islandname, timestamp
854 FROM uploads NATURAL JOIN islands
855 WHERE archipelago = ?
864 my $row= $sth_current->fetchrow_hashref();
866 next if $idone{$row->{'islandid'}}++;
870 return undef if $ix < 0;
871 my $iid= $islandids[$ix];
873 $sth_i->execute($iid);
874 $sth_current= $sth_i;
876 my $arch= $archipelagoes[$ix];
877 die unless defined $arch && length $arch;
878 $sth_a->execute($arch);
879 $sth_current= $sth_a;
885 <&| query_age:agestable, now => $now, fetchrow => $fetchrow &>
886 Islands shown in reverse order of visits.<br>
890 % if (!printable($m)) {
893 % my $cdspan= $qa->{ShowStalls} ? ' colspan=2' : '';
894 % my $cdstall= $qa->{ShowStalls} ? '<th>Stall</th>' : '';
895 <h2><a name="trades">Relevant trades</a></h2>
896 <table class="data" id="trades" rules=groups>
899 <% $qa->{ShowStalls} ? '<colgroup span=2>' : '' %>
911 <th<% $cdspan %>>Collect
912 <th<% $cdspan %>>Deliver
914 <th colspan=2>Collect
915 <th colspan=2>Deliver
921 <th colspan=3>Planned
926 <th>Island <% $cdstall %>
927 <th>Island <% $cdstall %>
948 <tr id="trades_sort">
949 % foreach my $col (@cols) {
953 % foreach my $flowix (0..$#flows) {
954 % my $flow= $flows[$flowix];
955 % my $rowid= "id_row_$flow->{UidShort}";
956 <tr id="<% $rowid %>" class="datarow<% $flowix & 1 %>">
957 <td><input type=hidden name=R<% $flow->{UidShort} %> value="">
958 <input type=checkbox name=T<% $flow->{UidShort} %> value=""
959 <% $flow->{Suppress} ? '' : 'checked' %> >
961 % while ($ci < @cols) {
962 % my $col= $cols[$ci];
965 % Align => ($col->{Text} ? '' : 'align=right')
967 % my $cn= $col->{Name};
969 % if (!$col->{TotalSubflows}) {
973 % $v += $_->{$cn} foreach @{ $flow->{Subflows} };
975 % if ($col->{Special}) { $col->{Special}($flow,$col,$v,$spec); }
976 % $col->{Total} += $v
977 % if defined $col->{Total} and not $flow->{Suppress};
978 % $v='' if !$col->{Text} && !$v;
979 % my $sortkey= $col->{SortColKey} ?
980 % $flow->{$col->{SortColKey}} : $v;
981 % $ts_sortkeys{$ci}{$rowid}= $sortkey;
982 <td <% $spec->{Span} ? "colspan=$spec->{Span}" : ''
984 %>><% exists $spec->{String} ? $spec->{String} : $v |h %>
985 % $ci += $spec->{Span};
988 <tr id="trades_total">
991 % foreach my $ci (3..$#cols) {
992 % my $col= $cols[$ci];
994 % if (defined $col->{Total}) {
995 <% $col->{Total} |h %>
1000 <&| tabsort, cols => \@cols, table => 'trades', rowclass => 'datarow',
1001 throw => 'trades_sort', tbrow => 'trades_total' &>
1002 ts_sortkeys= <% to_json_protecttags(\%ts_sortkeys) %>;
1005 <input type=submit name=update value="Update">