import { type CommonReservedFields, type NoReservedFields, defaultGqlPermission, defaultPermission, } from "@tailor-platform/erp-kit/core"; import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk"; import { stockAdjustment } from "./stockAdjustment"; import { storageLocation } from "./storageLocation"; export const LINE_ADJUSTMENT_DIRECTIONS = ["INCREASE", "DECREASE"] as const; export const STOCK_CATEGORIES = ["AVAILABLE", "BLOCKED"] as const; const builtins = (params: { itemType?: TailorAnyDBType }) => { const itemId = db.uuid().description("Foreign key to Item"); return { stockAdjustmentId: db .uuid() .relation({ type: "n-1", toward: { type: stockAdjustment, as: "stockAdjustment" }, backward: "stockAdjustmentLines", }) .description("Foreign key to StockAdjustment"), itemId: params.itemType ? itemId.relation({ type: "n-1", toward: { type: params.itemType, as: "item" }, backward: "stockAdjustmentLines", }) : itemId, storageLocationId: db .uuid() .relation({ type: "n-1", toward: { type: storageLocation, as: "storageLocation" }, backward: "stockAdjustmentLines", }) .description("Storage location where the adjustment occurs"), quantity: db.decimal().description("Quantity (always positive)"), adjustmentDirection: db .enum([...LINE_ADJUSTMENT_DIRECTIONS] as [string, ...string[]], { optional: true }) .description("Direction of stock adjustment (required for CORRECTION): INCREASE or DECREASE"), fromStockCategory: db .enum([...STOCK_CATEGORIES] as [string, ...string[]], { optional: true }) .description( "Source stock category (only used for SCRAP): AVAILABLE (default) or BLOCKED for scrapping blocked stock", ), unitCost: db.decimal({ optional: true }).description("Cost per unit (optional)"), }; }; type ReservedFields = keyof ReturnType | CommonReservedFields; export interface CreateStockAdjustmentLineTypeParams> { fields?: NoReservedFields; itemType?: TailorAnyDBType; } export function createStockAdjustmentLineType>( params: CreateStockAdjustmentLineTypeParams, ) { return db .table("StockAdjustmentLine", { ...builtins(params), ...((params.fields ?? {}) as F), ...db.fields.timestamps(), }) .permission(defaultPermission) .gqlPermission(defaultGqlPermission); } export const stockAdjustmentLine = createStockAdjustmentLineType({});