33 lines
1.1 KiB
TypeScript
33 lines
1.1 KiB
TypeScript
|
|
import { eq } from 'drizzle-orm';
|
||
|
|
|
||
|
|
import { db } from '@/lib/db';
|
||
|
|
import { ports } from '@/lib/db/schema/ports';
|
||
|
|
import { convert } from '@/lib/services/currency';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Port's default currency for money normalisation. Falls back to USD
|
||
|
|
* when the column is null (legacy ports). Shared across the report
|
||
|
|
* services so every money figure lands in one reporting currency.
|
||
|
|
*/
|
||
|
|
export async function resolvePortCurrency(portId: string): Promise<string> {
|
||
|
|
const [row] = await db
|
||
|
|
.select({ defaultCurrency: ports.defaultCurrency })
|
||
|
|
.from(ports)
|
||
|
|
.where(eq(ports.id, portId));
|
||
|
|
return row?.defaultCurrency ?? 'USD';
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Convert `amount` from `from` → `to`. Returns the amount unchanged when
|
||
|
|
* the currencies match or a rate is unavailable (so a missing FX rate
|
||
|
|
* degrades to "report in source units" rather than dropping the figure).
|
||
|
|
*/
|
||
|
|
export async function normalizeAmount(amount: number, from: string, to: string): Promise<number> {
|
||
|
|
if (!amount) return amount;
|
||
|
|
const f = from.toUpperCase();
|
||
|
|
const t = to.toUpperCase();
|
||
|
|
if (f === t) return amount;
|
||
|
|
const converted = await convert(amount, f, t);
|
||
|
|
return converted?.result ?? amount;
|
||
|
|
}
|