import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core"; import { recordBillings, type SalesOrder } from "../domain/salesOrder"; import type { Transaction } from "../generated/kysely-tailordb"; import { LineNotFoundError } from "../lib/errors.generated"; import { createSalesOrderRepository, type SalesOrderRepository, } from "../repository/salesOrderRepository"; export interface SalesOrderLineBillingInput { salesOrderLineId: string; billedQuantity: string; } export interface RecalculateSalesOrderBillingStatusInput { lineBillings: SalesOrderLineBillingInput[]; } export async function run( db: Transaction, input: RecalculateSalesOrderBillingStatusInput, _ctx: CommandContext, repositoryFactory: (db: Transaction) => SalesOrderRepository = createSalesOrderRepository, ) { if (input.lineBillings.length === 0) { return ok({ salesOrderIds: [] as string[] }); } const lineIds = [...new Set(input.lineBillings.map((billing) => billing.salesOrderLineId))]; const repository = repositoryFactory(db); const orders = await repository.findByLineIds(lineIds, { forUpdate: true }); if (orders.length === 0) { return err(new LineNotFoundError(lineIds[0])); } const recordedOrders: SalesOrder[] = []; for (const order of orders) { const recorded = recordBillings(order, input.lineBillings); if (!recorded.ok) { return recorded; } recordedOrders.push(recorded.value); } // Re-check after locking: a concurrent draft edit may have deleted a line. const recordedLineIds = new Set( recordedOrders.flatMap((order) => order.lines.map((line) => line.id)), ); const missingLineId = lineIds.find((lineId) => !recordedLineIds.has(lineId)); if (missingLineId) { return err(new LineNotFoundError(missingLineId)); } for (const order of recordedOrders) { await repository.save(order); } return ok({ salesOrderIds: recordedOrders.map((order) => order.id) }); }