import { type CommonReservedFields, type NoReservedFields, defaultGqlPermission, defaultPermission, } from "@tailor-platform/erp-kit/core"; import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk"; import { inventorySupplyPlanLifecycle } from "./inventorySupplyPlan.lifecycle.generated"; export const SUPPLY_PLAN_SOURCE_TYPES = ["PURCHASE_ORDER", "TRANSFER_ORDER"] as const; const builtins = (params: { itemType?: TailorAnyDBType; siteType?: TailorAnyDBType }) => { const itemId = db.uuid().description("Foreign key to Item"); const siteId = db.uuid().description("Destination site for the expected supply"); return { sourceType: db .enum(SUPPLY_PLAN_SOURCE_TYPES) .description("Source document type: PURCHASE_ORDER or TRANSFER_ORDER"), sourceId: db .uuid() .description( "ID of the source document (e.g., PurchaseOrder.id). Generic reference; not a typed foreign key.", ), sourceLineId: db .uuid() .description( "ID of the source supply line (e.g., PurchaseOrderLine.id). In the standard modules this is the unique source unit for one supply projection.", ), itemId: params.itemType ? itemId.relation({ type: "n-1", toward: { type: params.itemType, as: "item" }, }) : itemId, siteId: params.siteType ? siteId.relation({ type: "n-1", toward: { type: params.siteType, as: "site" }, }) : siteId, expectedQuantity: db .decimal() .description("Committed expected quantity for this ATP supply slice"), receivedQuantity: db .decimal() .description( "Cumulative quantity already received against this source line; open quantity is derived as expectedQuantity minus receivedQuantity", ), status: db .enum(inventorySupplyPlanLifecycle.states) .description( "Projection lifecycle status: OPEN while expected supply remains, CLOSED when it no longer contributes open supply", ), expectedDate: db.date().description("Latest expected receipt date from the source line"), }; }; type ReservedFields = keyof ReturnType | CommonReservedFields; export interface CreateInventorySupplyPlanTypeParams> { fields?: NoReservedFields; itemType?: TailorAnyDBType; siteType?: TailorAnyDBType; } export function createInventorySupplyPlanType>( params: CreateInventorySupplyPlanTypeParams, ) { return db .table("InventorySupplyPlan", { ...builtins(params), ...((params.fields ?? {}) as F), ...db.fields.timestamps(), }) .indexes( { fields: ["sourceType", "sourceLineId"], unique: true, name: "inventory_supply_plan_source_idx", }, { fields: ["sourceType", "sourceId"], unique: false, name: "inventory_supply_plan_source_document_idx", }, ) .permission(defaultPermission) .gqlPermission(defaultGqlPermission); } export const inventorySupplyPlan = createInventorySupplyPlanType({});