import { defaultGqlPermission, defaultPermission } from "@tailor-platform/erp-kit/core"; import { db, type TailorAnyDBType } from "@tailor-platform/sdk"; export const AVERAGE_COST_EVENT_TYPES = ["RECEIPT", "ISSUE", "COST_ADJUSTMENT"] as const; const builtins = (params: { itemType?: TailorAnyDBType; companyType?: TailorAnyDBType }) => { const itemId = db.uuid().description("Foreign key to Item"); const companyId = db.uuid().description("Foreign key to Company"); return { itemId: params.itemType ? itemId.relation({ type: "n-1", toward: { type: params.itemType, as: "item" }, backward: "averageCosts", }) : itemId, companyId: params.companyType ? companyId.relation({ type: "n-1", toward: { type: params.companyType, as: "company" }, backward: "averageCosts", }) : companyId, sequence: db.int().description("1-based event position within the item and company"), eventType: db.enum(AVERAGE_COST_EVENT_TYPES).description("Costed event that produced this row"), quantityBefore: db.decimal().description("On-hand quantity before this event"), unitCostBefore: db.decimal().description("Moving average unit cost before this event"), quantity: db .decimal() .description("Signed quantity the event moved; positive for receipts, negative for issues"), unitCost: db .decimal({ optional: true }) .description("Unit cost the event was valued at; null for COST_ADJUSTMENT events"), quantityAfter: db.decimal().description("On-hand quantity after this event"), unitCostAfter: db.decimal().description("Moving average unit cost after this event"), }; }; export function createAverageCostType(params: { itemType?: TailorAnyDBType; companyType?: TailorAnyDBType; }) { return db .table("AverageCost", { ...builtins(params), createdAt: db.fields.timestamps().createdAt, }) .indexes({ fields: ["itemId", "companyId", "sequence"], unique: true, name: "average_cost_item_company_sequence_unique_idx", }) .permission(defaultPermission) .gqlPermission(defaultGqlPermission); } export const averageCost = createAverageCostType({});