import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/core"; import { Decimal } from "decimal.js"; import type { DB } from "../generated/kysely-tailordb"; export function summarizeOrderProgress( lines: { quantity: string; fulfilledQuantity?: string | null; billedQuantity?: string | null; }[], ) { let totalOrdered = new Decimal(0); let totalFulfilled = new Decimal(0); let totalBilled = new Decimal(0); for (const line of lines) { totalOrdered = totalOrdered.plus(line.quantity); totalFulfilled = totalFulfilled.plus(line.fulfilledQuantity ?? "0"); totalBilled = totalBilled.plus(line.billedQuantity ?? "0"); } return { totalOrdered: totalOrdered.toString(), totalFulfilled: totalFulfilled.toString(), totalBilled: totalBilled.toString(), openToFulfill: Decimal.max(totalOrdered.minus(totalFulfilled), 0).toString(), openToBill: Decimal.max(totalOrdered.minus(totalBilled), 0).toString(), }; } export interface GetSalesOrderInput { id: string; } export async function run(db: ReadonlyDB, input: GetSalesOrderInput) { const salesOrder = await db .selectFrom("SalesOrder") .selectAll() .where("id", "=", input.id) .executeTakeFirst(); if (!salesOrder) return ok({ salesOrder: null }); const lines = await db .selectFrom("SalesOrderLine") .selectAll() .where("salesOrderId", "=", input.id) .execute(); return ok({ salesOrder: { ...salesOrder, lines, fulfillmentTotals: summarizeOrderProgress(lines), }, }); }