import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core"; import { close } from "../domain/purchaseOrder"; import type { Transaction } from "../generated/kysely-tailordb"; import { PurchaseOrderNotFoundError } from "../lib/errors.generated"; import type { InventoryCommands } from "../module"; import { createPurchaseOrderRepository, type PurchaseOrderRepository, } from "../repository/purchaseOrderRepository"; export interface ClosePurchaseOrderInput { id: string; closeReason?: string; writeOffRemaining?: boolean; } export async function run( db: Transaction, input: ClosePurchaseOrderInput, ctx: CommandContext, inventoryCommands: Pick, repositoryFactory: (db: Transaction) => PurchaseOrderRepository = createPurchaseOrderRepository, ) { const repository = repositoryFactory(db); const order = await repository.findById(input.id, { forUpdate: true }); if (!order) { return err(new PurchaseOrderNotFoundError(input.id)); } const closed = close(order, { closeReason: input.closeReason, writeOffRemaining: input.writeOffRemaining, }); if (!closed.ok) { return closed; } await repository.save(closed.value); const closeResult = await inventoryCommands.closeInventorySupplyPlan( db, { target: "SOURCE_DOCUMENT", sourceType: "PURCHASE_ORDER", sourceId: input.id }, ctx, ); if (!closeResult.ok) return closeResult; return ok({ purchaseOrderId: closed.value.id }); }