import { createContext, DomainError } from "@tailor-platform/erp-kit/app"; import { createResolver, t } from "@tailor-platform/sdk"; import { getDB } from "@/generated/kysely-tailordb"; import { invModulesExport } from "@/modules"; export default createResolver({ name: "setItemValuationPolicy", operation: "mutation", input: { itemId: t.string().description("Item ID"), companyId: t.string().description("Company the assignment applies to"), valuationPolicyId: t.string().description("Valuation policy ID (must belong to the company)"), }, body: async (context) => { const ctx = createContext(context); const db = getDB("main-db"); return db .transaction() .execute(async (trx) => { const result = await invModulesExport.commands.setItemValuationPolicy( trx, { itemId: context.input.itemId, companyId: context.input.companyId, valuationPolicyId: context.input.valuationPolicyId, }, ctx, ); if (!result.ok) { switch (result.error.code) { case "INVENTORY_ITEM_NOT_FOUND": throw new DomainError(`Item not found: ${context.input.itemId}`); case "INVENTORY_VALUATION_POLICY_NOT_FOUND": throw new DomainError( `Valuation policy not found: ${context.input.valuationPolicyId}`, ); case "INVENTORY_VALUATION_POLICY_COMPANY_MISMATCH": throw new DomainError("The valuation policy belongs to a different company"); case "INVENTORY_ITEM_VALUATION_POLICY_CHANGE_NOT_ALLOWED": throw new DomainError( "The valuation policy cannot be changed once the item has inventory ledger history in the company", ); case "INVENTORY_SITE_NOT_FOUND": throw new DomainError("A referenced site was not found."); case "UNAUTHENTICATED": throw new DomainError("Authentication is required"); case "INSUFFICIENT_PERMISSION": throw new DomainError("You do not have permission to perform this action"); default: throw result.error satisfies never; } } return { id: result.value.itemValuation.id }; }) .catch((err: unknown) => { if (err instanceof DomainError) throw err; throw new Error("Failed to set the item valuation policy", { cause: err }); }); }, output: t .object({ id: t.string().description("ItemValuation ID"), }) .description("Item valuation policy assignment"), });