import { defaultGqlPermission, defaultPermission } from "@tailor-platform/erp-kit/core"; import { db, type TailorAnyDBType } from "@tailor-platform/sdk"; export const COSTING_METHODS = ["STANDARD", "FIFO", "AVERAGE"] as const; const builtins = (params: { companyType?: TailorAnyDBType }) => { const companyId = db .uuid() .description("Company whose accounts and ledger the policy's costing posts to"); return { name: db.string().description("Policy display name"), companyId: params.companyType ? companyId.relation({ type: "n-1", toward: { type: params.companyType, as: "company" }, backward: "valuationPolicies", }) : companyId, costingMethod: db.enum(COSTING_METHODS).description("Costing method"), // Duplicates companyId so uniqueness enforces at most one default per // company (partial unique indexes are not supported). defaultCompanyId: db .uuid({ optional: true }) .unique() .description( "Set to the owning company's id when this policy is the company's default, null otherwise; items without an ItemValuation record are auto-assigned the default on their first valuation-affecting movement in the company", ), // Posting accounts for costing journals. inventoryAccountId: db.uuid().description("Posting account for the inventory asset side"), accrualAccountId: db .uuid() .description("Posting account for the uninvoiced-receipt accrual (GR/IR clearing)"), invoicePriceVarianceAccountId: db .uuid() .description("Posting account for the invoice-versus-order price difference (clearing)"), cogsAccountId: db.uuid().description("Posting account for cost of goods sold on issues"), ppvAccountId: db.uuid().description("Posting account for purchase price variance"), adjustmentAccountId: db .uuid() .description( "Posting account for inventory gain/loss: correction adjustments and scrap write-offs", ), standardCostAdjustmentAccountId: db .uuid() .description("Posting account for standard cost revision revaluations"), consumedPriceVarianceAccountId: db .uuid() .description( "Posting account for acquisition price variances that cannot be restated to their consumption", ), }; }; export interface CreateValuationPolicyTypeParams { companyType?: TailorAnyDBType; } export function createValuationPolicyType(params: CreateValuationPolicyTypeParams = {}) { return db .table("ValuationPolicy", { ...builtins(params), ...db.fields.timestamps(), }) .permission(defaultPermission) .gqlPermission(defaultGqlPermission); } export const valuationPolicy = createValuationPolicyType();