import { type CommonReservedFields, type NoReservedFields, defaultGqlPermission, defaultPermission, } from "@tailor-platform/erp-kit/core"; import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk"; import { accountPayableDocumentLine } from "./accountPayableDocumentLine"; export const ACCOUNT_PAYABLE_DISTRIBUTION_TYPES = [ "MANUAL", "ACCRUAL", "INVOICE_PRICE_VARIANCE", ] as const; const builtins = (params: { accountType?: TailorAnyDBType }) => { const accountId = db.uuid().description("Foreign key to posting Account"); return { accountPayableDocumentLineId: db .uuid() .relation({ type: "n-1", toward: { type: accountPayableDocumentLine, as: "accountPayableDocumentLine" }, backward: "distributions", }) .description("Foreign key to the commercial AP document line"), correctionOfDistributionLineId: db .uuid({ optional: true }) .relation({ type: "n-1", toward: { type: "self" }, backward: "correctionDistributions", }) .description("Optional self-reference to the posted AP distribution line being corrected"), accountId: params.accountType ? accountId.relation({ type: "n-1", toward: { type: params.accountType, as: "account" }, backward: "accountPayableDistributionLines", }) : accountId, amount: db .decimal() .description("Distribution amount; signed only on INVOICE_PRICE_VARIANCE rows"), distributionType: db .enum(ACCOUNT_PAYABLE_DISTRIBUTION_TYPES) .description("Distribution type; non-MANUAL rows are system-derived"), description: db .string({ optional: true }) .description("Optional distribution line description"), }; }; type ReservedFields = keyof ReturnType | CommonReservedFields; export interface CreateAccountPayableDistributionLineTypeParams< F extends Record, > { fields?: NoReservedFields; accountType?: TailorAnyDBType; } export function createAccountPayableDistributionLineType< const F extends Record, >(params: CreateAccountPayableDistributionLineTypeParams) { return db .table("AccountPayableDistributionLine", { ...builtins(params), ...((params.fields ?? {}) as F), ...db.fields.timestamps(), }) .permission(defaultPermission) .gqlPermission(defaultGqlPermission); } export const accountPayableDistributionLine = createAccountPayableDistributionLineType({});