import type { VoyageRow } from '@/hooks/use-vessels-data';
function todayISO(): string {
const d = new Date();
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
}
function csvEscape(value: string | number | null | undefined): string {
if (value === null || value === undefined) return '';
const s = String(value);
if (/[",\n\r]/.test(s)) return `"${s.replace(/"/g, '""')}"`;
return s;
}
function downloadBlob(content: string, mime: string, filename: string): void {
const blob = new Blob([content], { type: mime });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
export type VoyageExportContext = {
voyages: VoyageRow[];
filter: string;
sort: string;
totals: {
revenue: number;
margin: number;
fuelCost: number;
delayCost: number;
avgTce: number;
voyageCount: number;
};
topRoutes?:
| Array<{
route: string;
voyages: number;
totalRevenue: number;
avgTce: number;
avgMargin: number;
}>
| undefined;
};
export function exportVoyagesToCsv(ctx: VoyageExportContext): void {
const headers = [
'Voyage Ref',
'Voyage ID',
'Vessel',
'Vessel ID',
'Vessel Class',
'Route',
'Origin',
'Destination',
'Cargo Type',
'Charter Type',
'Status',
'Distance (nm)',
'Duration (days)',
'Delay (h)',
'Revenue (USD)',
'Total Cost (USD)',
'Fuel Cost (USD)',
'Port Cost (USD)',
'Delay Cost (USD)',
'Net Margin (USD)',
'Margin %',
'TCE/day (USD)',
];
const lines = [headers.map(csvEscape).join(',')];
for (const v of ctx.voyages) {
lines.push(
[
v.voyageRef,
v.voyageId,
v.vesselName,
v.vesselId,
v.vesselClass,
v.route,
v.origin,
v.destination,
v.cargoType,
v.charterType,
v.status,
Math.round(v.distanceNm),
Number(v.durationDays).toFixed(2),
Math.round(v.delayHours),
Math.round(v.estimatedRevenue),
Math.round(v.operatingCost),
Math.round(v.fuelCost),
Math.round(v.portCost),
Math.round(v.delayCost),
Math.round(v.marginEstimate),
(v.marginPct * 100).toFixed(2),
Math.round(v.tce),
]
.map(csvEscape)
.join(','),
);
}
const filterTag = ctx.filter && ctx.filter !== 'all' ? `-${ctx.filter}` : '';
const filename = `voyage-economics${filterTag}-${todayISO()}.csv`;
downloadBlob(lines.join('\n'), 'text/csv;charset=utf-8;', filename);
}
const fmtUsd = (n: number): string => {
if (Math.abs(n) >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;
if (Math.abs(n) >= 1e3) return `$${(n / 1e3).toFixed(1)}K`;
return `$${Math.round(n).toLocaleString()}`;
};
const escapeHtml = (s: string): string =>
s
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"');
export function exportVoyagesToPdf(ctx: VoyageExportContext): void {
const { voyages, totals, topRoutes, filter, sort } = ctx;
const date = todayISO();
const top10 = [...voyages]
.sort((a, b) => (b.estimatedRevenue || 0) - (a.estimatedRevenue || 0))
.slice(0, 10);
const maxTopRouteRev = Math.max(1, ...(topRoutes ?? []).map((r) => r.totalRevenue));
const filterLabel = filter === 'all' ? 'All voyages' : `Filter: ${filter}`;
const sortLabel = `Sort: ${sort}`;
const html = `
Voyage Economics — ${date}
Print / Save as PDF
Voyage Economics Report
Generated ${date} · ${filterLabel} · ${sortLabel} · ${totals.voyageCount} voyages
Fleet Revenue
${fmtUsd(totals.revenue)}
${totals.voyageCount} voyages
Fleet Margin
${fmtUsd(totals.margin)}
${totals.revenue > 0 ? `${((totals.margin / totals.revenue) * 100).toFixed(1)}% avg` : '—'}
Avg TCE/day
${totals.avgTce > 0 ? fmtUsd(totals.avgTce) : '—'}
per vessel/day
Delay Exposure
${fmtUsd(totals.delayCost)}
fleet-wide cost
${
topRoutes && topRoutes.length > 0
? `Top Routes by Revenue
# Route Voyages Revenue Share Avg Margin
${topRoutes
.slice(0, 10)
.map((r, i) => {
const pct = (r.totalRevenue / maxTopRouteRev) * 100;
return `
${i + 1}
${escapeHtml(r.route)}
${r.voyages}
${fmtUsd(r.totalRevenue)}
${fmtUsd(r.avgMargin)}
`;
})
.join('')}
`
: ''
}
Top 10 Voyages by Revenue
Voyage Vessel Route Status
Revenue Cost
TCE/day Margin
${top10
.map(
(v) => `
${escapeHtml(v.voyageRef ?? `#${v.voyageId}`)}
${escapeHtml(v.vesselName)}
${escapeHtml(v.route)}
${escapeHtml(v.status.replace('_', ' '))}
${fmtUsd(v.estimatedRevenue)}
${fmtUsd(v.operatingCost)}
${v.tce > 0 ? fmtUsd(v.tce) : '—'}
${fmtUsd(v.marginEstimate)} (${(v.marginPct * 100).toFixed(1)}%)
`,
)
.join('')}
`;
const w = window.open('', '_blank');
if (!w) {
// Pop-up blocked — fall back to a download of the HTML so the operator
// can still open + print it.
downloadBlob(html, 'text/html;charset=utf-8;', `voyage-economics-${date}.html`);
return;
}
w.document.open();
w.document.write(html);
w.document.close();
w.document.title = `Voyage Economics — ${date}`;
}