@eristack/qups
Version:
Quantity / unit price / subtotal (QUPS) with 2-of-3 sources of truth, plus modifiers and tax — business line pricing on @eristack/money
1 lines • 102 kB
Source Map (JSON)
{"version":3,"sources":["../../src/backseat/index.ts","../../src/backseat/stores.ts","../../src/backseat/collections.ts","../../src/backseat/register.ts","../../src/core/calculate.ts","../../src/core/line.ts","../../src/core/modifier.ts","../../src/core/errors.ts","../../src/core/qups.ts","../../src/core/tax.ts","../../src/core/stores/fields.ts","../../src/core/stores/serialize.ts","../../src/core/create-qups.ts","../../src/backseat/qups-routes.ts"],"sourcesContent":["import type { BackseatStore } from \"@eristack/backseat\";\nimport { createMemoryBackseatStore } from \"@eristack/backseat/testing\";\nimport type { PricingLineStore, PricingProfileStore } from \"../core/stores/types.js\";\nimport {\n createBackseatPricingLineStore,\n createBackseatPricingProfileStore,\n} from \"./stores.js\";\n\nexport function createBackseatQupsStores(options: {\n store?: BackseatStore;\n} = {}): {\n backseatStore: BackseatStore;\n profiles: PricingProfileStore;\n lines: PricingLineStore;\n} {\n const backseatStore = options.store ?? createMemoryBackseatStore();\n return {\n backseatStore,\n profiles: createBackseatPricingProfileStore(backseatStore),\n lines: createBackseatPricingLineStore(backseatStore),\n };\n}\n\nexport {\n registerQupsBackseat,\n createBackseatPricingLineStore,\n createBackseatPricingProfileStore,\n QUPS_COLLECTIONS,\n} from \"./register.js\";\nexport type { RegisterQupsBackseatOptions } from \"./register.js\";\n","import { asDate } from \"@eristack/backseat/adapters\";\nimport type { BackseatStore } from \"@eristack/backseat\";\nimport type { ModifierKind } from \"../core/modifier.js\";\nimport type { QupsTruthMode } from \"../core/qups.js\";\nimport type {\n PricingField,\n PricingLineRecord,\n PricingLineStore,\n PricingModifierRecord,\n PricingProfile,\n PricingProfileStore,\n} from \"../core/stores/types.js\";\nimport { QUPS_COLLECTIONS } from \"./collections.js\";\n\nfunction profileFromDoc(doc: Record<string, unknown>): PricingProfile {\n return {\n id: String(doc.id),\n entityKey: String(doc.entityKey),\n defaultTruth: String(doc.defaultTruth) as QupsTruthMode,\n defaultCurrencyCode: String(doc.defaultCurrencyCode),\n fields: Array.isArray(doc.fields)\n ? (doc.fields as PricingField[])\n : [],\n defaultTaxRatePercent:\n doc.defaultTaxRatePercent == null\n ? undefined\n : String(doc.defaultTaxRatePercent),\n defaultTaxMode:\n doc.defaultTaxMode == null\n ? undefined\n : (String(doc.defaultTaxMode) as \"exclusive\" | \"inclusive\"),\n allowedModifierKinds: Array.isArray(doc.allowedModifierKinds)\n ? (doc.allowedModifierKinds as ModifierKind[])\n : undefined,\n active: Boolean(doc.active),\n createdAt: asDate(doc.createdAt),\n updatedAt: asDate(doc.updatedAt),\n };\n}\n\nfunction profileToDoc(record: PricingProfile): Record<string, unknown> {\n return {\n id: record.id,\n entityKey: record.entityKey,\n defaultTruth: record.defaultTruth,\n defaultCurrencyCode: record.defaultCurrencyCode,\n fields: record.fields,\n defaultTaxRatePercent: record.defaultTaxRatePercent ?? null,\n defaultTaxMode: record.defaultTaxMode ?? null,\n allowedModifierKinds: record.allowedModifierKinds ?? null,\n active: record.active,\n createdAt: record.createdAt.toISOString(),\n updatedAt: record.updatedAt.toISOString(),\n };\n}\n\nexport function createBackseatPricingProfileStore(\n store: BackseatStore,\n options: { collection?: string } = {},\n): PricingProfileStore {\n const collection = options.collection ?? QUPS_COLLECTIONS.profiles;\n\n async function allProfiles(): Promise<PricingProfile[]> {\n const docs = await store.list(collection);\n return docs.map(profileFromDoc);\n }\n\n return {\n async save(record) {\n const doc = profileToDoc(record);\n const existing = await store.get(collection, record.id);\n if (existing) {\n await store.update(collection, record.id, doc);\n return;\n }\n await store.create(collection, doc);\n },\n\n async findById(id) {\n const doc = await store.get(collection, id);\n return doc ? profileFromDoc(doc) : null;\n },\n\n async findActiveByEntityKey(entityKey) {\n const matches = (await allProfiles())\n .filter((row) => row.entityKey === entityKey && row.active)\n .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());\n return matches[0] ?? null;\n },\n\n async listByEntityKey(entityKey) {\n return (await allProfiles())\n .filter((row) => row.entityKey === entityKey)\n .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());\n },\n };\n}\n\nfunction lineFromDoc(doc: Record<string, unknown>): PricingLineRecord {\n return {\n id: String(doc.id),\n ownerKey: String(doc.ownerKey),\n profileId: doc.profileId == null ? undefined : String(doc.profileId),\n truth: String(doc.truth) as QupsTruthMode,\n quantity: String(doc.quantity),\n quantityRatioNumerator:\n doc.quantityRatioNumerator == null\n ? undefined\n : String(doc.quantityRatioNumerator),\n quantityRatioDenominator:\n doc.quantityRatioDenominator == null\n ? undefined\n : String(doc.quantityRatioDenominator),\n currency: String(doc.currency),\n unitPriceAmount: String(doc.unitPriceAmount),\n subtotalAmount: String(doc.subtotalAmount),\n taxRatePercent:\n doc.taxRatePercent == null ? undefined : String(doc.taxRatePercent),\n taxMode:\n doc.taxMode == null\n ? undefined\n : (String(doc.taxMode) as \"exclusive\" | \"inclusive\"),\n taxAmount: doc.taxAmount == null ? undefined : String(doc.taxAmount),\n netAmount: doc.netAmount == null ? undefined : String(doc.netAmount),\n grossAmount: doc.grossAmount == null ? undefined : String(doc.grossAmount),\n modifiers: Array.isArray(doc.modifiers)\n ? (doc.modifiers as PricingModifierRecord[])\n : [],\n fieldValues: Array.isArray(doc.fieldValues)\n ? (doc.fieldValues as PricingLineRecord[\"fieldValues\"])\n : [],\n rowExtras:\n doc.rowExtras && typeof doc.rowExtras === \"object\"\n ? (doc.rowExtras as Record<string, unknown>)\n : undefined,\n position: doc.position == null ? undefined : Number(doc.position),\n createdAt: asDate(doc.createdAt),\n updatedAt: asDate(doc.updatedAt),\n };\n}\n\nfunction lineToDoc(record: PricingLineRecord): Record<string, unknown> {\n return {\n id: record.id,\n ownerKey: record.ownerKey,\n profileId: record.profileId ?? null,\n truth: record.truth,\n quantity: record.quantity,\n quantityRatioNumerator: record.quantityRatioNumerator ?? null,\n quantityRatioDenominator: record.quantityRatioDenominator ?? null,\n currency: record.currency,\n unitPriceAmount: record.unitPriceAmount,\n subtotalAmount: record.subtotalAmount,\n taxRatePercent: record.taxRatePercent ?? null,\n taxMode: record.taxMode ?? null,\n taxAmount: record.taxAmount ?? null,\n netAmount: record.netAmount ?? null,\n grossAmount: record.grossAmount ?? null,\n modifiers: record.modifiers,\n fieldValues: record.fieldValues,\n rowExtras: record.rowExtras ?? null,\n position: record.position ?? null,\n createdAt: record.createdAt.toISOString(),\n updatedAt: record.updatedAt.toISOString(),\n };\n}\n\nexport function createBackseatPricingLineStore(\n store: BackseatStore,\n options: { collection?: string } = {},\n): PricingLineStore {\n const collection = options.collection ?? QUPS_COLLECTIONS.lines;\n\n async function allLines(): Promise<PricingLineRecord[]> {\n const docs = await store.list(collection);\n return docs.map(lineFromDoc);\n }\n\n return {\n async save(record) {\n const doc = lineToDoc(record);\n const existing = await store.get(collection, record.id);\n if (existing) {\n await store.update(collection, record.id, doc);\n return;\n }\n await store.create(collection, doc);\n },\n\n async findById(id) {\n const doc = await store.get(collection, id);\n return doc ? lineFromDoc(doc) : null;\n },\n\n async listByOwnerKey(ownerKey) {\n return (await allLines()).filter((row) => row.ownerKey === ownerKey);\n },\n\n async delete(id) {\n const existing = await store.get(collection, id);\n if (existing) await store.delete(collection, id);\n },\n };\n}\n","export const QUPS_COLLECTIONS = {\n profiles: \"qups.profiles\",\n lines: \"qups.lines\",\n} as const;\n","import { registerMountedRoutes } from \"@eristack/backseat/adapters\";\nimport type { Backseat } from \"@eristack/backseat\";\nimport { calculateLine } from \"../core/calculate.js\";\nimport { createQups, type CreateQupsOptions, type QupsApi } from \"../core/create-qups.js\";\nimport { createQupsRoutes } from \"./qups-routes.js\";\nimport { createBackseatPricingLineStore, createBackseatPricingProfileStore } from \"./stores.js\";\n\nexport type RegisterQupsBackseatOptions = CreateQupsOptions & {\n basePath?: string;\n qups?: QupsApi;\n};\n\nexport function registerQupsBackseat(\n api: Backseat,\n options: RegisterQupsBackseatOptions = {},\n): QupsApi {\n const profiles =\n options.profiles ?? createBackseatPricingProfileStore(api.store);\n const lines = options.lines ?? createBackseatPricingLineStore(api.store);\n const qups =\n options.qups ??\n createQups({\n profiles,\n lines,\n clock: options.clock,\n idFactory: options.idFactory,\n });\n\n registerMountedRoutes(api, options.basePath ?? \"/qups\", createQupsRoutes(qups));\n\n api.registerAction(\"qups.calculateLine\", async ({ input }) =>\n calculateLine(input as Parameters<typeof calculateLine>[0]),\n );\n\n return qups;\n}\n\nexport {\n createBackseatPricingLineStore,\n createBackseatPricingProfileStore,\n} from \"./stores.js\";\nexport { QUPS_COLLECTIONS } from \"./collections.js\";\n","import { Money, Rounding } from \"@eristack/money\";\nimport { PricingLine } from \"./line.js\";\nimport type { ModifierKind } from \"./modifier.js\";\nimport type { QupsTruthMode, QuantityRatio } from \"./qups.js\";\nimport { qupsRolesFor } from \"./stores/fields.js\";\n\n/**\n * Plain string input for forms / HTTP / BE — no Money objects required.\n * Exactly two of quantity / unitPrice / subtotal must be present per `truth`.\n */\nexport type CalculateLineInput = {\n truth: QupsTruthMode;\n /** Currency code for all money fields on the line. */\n currency: string;\n quantity?: string;\n unitPrice?: string;\n subtotal?: string;\n modifiers?: readonly CalculateModifierInput[];\n taxRatePercent?: string;\n taxMode?: \"exclusive\" | \"inclusive\";\n /** Round money fields with `Rounding.currencyDefault()` (typical before display/persist). */\n round?: boolean;\n};\n\nexport type CalculateModifierInput =\n | {\n id?: string;\n kind: ModifierKind;\n type: \"percent\";\n percent: string;\n }\n | {\n id?: string;\n kind: ModifierKind;\n type: \"nominal\";\n amount: string;\n currency?: string;\n };\n\n/**\n * Flat snapshot for TanStack Form state, API responses, or DB inserts.\n * All money/qty are decimal strings.\n */\nexport type CalculatedLine = {\n truth: QupsTruthMode;\n currency: string;\n quantity: string;\n quantityRatio: QuantityRatio | null;\n unitPrice: string;\n subtotal: string;\n discountTotal: string;\n surchargeTotal: string;\n net: string;\n taxAmount: string;\n taxRatePercent: string | null;\n taxMode: \"exclusive\" | \"inclusive\" | null;\n /** Payable gross. */\n total: string;\n /** Echo modifiers as plain strings (for form round-trip). */\n modifiers: CalculateModifierInput[];\n /** Which QUPS fields are editable vs derived for the current truth. */\n roles: ReturnType<typeof qupsRolesFor>;\n /**\n * Values shaped for injectable Drizzle columns / SQL insert\n * (`currency`, `unit_price_amount`, …).\n */\n columns: QupsColumnValues;\n};\n\n/** CamelCase keys matching `qupsLineColumns()` drizzle properties. */\nexport type QupsColumnValues = {\n truth: QupsTruthMode;\n quantity: string;\n quantityRatioNumerator: string | null;\n quantityRatioDenominator: string | null;\n currency: string;\n unitPriceAmount: string;\n subtotalAmount: string;\n taxRatePercent: string | null;\n taxMode: \"exclusive\" | \"inclusive\" | null;\n taxAmount: string | null;\n netAmount: string;\n grossAmount: string;\n};\n\nexport type PatchLineInput = {\n quantity?: string;\n unitPrice?: string;\n subtotal?: string;\n truth?: QupsTruthMode;\n currency?: string;\n modifiers?: readonly CalculateModifierInput[];\n taxRatePercent?: string | null;\n taxMode?: \"exclusive\" | \"inclusive\" | null;\n /**\n * When only `subtotal` changes, keep this SoT partner\n * (same as `Qups.edit` prefer).\n */\n prefer?: \"quantity\" | \"unitPrice\";\n round?: boolean;\n};\n\nfunction toPricingLine(input: CalculateLineInput): PricingLine {\n const { truth, currency } = input;\n let line: PricingLine;\n\n if (truth === \"quantity+unitPrice\") {\n if (input.quantity == null || input.unitPrice == null) {\n throw new Error(\"truth quantity+unitPrice requires quantity and unitPrice\");\n }\n line = PricingLine.of({\n qups: {\n truth,\n quantity: input.quantity,\n unitPrice: Money.of(input.unitPrice, currency),\n },\n modifiers: mapModifiers(input.modifiers, currency),\n tax: taxInput(input),\n });\n } else if (truth === \"quantity+subtotal\") {\n if (input.quantity == null || input.subtotal == null) {\n throw new Error(\"truth quantity+subtotal requires quantity and subtotal\");\n }\n line = PricingLine.of({\n qups: {\n truth,\n quantity: input.quantity,\n subtotal: Money.of(input.subtotal, currency),\n },\n modifiers: mapModifiers(input.modifiers, currency),\n tax: taxInput(input),\n });\n } else {\n if (input.unitPrice == null || input.subtotal == null) {\n throw new Error(\"truth unitPrice+subtotal requires unitPrice and subtotal\");\n }\n line = PricingLine.of({\n qups: {\n truth,\n unitPrice: Money.of(input.unitPrice, currency),\n subtotal: Money.of(input.subtotal, currency),\n },\n modifiers: mapModifiers(input.modifiers, currency),\n tax: taxInput(input),\n });\n }\n\n return input.round ? line.withRounding(Rounding.currencyDefault()) : line;\n}\n\nfunction mapModifiers(\n modifiers: readonly CalculateModifierInput[] | undefined,\n currency: string,\n) {\n return (modifiers ?? []).map((m) => {\n if (m.type === \"percent\") {\n return {\n id: m.id,\n kind: m.kind,\n type: \"percent\" as const,\n percent: m.percent,\n };\n }\n return {\n id: m.id,\n kind: m.kind,\n type: \"nominal\" as const,\n amount: Money.of(m.amount, m.currency ?? currency),\n };\n });\n}\n\nfunction taxInput(\n input: Pick<CalculateLineInput, \"taxRatePercent\" | \"taxMode\">,\n):\n | { ratePercent: string; mode?: \"exclusive\" }\n | { ratePercent: string; mode: \"inclusive\" }\n | undefined {\n if (!input.taxRatePercent) return undefined;\n if (input.taxMode === \"inclusive\") {\n return { ratePercent: input.taxRatePercent, mode: \"inclusive\" };\n }\n return { ratePercent: input.taxRatePercent, mode: \"exclusive\" };\n}\n\nfunction snapshotFromLine(\n line: PricingLine,\n currency: string,\n taxRatePercent: string | null,\n taxMode: \"exclusive\" | \"inclusive\" | null,\n): CalculatedLine {\n const amount = (m: Money) => m.toJSON().amount;\n const qtyRatio = line.qups.quantityRatio;\n const resolvedTaxMode: \"exclusive\" | \"inclusive\" | null =\n taxMode ??\n (line.tax.truth === \"gross+rate\"\n ? \"inclusive\"\n : line.tax.ratePercent\n ? \"exclusive\"\n : null);\n const resolvedRate = taxRatePercent ?? line.tax.ratePercent;\n\n const modifiers: CalculateModifierInput[] = line.adjusted.modifiers.map((m) => {\n if (m.type === \"percent\") {\n return {\n id: m.id,\n kind: m.kind,\n type: \"percent\" as const,\n percent: m.percent,\n };\n }\n return {\n id: m.id,\n kind: m.kind,\n type: \"nominal\" as const,\n amount: amount(m.amount),\n currency: m.amount.currency.currencyCode,\n };\n });\n\n return {\n truth: line.qups.truth,\n currency,\n quantity: line.qups.quantity,\n quantityRatio: qtyRatio,\n unitPrice: amount(line.qups.unitPrice),\n subtotal: amount(line.qups.subtotal),\n discountTotal: amount(line.adjusted.discountTotal),\n surchargeTotal: amount(line.adjusted.surchargeTotal),\n net: amount(line.tax.net),\n taxAmount: amount(line.tax.tax),\n taxRatePercent: resolvedRate,\n taxMode: resolvedTaxMode,\n total: amount(line.total),\n modifiers,\n roles: qupsRolesFor(line.qups.truth),\n columns: {\n truth: line.qups.truth,\n quantity: line.qups.quantity,\n quantityRatioNumerator: qtyRatio?.numerator ?? null,\n quantityRatioDenominator: qtyRatio?.denominator ?? null,\n currency,\n unitPriceAmount: amount(line.qups.unitPrice),\n subtotalAmount: amount(line.qups.subtotal),\n taxRatePercent: resolvedRate,\n taxMode: resolvedTaxMode,\n taxAmount: amount(line.tax.tax),\n netAmount: amount(line.tax.net),\n grossAmount: amount(line.total),\n },\n };\n}\n\n/**\n * Recalculate a full pricing line from plain strings.\n * Use in TanStack Form listeners and BE insert/update handlers — same function both sides.\n *\n * ```ts\n * const line = calculateLine({\n * truth: \"quantity+unitPrice\",\n * currency: \"USD\",\n * quantity: \"2\",\n * unitPrice: \"50\",\n * modifiers: [{ kind: \"discount\", type: \"percent\", percent: \"5\" }],\n * taxRatePercent: \"11\",\n * round: true,\n * });\n * // form: line.quantity, line.unitPrice, line.subtotal, line.total\n * // db: { itemId, ...line.columns }\n * ```\n */\nexport function calculateLine(input: CalculateLineInput): CalculatedLine {\n const line = toPricingLine(input);\n return snapshotFromLine(\n line,\n input.currency,\n input.taxRatePercent ?? null,\n input.taxMode ?? null,\n );\n}\n\nfunction asCalculateInput(\n current: CalculatedLine | CalculateLineInput,\n): CalculateLineInput {\n if (\"columns\" in current) {\n return {\n truth: current.truth,\n currency: current.currency,\n quantity: current.quantity,\n unitPrice: current.unitPrice,\n subtotal: current.subtotal,\n modifiers: current.modifiers,\n taxRatePercent: current.taxRatePercent ?? undefined,\n taxMode: current.taxMode ?? undefined,\n };\n }\n return current;\n}\n\n/**\n * Patch one or more fields and recalculate (form onChange / BE partial update).\n * Uses the same SoT edit rules as `Qups.edit` when quantity/unitPrice/subtotal change.\n */\nexport function patchLine(\n current: CalculatedLine | CalculateLineInput,\n patch: PatchLineInput,\n): CalculatedLine {\n const base = asCalculateInput(current);\n const currency = patch.currency ?? base.currency;\n const modifiers = patch.modifiers ?? base.modifiers;\n const taxRatePercent =\n patch.taxRatePercent === null\n ? undefined\n : (patch.taxRatePercent ?? base.taxRatePercent);\n const taxMode =\n patch.taxMode === null ? undefined : (patch.taxMode ?? base.taxMode);\n const round = patch.round ?? base.round;\n\n const qupsChanged =\n patch.quantity !== undefined ||\n patch.unitPrice !== undefined ||\n patch.subtotal !== undefined ||\n patch.truth !== undefined;\n\n if (!qupsChanged) {\n return calculateLine({\n truth: patch.truth ?? base.truth,\n currency,\n quantity: base.quantity,\n unitPrice: base.unitPrice,\n subtotal: base.subtotal,\n modifiers,\n taxRatePercent,\n taxMode,\n round,\n });\n }\n\n let live = toPricingLine({\n ...base,\n // keep base tax while editing qups; tax applied again below\n });\n\n if (patch.truth && patch.truth !== live.qups.truth) {\n const q = live.qups.asTruth(patch.truth);\n live = toPricingLine({\n truth: q.truth,\n currency: base.currency,\n quantity: q.quantity,\n unitPrice: q.unitPrice.toJSON().amount,\n subtotal: q.subtotal.toJSON().amount,\n modifiers: base.modifiers,\n taxRatePercent: base.taxRatePercent,\n taxMode: base.taxMode,\n });\n }\n\n const editPatch: {\n quantity?: string;\n unitPrice?: Money;\n subtotal?: Money;\n } = {};\n if (patch.quantity !== undefined) editPatch.quantity = patch.quantity;\n if (patch.unitPrice !== undefined) {\n editPatch.unitPrice = Money.of(patch.unitPrice, currency);\n }\n if (patch.subtotal !== undefined) {\n editPatch.subtotal = Money.of(patch.subtotal, currency);\n }\n if (Object.keys(editPatch).length) {\n live = live.editQups(editPatch, { prefer: patch.prefer });\n }\n\n return calculateLine({\n truth: live.qups.truth,\n currency,\n quantity: live.qups.quantity,\n unitPrice: live.qups.unitPrice.toJSON().amount,\n subtotal: live.qups.subtotal.toJSON().amount,\n modifiers,\n taxRatePercent,\n taxMode,\n round,\n });\n}\n\n/** Merge calculated QUPS columns into an insert/update payload (with itemId, …). */\nexport function withQupsColumns<T extends Record<string, unknown>>(\n row: T,\n line: CalculatedLine | QupsColumnValues,\n): T & QupsColumnValues {\n const columns = \"columns\" in line ? line.columns : line;\n return { ...row, ...columns };\n}\n\n","import { Money, Rounding } from \"@eristack/money\";\nimport { AdjustedAmount, type ModifierSpec } from \"./modifier.js\";\nimport { Qups, type QupsInput } from \"./qups.js\";\nimport { LineTax } from \"./tax.js\";\n\nexport type PricingLineInput = {\n qups: QupsInput;\n /** Applied to QUPS subtotal in order. */\n modifiers?: readonly ModifierSpec[];\n tax?:\n | { ratePercent: string; mode?: \"exclusive\" }\n | { ratePercent: string; mode: \"inclusive\" };\n};\n\n/**\n * Full line: QUPS → modifiers → tax.\n * All math stays in the business layer via Money — UI only displays.\n */\nexport class PricingLine {\n readonly qups: Qups;\n readonly adjusted: AdjustedAmount;\n readonly tax: LineTax;\n /** Payable total (tax.gross). */\n readonly total: Money;\n\n private constructor(qups: Qups, adjusted: AdjustedAmount, tax: LineTax) {\n this.qups = qups;\n this.adjusted = adjusted;\n this.tax = tax;\n this.total = tax.gross;\n }\n\n static of(input: PricingLineInput): PricingLine {\n const qups = Qups.of(input.qups);\n const adjusted = AdjustedAmount.of({\n truth: \"base+modifiers\",\n base: qups.subtotal,\n modifiers: input.modifiers ?? [],\n });\n\n const taxInput = input.tax;\n let tax: LineTax;\n if (!taxInput) {\n tax = LineTax.of({\n truth: \"net+tax\",\n net: adjusted.net,\n tax: Money.zero(adjusted.net.currency),\n });\n } else if (taxInput.mode === \"inclusive\") {\n // Interpreting adjusted.net as inclusive gross when mode is inclusive\n tax = LineTax.of({\n truth: \"gross+rate\",\n gross: adjusted.net,\n ratePercent: taxInput.ratePercent,\n mode: \"inclusive\",\n });\n } else {\n tax = LineTax.of({\n truth: \"net+rate\",\n net: adjusted.net,\n ratePercent: taxInput.ratePercent,\n });\n }\n\n return new PricingLine(qups, adjusted, tax);\n }\n\n editQups(\n patch: Parameters<Qups[\"edit\"]>[0],\n options?: Parameters<Qups[\"edit\"]>[1],\n ): PricingLine {\n return PricingLine.of({\n qups: truthFromQups(this.qups.edit(patch, options)),\n modifiers: this.adjusted.modifiers,\n tax: taxOptsFrom(this.tax),\n });\n }\n\n withModifiers(modifiers: readonly ModifierSpec[]): PricingLine {\n return PricingLine.of({\n qups: truthFromQups(this.qups),\n modifiers,\n tax: taxOptsFrom(this.tax),\n });\n }\n\n withRounding(round = Rounding.currencyDefault()): PricingLine {\n const apply = (m: Money) => m.with(round);\n return new PricingLine(\n this.qups.withRounding({ apply }),\n AdjustedAmount.of({\n truth: \"base+modifiers\",\n base: apply(this.adjusted.base),\n modifiers: this.adjusted.modifiers.map((m) =>\n m.type === \"nominal\"\n ? { ...m, amount: apply(m.amount) }\n : m,\n ),\n }),\n this.tax.withRounding(round),\n );\n }\n\n toJSON() {\n return {\n qups: this.qups.toJSON(),\n adjusted: this.adjusted.toJSON(),\n tax: this.tax.toJSON(),\n total: this.total.toJSON(),\n };\n }\n}\n\nfunction truthFromQups(q: Qups): QupsInput {\n if (q.truth === \"quantity+unitPrice\") {\n return {\n truth: \"quantity+unitPrice\",\n quantity: q.quantity,\n unitPrice: q.unitPrice,\n };\n }\n if (q.truth === \"quantity+subtotal\") {\n return {\n truth: \"quantity+subtotal\",\n quantity: q.quantity,\n subtotal: q.subtotal,\n };\n }\n return {\n truth: \"unitPrice+subtotal\",\n unitPrice: q.unitPrice,\n subtotal: q.subtotal,\n };\n}\n\nfunction taxOptsFrom(\n tax: LineTax,\n): PricingLineInput[\"tax\"] | undefined {\n if (!tax.ratePercent) {\n if (tax.tax.isZero()) return undefined;\n return undefined;\n }\n if (tax.truth === \"gross+rate\") {\n return { ratePercent: tax.ratePercent, mode: \"inclusive\" };\n }\n return { ratePercent: tax.ratePercent, mode: \"exclusive\" };\n}\n","import { Money, Discount, Markup } from \"@eristack/money\";\nimport { CurrencyMismatchError, InvalidTruthError } from \"./errors.js\";\n\nexport type ModifierKind = \"discount\" | \"surcharge\";\n\nexport type ModifierSpec =\n | {\n id?: string;\n kind: ModifierKind;\n type: \"percent\";\n /** Percent points, e.g. `\"10\"` for 10%. */\n percent: string;\n }\n | {\n id?: string;\n kind: ModifierKind;\n type: \"nominal\";\n amount: Money;\n };\n\nexport type ModifierStep = {\n spec: ModifierSpec;\n /** Absolute money effect (always ≥ 0). */\n amount: Money;\n /** Running total after this step. */\n running: Money;\n};\n\nexport type AdjustedInput =\n | {\n truth: \"base+modifiers\";\n base: Money;\n modifiers: readonly ModifierSpec[];\n }\n | {\n /** Derive a single nominal modifier so base ± mod = net. */\n truth: \"base+net\";\n base: Money;\n net: Money;\n kind?: ModifierKind;\n id?: string;\n }\n | {\n /** Derive base from net by reversing modifiers (percent/nominal). */\n truth: \"modifiers+net\";\n net: Money;\n modifiers: readonly ModifierSpec[];\n };\n\nfunction applyOne(running: Money, spec: ModifierSpec): {\n amount: Money;\n next: Money;\n} {\n if (spec.type === \"percent\") {\n if (spec.kind === \"discount\") {\n const next = running.with(Discount.ofPercent(spec.percent));\n return { amount: running.subtract(next), next };\n }\n const next = running.with(Markup.ofPercent(spec.percent));\n return { amount: next.subtract(running), next };\n }\n\n if (spec.amount.currency.currencyCode !== running.currency.currencyCode) {\n throw new CurrencyMismatchError(\n `Modifier currency ${spec.amount.currency.currencyCode} != base ${running.currency.currencyCode}`,\n );\n }\n if (spec.kind === \"discount\") {\n const next = running.subtract(spec.amount);\n return { amount: spec.amount, next };\n }\n const next = running.add(spec.amount);\n return { amount: spec.amount, next };\n}\n\nfunction applyForward(\n base: Money,\n modifiers: readonly ModifierSpec[],\n): { net: Money; steps: ModifierStep[] } {\n let running = base;\n const steps: ModifierStep[] = [];\n for (const spec of modifiers) {\n const { amount, next } = applyOne(running, spec);\n running = next;\n steps.push({ spec, amount, running });\n }\n return { net: running, steps };\n}\n\n/**\n * Reverse modifiers from net → base.\n * Nominal discounts add back; surcharges subtract; percents invert.\n */\nfunction reverseModifiers(\n net: Money,\n modifiers: readonly ModifierSpec[],\n): Money {\n let running = net;\n for (let i = modifiers.length - 1; i >= 0; i--) {\n const spec = modifiers[i]!;\n if (spec.type === \"percent\") {\n if (spec.kind === \"discount\") {\n // net = base * (1 - p/100) → base = net / (1 - p/100)\n const factor = Money.of(\"100\", running.currency)\n .subtract(Money.of(spec.percent, running.currency))\n .divide(\"100\")\n .getNumber()\n .toString();\n running = running.divide(factor);\n } else {\n // net = base * (1 + p/100) → base = net / (1 + p/100)\n const factor = Money.of(\"100\", running.currency)\n .add(Money.of(spec.percent, running.currency))\n .divide(\"100\")\n .getNumber()\n .toString();\n running = running.divide(factor);\n }\n } else if (spec.kind === \"discount\") {\n running = running.add(spec.amount);\n } else {\n running = running.subtract(spec.amount);\n }\n }\n return running;\n}\n\n/**\n * Base amount ↔ modifiers ↔ net, with exactly two sources of truth.\n * Supports multiple percent/nominal discounts and surcharges in order.\n */\nexport class AdjustedAmount {\n readonly truth: \"base+modifiers\" | \"base+net\" | \"modifiers+net\";\n readonly base: Money;\n readonly net: Money;\n readonly modifiers: readonly ModifierSpec[];\n readonly steps: readonly ModifierStep[];\n readonly discountTotal: Money;\n readonly surchargeTotal: Money;\n\n private constructor(\n truth: AdjustedAmount[\"truth\"],\n base: Money,\n net: Money,\n modifiers: readonly ModifierSpec[],\n steps: readonly ModifierStep[],\n ) {\n this.truth = truth;\n this.base = base;\n this.net = net;\n this.modifiers = modifiers;\n this.steps = steps;\n\n let discountTotal = Money.zero(base.currency);\n let surchargeTotal = Money.zero(base.currency);\n for (const step of steps) {\n if (step.spec.kind === \"discount\") {\n discountTotal = discountTotal.add(step.amount);\n } else {\n surchargeTotal = surchargeTotal.add(step.amount);\n }\n }\n this.discountTotal = discountTotal;\n this.surchargeTotal = surchargeTotal;\n }\n\n static of(input: AdjustedInput): AdjustedAmount {\n if (input.truth === \"base+modifiers\") {\n const { net, steps } = applyForward(input.base, input.modifiers);\n return new AdjustedAmount(\n \"base+modifiers\",\n input.base,\n net,\n input.modifiers,\n steps,\n );\n }\n\n if (input.truth === \"base+net\") {\n sameMoneyCurrency(input.base, input.net);\n const diff = input.base.subtract(input.net);\n let kind = input.kind;\n let amount: Money;\n if (diff.isZero()) {\n kind = kind ?? \"discount\";\n amount = Money.zero(input.base.currency);\n } else if (diff.isPositive()) {\n kind = \"discount\";\n amount = diff;\n } else {\n kind = \"surcharge\";\n amount = diff.abs();\n }\n const modifiers: ModifierSpec[] = [\n {\n id: input.id,\n kind,\n type: \"nominal\",\n amount,\n },\n ];\n const { net, steps } = applyForward(input.base, modifiers);\n return new AdjustedAmount(\n \"base+net\",\n input.base,\n net,\n modifiers,\n steps,\n );\n }\n\n if (!input.modifiers.length) {\n throw new InvalidTruthError(\n \"modifiers+net requires at least one modifier to reverse\",\n );\n }\n const base = reverseModifiers(input.net, input.modifiers);\n const { net, steps } = applyForward(base, input.modifiers);\n return new AdjustedAmount(\n \"modifiers+net\",\n base,\n net,\n input.modifiers,\n steps,\n );\n }\n\n toJSON() {\n return {\n truth: this.truth,\n base: this.base.toJSON(),\n net: this.net.toJSON(),\n discountTotal: this.discountTotal.toJSON(),\n surchargeTotal: this.surchargeTotal.toJSON(),\n modifiers: this.modifiers.map((m) =>\n m.type === \"percent\"\n ? { id: m.id, kind: m.kind, type: m.type, percent: m.percent }\n : {\n id: m.id,\n kind: m.kind,\n type: m.type,\n amount: m.amount.toJSON(),\n },\n ),\n };\n }\n}\n\nfunction sameMoneyCurrency(a: Money, b: Money) {\n if (a.currency.currencyCode !== b.currency.currencyCode) {\n throw new CurrencyMismatchError(\n `Currency mismatch: ${a.currency.currencyCode} vs ${b.currency.currencyCode}`,\n );\n }\n}\n","export class QupsError extends Error {\n readonly code: string;\n constructor(code: string, message: string) {\n super(message);\n this.name = \"QupsError\";\n this.code = code;\n }\n}\n\nexport class InvalidTruthError extends QupsError {\n constructor(message: string) {\n super(\"INVALID_TRUTH\", message);\n this.name = \"InvalidTruthError\";\n }\n}\n\nexport class CurrencyMismatchError extends QupsError {\n constructor(message: string) {\n super(\"CURRENCY_MISMATCH\", message);\n this.name = \"CurrencyMismatchError\";\n }\n}\n\nexport class MissingDependencyError extends QupsError {\n constructor(dependency: string) {\n super(\"MISSING_DEPENDENCY\", `Missing dependency: ${dependency}`);\n this.name = \"MissingDependencyError\";\n }\n}\n\nexport class ProfileNotFoundError extends QupsError {\n constructor(entityKeyOrId: string) {\n super(\"PROFILE_NOT_FOUND\", `Pricing profile not found: ${entityKeyOrId}`);\n this.name = \"ProfileNotFoundError\";\n }\n}\n\nexport class LineNotFoundError extends QupsError {\n constructor(id: string) {\n super(\"LINE_NOT_FOUND\", `Pricing line not found: ${id}`);\n this.name = \"LineNotFoundError\";\n }\n}\n","import { Money, type CurrencyUnit } from \"@eristack/money\";\nimport Decimal from \"decimal.js\";\nimport { CurrencyMismatchError, InvalidTruthError } from \"./errors.js\";\nimport type { QupsTruthMode } from \"./truth-mode.js\";\n\nexport type { QupsTruthMode } from \"./truth-mode.js\";\nexport { QUPS_TRUTH_MODES, isQupsTruthMode } from \"./truth-mode.js\";\n\nconst QtyDecimal = Decimal.clone({\n precision: 40,\n rounding: Decimal.ROUND_HALF_EVEN,\n});\n\nexport type QupsInput =\n | {\n truth: \"quantity+unitPrice\";\n quantity: string;\n unitPrice: Money;\n }\n | {\n truth: \"quantity+subtotal\";\n quantity: string;\n subtotal: Money;\n }\n | {\n truth: \"unitPrice+subtotal\";\n unitPrice: Money;\n subtotal: Money;\n };\n\n/** Exact quantity as a ratio of decimal strings (avoids losing 10/3). */\nexport type QuantityRatio = {\n numerator: string;\n denominator: string;\n};\n\nfunction assertQuantity(quantity: string) {\n if (quantity.trim() === \"\") {\n throw new InvalidTruthError(\"quantity is required\");\n }\n try {\n // eslint-disable-next-line no-new\n new QtyDecimal(quantity);\n } catch {\n throw new InvalidTruthError(`Invalid quantity: ${quantity}`);\n }\n}\n\nfunction sameCurrency(a: Money, b: Money) {\n if (a.currency.currencyCode !== b.currency.currencyCode) {\n throw new CurrencyMismatchError(\n `Currency mismatch: ${a.currency.currencyCode} vs ${b.currency.currencyCode}`,\n );\n }\n}\n\nfunction ratioString(ratio: QuantityRatio): string {\n return new QtyDecimal(ratio.numerator).div(ratio.denominator).toFixed();\n}\n\n/**\n * Quantity · Unit price · Subtotal triad with exactly two sources of truth.\n *\n * When truth is `unitPrice+subtotal` (e.g. UP=3, S=10), quantity is kept as\n * the ratio `10/3` so the true qty is not collapsed to a rounded 3.33.\n */\nexport class Qups {\n readonly truth: QupsTruthMode;\n readonly unitPrice: Money;\n readonly subtotal: Money;\n /**\n * Decimal string view of quantity (high precision).\n * Prefer `quantityRatio` when truth is `unitPrice+subtotal`.\n */\n readonly quantity: string;\n /** Exact ratio when quantity was derived from unitPrice+subtotal; else null. */\n readonly quantityRatio: QuantityRatio | null;\n\n private constructor(\n truth: QupsTruthMode,\n quantity: string,\n unitPrice: Money,\n subtotal: Money,\n quantityRatio: QuantityRatio | null,\n ) {\n this.truth = truth;\n this.quantity = quantity;\n this.unitPrice = unitPrice;\n this.subtotal = subtotal;\n this.quantityRatio = quantityRatio;\n }\n\n get currency(): CurrencyUnit {\n return this.unitPrice.currency;\n }\n\n static of(input: QupsInput): Qups {\n if (input.truth === \"quantity+unitPrice\") {\n assertQuantity(input.quantity);\n const quantity = input.quantity.trim();\n const subtotal = input.unitPrice.multiply(quantity);\n return new Qups(\n \"quantity+unitPrice\",\n quantity,\n input.unitPrice,\n subtotal,\n null,\n );\n }\n\n if (input.truth === \"quantity+subtotal\") {\n assertQuantity(input.quantity);\n const quantity = input.quantity.trim();\n if (new QtyDecimal(quantity).isZero()) {\n throw new InvalidTruthError(\n \"Cannot derive unitPrice when quantity is 0\",\n );\n }\n const unitPrice = input.subtotal.divide(quantity);\n return new Qups(\n \"quantity+subtotal\",\n quantity,\n unitPrice,\n input.subtotal,\n null,\n );\n }\n\n sameCurrency(input.unitPrice, input.subtotal);\n if (input.unitPrice.isZero()) {\n throw new InvalidTruthError(\n \"Cannot derive quantity when unitPrice is zero\",\n );\n }\n const numerator = input.subtotal.getNumber().toString();\n const denominator = input.unitPrice.getNumber().toString();\n const quantityRatio = { numerator, denominator };\n return new Qups(\n \"unitPrice+subtotal\",\n ratioString(quantityRatio),\n input.unitPrice,\n input.subtotal,\n quantityRatio,\n );\n }\n\n withTruth(input: QupsInput): Qups {\n return Qups.of(input);\n }\n\n /**\n * `quantity × unitPrice` using SoT when possible so UP+S never drifts.\n */\n product(): Money {\n if (this.truth === \"unitPrice+subtotal\") return this.subtotal;\n if (this.truth === \"quantity+subtotal\") return this.subtotal;\n return this.unitPrice.multiply(this.quantity);\n }\n\n /**\n * Common UI edits. Single-field defaults:\n * - qty or unitPrice → recompute subtotal (`quantity+unitPrice`)\n * - subtotal → keep unitPrice, recompute qty (`unitPrice+subtotal`)\n * unless `prefer: \"quantity\"`\n */\n edit(\n patch: {\n quantity?: string;\n unitPrice?: Money;\n subtotal?: Money;\n },\n options?: { prefer?: \"quantity\" | \"unitPrice\" },\n ): Qups {\n const prefer = options?.prefer ?? \"unitPrice\";\n const keys = (\n [\"quantity\", \"unitPrice\", \"subtotal\"] as const\n ).filter((k) => patch[k] !== undefined);\n\n if (keys.length === 0) return this;\n if (keys.length >= 3) {\n throw new InvalidTruthError(\n \"edit() accepts at most two of quantity, unitPrice, subtotal\",\n );\n }\n\n if (keys.length === 2) {\n if (keys.includes(\"quantity\") && keys.includes(\"unitPrice\")) {\n return Qups.of({\n truth: \"quantity+unitPrice\",\n quantity: patch.quantity!,\n unitPrice: patch.unitPrice!,\n });\n }\n if (keys.includes(\"quantity\") && keys.includes(\"subtotal\")) {\n return Qups.of({\n truth: \"quantity+subtotal\",\n quantity: patch.quantity!,\n subtotal: patch.subtotal!,\n });\n }\n return Qups.of({\n truth: \"unitPrice+subtotal\",\n unitPrice: patch.unitPrice!,\n subtotal: patch.subtotal!,\n });\n }\n\n if (patch.quantity !== undefined) {\n return Qups.of({\n truth: \"quantity+unitPrice\",\n quantity: patch.quantity,\n unitPrice: this.unitPrice,\n });\n }\n if (patch.unitPrice !== undefined) {\n return Qups.of({\n truth: \"quantity+unitPrice\",\n quantity: this.quantity,\n unitPrice: patch.unitPrice,\n });\n }\n if (prefer === \"quantity\") {\n return Qups.of({\n truth: \"quantity+subtotal\",\n quantity: this.quantity,\n subtotal: patch.subtotal!,\n });\n }\n return Qups.of({\n truth: \"unitPrice+subtotal\",\n unitPrice: this.unitPrice,\n subtotal: patch.subtotal!,\n });\n }\n\n asTruth(truth: QupsTruthMode): Qups {\n if (truth === \"quantity+unitPrice\") {\n return Qups.of({\n truth,\n quantity: this.quantity,\n unitPrice: this.unitPrice,\n });\n }\n if (truth === \"quantity+subtotal\") {\n return Qups.of({\n truth,\n quantity: this.quantity,\n subtotal: this.subtotal,\n });\n }\n return Qups.of({\n truth,\n unitPrice: this.unitPrice,\n subtotal: this.subtotal,\n });\n }\n\n withRounding(round: { apply: (m: Money) => Money }): Qups {\n const unitPrice = round.apply(this.unitPrice);\n const subtotal = round.apply(this.subtotal);\n if (this.truth === \"quantity+unitPrice\") {\n return Qups.of({\n truth: this.truth,\n quantity: this.quantity,\n unitPrice,\n });\n }\n if (this.truth === \"quantity+subtotal\") {\n return Qups.of({\n truth: this.truth,\n quantity: this.quantity,\n subtotal,\n });\n }\n return Qups.of({\n truth: this.truth,\n unitPrice,\n subtotal,\n });\n }\n\n toJSON() {\n return {\n truth: this.truth,\n quantity: this.quantity,\n quantityRatio: this.quantityRatio,\n unitPrice: this.unitPrice.toJSON(),\n subtotal: this.subtotal.toJSON(),\n };\n }\n}\n","import { Money, Tax, Rounding } from \"@eristack/money\";\nimport { CurrencyMismatchError, InvalidTruthError } from \"./errors.js\";\n\nexport type TaxMode = \"exclusive\" | \"inclusive\";\n\nexport type TaxInput =\n | {\n /** net + rate → tax + gross (exclusive). */\n truth: \"net+rate\";\n net: Money;\n ratePercent: string;\n mode?: \"exclusive\";\n }\n | {\n /** gross + rate → net + tax (inclusive). */\n truth: \"gross+rate\";\n gross: Money;\n ratePercent: string;\n mode: \"inclusive\";\n }\n | {\n /** net + tax → gross; rate optional derived as informational string. */\n truth: \"net+tax\";\n net: Money;\n tax: Money;\n };\n\n/**\n * Tax triad with two sources of truth (net/rate, gross/rate, or net/tax).\n * Uses `@eristack/money` Tax operators under the hood.\n */\nexport class LineTax {\n readonly truth: \"net+rate\" | \"gross+rate\" | \"net+tax\";\n readonly net: Money;\n readonly tax: Money;\n readonly gross: Money;\n /** Percent points when known from rate-based truth. */\n readonly ratePercent: string | null;\n\n private constructor(\n truth: LineTax[\"truth\"],\n net: Money,\n tax: Money,\n gross: Money,\n ratePercent: string | null,\n ) {\n this.truth = truth;\n this.net = net;\n this.tax = tax;\n this.gross = gross;\n this.ratePercent = ratePercent;\n }\n\n static of(input: TaxInput): LineTax {\n if (input.truth === \"net+rate\") {\n const tax = input.net.with(Tax.onExclusive(input.ratePercent));\n const gross = input.net.add(tax);\n return new LineTax(\n \"net+rate\",\n input.net,\n tax,\n gross,\n input.ratePercent,\n );\n }\n\n if (input.truth === \"gross+rate\") {\n const net = input.gross.with(Tax.netFromInclusive(input.ratePercent));\n const tax = input.gross.with(Tax.extractFromInclusive(input.ratePercent));\n return new LineTax(\n \"gross+rate\",\n net,\n tax,\n input.gross,\n input.ratePercent,\n );\n }\n\n if (input.net.currency.currencyCode !== input.tax.currency.currencyCode) {\n throw new CurrencyMismatchError(\"net and tax currencies must match\");\n }\n const gross = input.net.add(input.tax);\n return new LineTax(\"net+tax\", input.net, input.tax, gross, null);\n }\n\n withRounding(round = Rounding.currencyDefault()): LineTax {\n return new LineTax(\n this.truth,\n this.net.with(round),\n this.tax.with(round),\n this.gross.with(round),\n this.ratePercent,\n );\n }\n\n toJSON() {\n return {\n truth: this.truth,\n net: this.net.toJSON(),\n tax: this.tax.toJSON(),\n gross: this.gross.toJSON(),\n ratePercent: this.ratePercent,\n };\n }\n}\n\nexport function assertRate(ratePercent: string) {\n if (ratePercent.trim() === \"\") {\n throw new InvalidTruthError(\"ratePercent is required\");\n }\n}\n","import type { QupsTruthMode } from \"../qups.js\";\nimport type {\n BuiltinPricingFieldKey,\n PricingField,\n PricingFieldKind,\n PricingFieldRole,\n} from \"./types.js\";\n\n/** Which of Q / UP / S are sources of truth vs derived for a given mode. */\nexport function qupsRolesFor(\n truth: QupsTruthMode,\n): Record<\"quantity\" | \"unit_price\" | \"subtotal\", \"source\" | \"derived\"> {\n if (truth === \"quantity+unitPrice\") {\n return { quantity: \"source\", unit_price: \"source\", subtotal: \"derived\" };\n }\n if (truth === \"quantity+subtotal\") {\n return { quantity: \"source\", unit_price: \"derived\", subtotal: \"source\" };\n }\n return { quantity: \"derived\", unit_price: \"source\", subtotal: \"source\" };\n}\n\ntype FieldSeed = Omit<PricingField, \"id\" | \"profileId\">;\n\nconst BUILTIN_KEYS = new Set<string>([\n \"quantity\",\n \"unit_price\",\n \"subtotal\",\n \"modifiers\",\n \"tax\",\n \"net\",\n \"gross\",\n \"total\",\n]);\n\nexport function isBuiltinFieldKey(key: string): key is BuiltinPricingFieldKey {\n return BUILTIN_KEYS.has(key);\n}\n\nfunction moneyField(\n key: \"unit_price\" | \"subtotal\",\n label: string,\n role: PricingFieldRole,\n position: number,\n): FieldSeed {\n return {\n key,\n label,\n kind: \"money\",\n role,\n enabled: true,\n required: role === \"source\",\n position,\n };\n}\n\n/**\n * Build a headless field catalog from a truth mode.\n * Money fields are first-class (`unit_price`, `subtotal`) — one shared `currency`\n * column plus `*_amount` SQL columns, not separate catalog entries.\n */\nexport function fieldsForTruth(\n truth: QupsTruthMode,\n options?: {\n includeModifiers?: boolean;\n includeTax?: boolean;\n includeNetGross?: boolean;\n includeTotal?: boolean;\n extras?: readonly {\n key: string;\n label?: string;\n kind?: PricingFieldKind;\n required?: boolean;\n }[];\n },\n): FieldSeed[] {\n const roles = qupsRolesFor(truth);\n const fields: FieldSeed[] = [\n {\n key: \"quantity\",\n label: \"Quantity\",\n kind: \"quantity\",\n role: roles.quantity,\n enabled: true,\n required: roles.quantity === \"source\",\n position: 0,\n },\n moneyField(\"unit_price\", \"Unit price\", roles.unit_price, 1),\n moneyField(\"subtotal\", \"Subtotal\", roles.subtotal, 2),\n ];\n\n let pos = 3;\n if (options?.includeModifiers !== false) {\n fields.push({\n key: \"modifiers\",\n label: \"Modifiers\",\n kind: \"modifiers\",\n role: \"independent\",\n enabled: true,\n position: pos++,\n });\n }\n if (options?.includeTax !== false) {\n fields.push({\n key: \"tax\",\n label: \"Tax\",\n kind: \"percent\",\n role: \"independent\",\n enabled: true,\n position: pos++,\n });\n }\n if (options?.includeNetGross !== false) {\n fields.push({\n key: \"net\",\n label: \"Net\",\n kind: \"money\",\n role: \"derived\",\n enabled: true,\n position: pos++,\n });\n fields.push({\n key: \"gross\",\n label: \"Gross\",\n kind: \"money\",\n role: \"derived\",\n enabled: true,\n position: pos++,\n });\n }\n if (options?.includeTotal !== false) {\n fields.push({\n key: \"total\",\n label: \"Total\",\n kind: \"derived\",\n role: \"derived\",\n enabled: true,\n position: pos++,\n });\n }\n\n for (const extra of options?.extras ?? []) {\n fields.push({\n key: extra.key,\n label: extra.label ?? extra.key,\n kind: extra.kind ?? \"text\",\n role: \"independent\",\n enabled: true,\n required: extra.required,\n position: pos++,\n });\n }\n\n return fields;\n}\n\n/** Re-apply QUPS source/derived roles after a truth change; keep customs as-is. */\nexport function syncFieldRoles(\n fields: readonly FieldSeed[],\n truth: QupsTruthMode,\n): FieldSeed[] {\n const roles = qupsRolesFor(truth);\n return fields.map((f) => {\n if (f.key === \"quantity\") {\n return {\n ...f,\n role: roles.quantity,\n required: roles.quantity === \"source\" ? true : f.required,\n };\n }\n if (f.key === \"unit_price\") {\n return {\n ...f,\n role: roles.unit_price,\n required: roles.unit_price === \"source\" ? true : f.required,\n };\n }\n if (f.key === \"subtotal\") {\n return {\n ...f,\n role: roles.subtotal,\n required: roles.subtotal === \"source\" ? true : f.required,\n };\n }\n if (\n f.key === \"total\" ||\n f.key === \"net\" ||\n f.key === \"gross\"\n ) {\n return { ...f, role: \"derived\" as const };\n }\n return { ...f };\n });\n}\n\nexport function editableFieldKeys(\n fields: readonly Pick<PricingField, \"key\" | \"enabled\" | \"role\">[],\n): string[] {\n return fields\n .filter((f) => f.enabled && f.role !== \"derived\")\n .map((f) => f.key);\n}\n\n/**\n * Headless column map for a money field key → { amountCol, currencyCol }.\n * QUPS lines use one shared `currency` column for all money amounts.\n */\nexport function moneyColumnPair(\n key: \"unit_price\" | \"subtotal\" | \"tax\" | \"net\" | \"gross\",\n): { amount: string; currency: string } {\n if (key === \"unit_price\") {\n return { amount: \"unit_price_amount\", currency: \"currency\" };\n }\n if (key === \"subtotal\") {\n return { amount: \"subtotal_amount\", currency: \"currency\" };\n }\n if (key === \"tax\") {\n return { amount: \"tax_amount\", currency: \"currency\" };\n }\n if (key === \"net\") {\n return { amount: \"net_amount\", currency: \"currency\" };\n }\n return { amount: \"gross_amount\", currency: \"currency\" };\n}\n","import { Money } from \"@eristack/money\";\nimport { PricingLine, type PricingLineInput } from \"../line.js\";\nimport type { ModifierSpec } from \"../modifier.js\";\nimport type { QupsInput, QupsTruthMode } from \"../qups.js\";\nimport type {\n PricingFieldValue,\n PricingLineRecord,\n PricingModifierRecord,\n PricingTaxDefaults,\n} from \"./types.js\";\n\nexport function modifiersToRecords(\n modifiers: readonly ModifierSpec[],\n idFactory: () => string,\n): PricingModifierRecord[] {\n return modifiers.map((m, position) => {\n if (m.type === \"percent\") {\n return {\n id: m.id ?? idFactory(),\n position,\n kind: m.kind,\n type: \"percent\" as const,\n percent: m.percent,\n };\n }\n return {\n id: m.id ?? idFactory(),\n position,\n kind: m.kind,\n type: \"nominal\" as const,\n amount: m.amount.toJSON().amount,\n currency: m.amount.currency.currencyCode,\n };\n });\n}\n\nexport function recordsToModifiers(\n modifiers: readonly PricingModifierRecord[],\n fallbackCurrency: string,\n): ModifierSpec[] {\n return [...modifiers]\n .sort((a, b) => a.position - b.position)\n .map((m) => {\n if (m.type === \"percent\") {\n return {\n id: m.id,\n kind: m.kind,\n type: \"percent\" as const,\n percent: m.percent ?? \"0\",\n };\n }\n return {\n id: m.id,\n kind: m.kind,\n type: \"nominal\" as const,\n amount: Money.of(m.amount ?? \"0\", m.currency || fallbackCurrency),\n };\n });\n}\n\nfunction qupsInputFromRecord(record: PricingLineRecord): QupsInput {\n const unitPrice = Money.of(record.unitPriceAmount, record.currency);\n const subtotal = Money.of(record.subtotalAmount, record.currency);\n if (record.truth === \"quantity+unitPrice\") {\n return {\n truth: \"quantity+unitPrice\",\n quantity: record.quantity,\n unitPrice,\n };\n }\n if (record.truth === \"quantity+subtotal\") {\n return {\n truth: \"quantity+subtotal\",\n quantity: record.quantity,\n subtotal,\n };\n }\n return {\n truth: \"unitPrice+subtotal\",\n unitPrice,\n subtotal,\n };\n}\n\nfunction taxFromRecord(\n record: PricingLineRecord,\n): PricingLineInput[\"tax\"] | undefined {\n if (!record.taxRatePercent) return undefined;\n if (record.taxMode === \"inclusive\") {\n return { ratePercent: record.taxRatePercent, mode: \"inclusive\" };\n }\n return { ratePercent: record.taxRatePercent, mode: \"exclusive\" };\n}\n\n/** Hydrate a persisted row into a live PricingLine (recomputes derived values). */\nexport function pricingLineFromRecord(record: PricingLineRecord): PricingLine {\n return PricingLine.of({\n qups: qupsInputFromRecord(record),\n modifiers: recordsToModifiers(record.modifiers, record.currency),\n tax: taxFromRecord(record),\n });\n}\n\nexport function recordFromPricingLine(options: {\n id: string;\n ownerKey: string;\n line: PricingLine;\n profileId?: string;\n fieldValues?: PricingFieldValue[];\n position?: number;\n createdAt: Date;\n updatedAt: Date;\n idFactory: () => string;\n}): PricingLineRecord {\n const { line } = options;\n const currency = line.qups.unitPrice.currency.currencyCode;\n const tax = taxOpts(line);\n return {\n id: options.id,\n ownerKey: options.ownerKey,\n profileId: options.profileId,\n truth: line.qups.truth,\n quantity: line.qups.quantity,\n quantityRatioNumerator: line.qups.quantityRatio?.numerator,\n quantityRatioDenominator: line.qups.quantityRatio?.denominator,\n currency,\n unitPriceAmount: line.qups.unitPrice.toJSON().amount,\n subtotalAmount: line.qups.subtotal.toJSON().amount,\n taxRatePercent: tax?.ratePercent,\n taxMode: tax?.mode,\n taxAmount: line.tax.tax.toJSON().amount,\n netAmount: line.tax.net.toJSON().amount,\n grossAmount: line.tax.gross.toJSON().amount,\n modifiers: modifiersToRecords(line.adjusted.modifiers, options.idFactory),\n fieldValues: options.fieldValues ?? [],\n position: options.position,\n createdAt: options.createdAt,\n updatedAt: options.updatedAt,\n };\n}\n\nfunction taxOpts(line: PricingLine): PricingTaxDefaults | undefined {\n if (!line.tax.ratePercent) return undefined;\n if (line.tax.truth === \"gross+rate\") {\n return { ratePercent: line.tax.ratePercent, mode: \"inclusive\" };\n }\n return { ratePercent: line.tax.ratePercent, mode: \"exclusive\" };\n}\n\nexport function pricingLineInputFromParts(input: {\n truth: QupsTruthMode;\n currency: string;\n quantity?: string;\n unitPrice?: string;\n subtotal?: string;\n modifiers?: readonly ModifierSpec[];\n tax?: PricingTaxDefaults;\n}): PricingLineInput {\n let qups: QupsInput;\n if (input.truth === \"quantity+unitPrice\") {\n if (input.quantity == null || input.unitPrice == null) {\n throw new Error(\"quantity+unitPrice requires quantity and unitPrice\");\n }\n qups = {\n truth: \"quantity+unitPrice\",\n quantity: input.quantity,\n unitPrice: Money.of(input.unitPrice, input.currency),\n };\n } else if (input.truth === \"quantity+subtotal\") {\n if (input.quantity == null || input.subtotal == null) {\n throw new Error(\"quantity+subtotal requires quantity and subtotal\");\n }\n qups = {\n truth: \"quantity+subtotal\",\n quantity: input.quantity,\n subtotal: Money.of(input.subtotal, input.currency),\n };\n } else {\n if (input.unitPrice == null || input.subtotal == null) {\n throw new Error(\"unitPrice+subtotal requires unitPrice and subtotal\");\n }\n qups = {\n truth: \"unitPrice+subtotal\",\n unitPrice: Money.of(input.unitPrice, input.currency),\n subtotal: Money.of(input.subtotal, input.currency),\n };\n }\n\n return {\n qups,\n modifiers: input.modifiers,\n tax: input.tax\n ? input.tax.mode === \"inclusive\"\n ? { ratePercent: input.tax.ratePercent, mode: \"inclusive\" }\n : { ratePercent: input.tax.ratePercent, mode: \"exclusive\" }\n : undefined,\n };\n}\n\n/** Headless view of built-in columns + custom field values for forms/APIs. */\nexport function lineFieldMap(record: PricingLineRecord): Record<\n string,\n { value: string; currency?: string }\n> {\n const map: Record<string, { value: string; currency?: string }> = {\n quantity: { value: record.quantity },\n unit_price: {\n value: record.unitPriceAmount,\n currency: record.currency,\n },\n subtotal: {\n value: record.subtotalAmount,\n currency: record.currency,\n },\n };\n if (record.taxRatePercent != null) {\n map.tax = { value: record.taxRatePercent };\n }\n if (record.taxAmount != null) {\n map.tax_amount = {\n value: record.taxAmount,\n currency: record.currency,\n };\n }\n if (record.netAmount != null) {\n map.net = { value: record.netAmount, currency: record.currency };\n }\n if (record.grossAmount != null) {\n map.gross = { value: record.grossAmount, currency: record.currency };\n map.total = { value: record.grossAmount, currency: record.currency };\n }\n for (const fv of record.fieldValues) {\n map[fv.fieldKey] = { value: fv.value, currency: fv.currency };\n }\n return map;\n}\n","import {\n LineNotFoundError,\n MissingDependencyError,\n ProfileNotFoundError,\n} from \"./errors.js\";\nimport { PricingLine } from \"./line.js\";\nimport {\n editableFieldKeys,\n fieldsForTruth,\n syncFieldRoles,\n} from \"./stores/fields.js\";\nimport {\n lineFieldMap,\n pricingLineFromRecord,\n pricingLineInputFromParts,\n recordFromPricingLine,\n} from \"./stores/serialize.js\";\nimport type {\n PricingField,\n PricingLineRecord,\n PricingLineStore,\n PricingProfile,\n PricingProfileStore,\n RegisterProfileInput,\n SaveLineInput,\n UpdateProfileInput,\n} from \"./stores/types.js\";\nimport type { QupsTruthMode } from \"./qups.js\";\nimport { entityIdFactory } from \"@eristack/entity-id\";\n\nexport interface CreateQupsOptions {\n profiles?: PricingProfileStore;\n lines?: PricingLineStore;\n clock?: () => Date;\n idFactory?: () => string;\n}\n\nexport interface QupsApi {\n registerProfile(input: RegisterProfileInput): Promise<PricingProfile>;\n updateProfile(input: UpdateProfileInput): Promise<PricingProfile>;\n getProfile(entityKey: string): Promise<PricingProfile | null>;\n getProfileById(id: string): Promise<PricingProfile | null>;\n listProfiles(entityKey: string): Promise<PricingProfile[]>;\n\n saveLine(input: SaveLineInput): Promise<PricingLineRecord>;\n getLine(id: string): Promise<PricingLineRecord | null>;\n listLines(ownerKey: string): Promise<PricingLineRecord[]>;\n deleteLine(id: string): Promise<void>;\n\n hydrateLine(record: PricingLineRecord): PricingLine;\n /** Headless map of field key → { value, currency? } for forms/APIs. */\n lineFields(record: PricingLineRecord): Record<\n string,\n { value: string; currency?: string }\n >;\n fieldsFor(\n truth: QupsTruthMode,\n profile?: PricingProfile | null,\n ): Omit<PricingField, \"id\" | \"profileId\">[];\n editableKeys(\n fields: readonly Pick<PricingField, \"key\" | \"enabled\" | \"role\">[],\n ): string[];\n}\n\nfunction attachFieldIds(\n profileId: string,\n seeds: Omit<PricingField, \"id\" | \"profileId\">[],\n idFactory: () => string,\n): PricingField[] {\n return seeds.map((f) => ({\n ...f,\n id: idFactory(),\n profileId,\n }));\n}\n\nexport function createQups(options: CreateQupsOptions = {}): QupsApi {\n const clock = options.clock ?? (() => new Date());\n const idFactory = options.idFactory ?? entityIdFactory;\n const profiles = options.profiles;\n const lines = options.lines;\n\n function requireProfiles(): PricingProfileStore {\n if (!profiles) {\n throw new MissingDependencyError(\"profiles (PricingProfileStore)\");\n }\n return profiles;\n }\n\n function requireLines(): PricingLineStore {\n if (!lines) throw new MissingDependencyError(\"lines (PricingLineStore)\");\n return lines;\n }\n\n async function deactivateSiblings(entityKey: string, exceptId: string) {\n const store = requireProfiles();\n const siblings = await store.listByEntityKey(entityKey);\n const now = clock();\n await Promise.all(\n siblings\n .filter((p) => p.id !== exceptId && p.active)\n .map((p) =>\n store.save({\n ...p,\n active: false,\n updatedAt: now,\n }),\n ),\n );\n }\n\n return {\n async registerProfile(input) {\n const store = requireProfiles();\n const now = clock();\n const truth = input.defaultTruth ?? \"quantity+unitPrice\";\n const profileId = input.id ?? idFactory();\n\n const seeds = input.fields?.length\n ? syncFieldRoles(input.fields, truth)\n : fieldsForTruth(truth);\n\n const record: PricingProfile = {\n id: profileId,\n entityKey: input.entityKey,\n defaultTruth: truth,\n defaultCurrencyCode: input.defaultCurrencyCode,\n fields: attachFieldIds(profileId, seeds, idFactory),\n defaultTaxRatePercent: input.defaultTaxRatePercent,\n defaultTaxMode: input.defaultTaxMode,\n allowedModifierKinds: input.allowedModifierKinds,\n active: input.activate !== false,\n createdAt: now,\n updatedAt: now,\n };\n\n if (record.active) {\n await deactivateSiblings(record.entityKey, record.id);\n }\n await store.save(record);\n return record;\n },\n\n async updateProfile(input) {\n const store = requireProfiles();\n const existing = await store.findById(input.id);\n if (!existing) throw new ProfileNotFoundError(input.id);\n\n const truth = input.defaultTruth ?? existing.defaultTruth;\n let fields = existing.fields;\n if (input.fields) {\n fields = attachFieldIds(\n existing.id,\n syncFieldRoles(input.fields, truth),\n idFactory,\n );\n } else if (input.defaultTruth) {\n fields = attachFieldIds(\n existing.id,\n syncFieldRoles(\n existing.fields.map(({ id: _id, profileId: _p, ...rest }) => rest),\n truth,\n ),\n idFactory,\n );\n }\n\n const now = clock();\n const next: PricingProfile = {\n ...existing,\n defaultTruth: truth,\n defaultCurrencyCode:\n input.defaultCurrencyCode ?? existing.defaultCurrencyCode,\n fields,\n defaultTaxRatePercent:\n input.defaultTaxRatePercent === null\n ? undefined\n : (input.defaultTaxRatePercent ?? existing.defaultTaxRatePercent),\n defaultTaxMode:\n input.defaultTaxMode === null\n ? undefined\n : (input.defaultTaxMode ?? existing.defaultTaxMode),\n allowedModifierKinds:\n input.allowedModifierKinds === null\n ? undefined\n : (input.allowedModifierKinds ?? existing.allowedModifierKinds),\n active: input.active ?? existing.active,\n updatedAt: now,\n };\n\n if (next.active) {\n await deactivateSiblings(next.entityKey, next.id);\n }\n await store.save(next);\n return next;\n },\n\n async getProfile(entityKey) {\n return requireProfiles().findActiveByEntityKey(entityKey);\n },\n\n async getProfileById(id) {\n return requireProfiles().findById(id);\n },\n\n async listProfiles(entityKey) {\n return requireProfiles().listByEntityKey(entityKey);\n },\n\n async saveLine(input) {\n const store = requireLines();\n const now = clock();\n const existing = input.id ? await store.findById(input.id) : null;\n\n let line: PricingLine;\n if (input.line) {\n line = input.line;\n } else {\n const currency =\n input.currency ??\n existing?.currency ??\n (() => {\n throw new Error(\"currency is required when line is omitted\");\n })();\n const truth = input.truth ?? existing?.truth ?? \"quantity+unitPrice\";\n line = PricingLine.of(\n pricingLineInputFromParts({\n truth,\n currency,\n quantity: input.quantity ?? existing?.quantity,\n unitPrice: input.unitPrice ?? existing?.unitPriceAmount,\n subtotal: input.subtotal ?? existing?.subtotalAmount,\n modifiers:\n input.modifiers ??\n (existing\n ? pricingLineFromRecord(existing).adjusted.modifiers\n : []),\n tax:\n input.tax ??\n (existing?.taxRatePercent\n ? {\n ratePercent: existing.taxRatePercent,\n mode: existing.taxMode,\n }\n : undefined),\n }),\n );\n }\n\n const record = recordFromPricingLine({\n id: input.id ?? existing?.id ?? idFactory(),\n ownerKey: input.ownerKey,\n line,\n profileId: input.profileId ?? existing?.profileId,\n fieldValues: input.fieldValues ?? existing?.fieldValues ?? [],\n position: input.position ?? existing?.position,\n createdAt: existing?.createdAt ?? now,\n updatedAt: now,\n idFactory,\n });\n record.rowExtras = input.rowExtras ?? existing?.rowExtras;\n\n await store.save(record);\n return record;\n },\n\n async getLine(id) {\n return requireLines().findById(id);\n },\n\n async listLines(ownerKey) {\n return requireLines().listByOwnerKey(ownerKey);\n },\n\n async deleteLine(id) {\n const store = requireLines();\n const existing = await store.findById(id);\n if (!existing) throw new LineNotFoundError(id);\n await store.delete(id);\n },\n\n hydrateLine(record) {\n return pricingLineFromRecord(record);\n },\n\n lineFields(record) {\n return lineFieldMap(record);\n },\n\n fieldsFor(truth, profile) {\n if (!profile) return fieldsForTruth(truth);\n return syncFieldRoles(\n profile.fields.map(({ id: _i, profileId: _p, ...rest }) => rest),\n truth,\n );\n },\n\n editableKeys: editableFieldKeys,\n };\n}\n","import { requireParam } from \"@eristack/backseat/adapters\";\nimport type { BackseatHandlerContext, BackseatResponse } from \"@eristack/backseat\";\nimport { calculateLine, patchLine } from \"../core/calculate.js\";\nimport type { QupsApi } from \"../core/create-qups.js\";\n\nexport function createQupsRoutes(qups: QupsApi) {\n return [\n {\n method: \"POST\" as const,\n segment: \"/calculate-line\",\n name: \"qups.calculate-line\",\n handler: async (ctx: BackseatHandlerContext) => ({\n status: 200,\n body: calculateLine(ctx.json() as Parameters<typeof calculateLine>[0]),\n }),\n },\n {\n method: \"POST\" as const,\n segment: \"/patch-line\",\n name: \"qups.patch-line\",\n handler: async (ctx: BackseatHandlerContext) => {\n const body = ctx.json<{\n current: Parameters<typeof patchLine>[0];\n patch: Parameters<typeof patchLine>[1];\n }>();\n return { status: 200, body: patchLine(body.current, body.patch) };\n },\n },\n {\n method: \"GET\" as const,\n segment: \"/lines/:ownerKey\",\n name: \"qups.list-lines\",\n handler: async (ctx: BackseatHandlerContext) => {\n const ownerKey = requireParam(ctx.params.ownerKey, \"ownerKey required\");\n if (typeof ownerKey !== \"string\") return ownerKey;\n return { status: 200, body: await qups.listLines(ownerKey) };\n },\n },\n ] satisfies Array<{\n method: \"GET\" | \"POST\";\n segment: string;\n name: string;\n handler: (ctx: BackseatHandlerContext) => Promise<BackseatResponse>;\n }>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,qBAA0C;;;ACD1C,sBAAuB;;;ACAhB,IAAM,mBAAmB;AAAA,EAC9B,UAAU;AAAA,EACV,OAAO;AACT;;;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ACN,SAAS,OAAO,QAAgC;AAC9C,cAAM,eAAW,+BAAa,IAAI,OAAO,UAAU,mBAAmB;AACtE,YAAI,OAAO,aAAa,SAAU,QAAO;AACzC,eAAO,EAAE,QAAQ,KAAK,MAAM,MAAM,KAAK,UAAU,QAAQ,EAAE;AAAA,MAC7D;AAAA,IACF;AAAA,EACF;AAMF;;;AVhCO,SAAS,qBACd,KACA,UAAuC,CAAC,GAC/B;AACT,QAAM,WACJ,QAAQ,YAAY,kCAAkC,IAAI,KAAK;AACjE,QAAM,QAAQ,QAAQ,SAAS,+BAA+B,IAAI,KAAK;AACvE,QAAM,OACJ,QAAQ,QACR,WAAW;AAAA,IACT;AAAA,IACA;AAAA,IACA,OAAO,QAAQ;AAAA,IACf,WAAW,QAAQ;AAAA,EACrB,CAAC;AAEH,8CAAsB,KAAK,QAAQ,YAAY,SAAS,iBAAiB,IAAI,CAAC;AAE9E,MAAI;AAAA,IAAe;AAAA,IAAsB,OAAO,EAAE,MAAM,MACtD,cAAc,KAA4C;AAAA,EAC5D;AAEA,SAAO;AACT;;;AH3BO,SAAS,yBAAyB,UAErC,CAAC,GAIH;AACA,QAAM,gBAAgB,QAAQ,aAAS,0CAA0B;AACjE,SAAO;AAAA,IACL;AAAA,IACA,UAAU,kCAAkC,aAAa;AAAA,IACzD,OAAO,+BAA+B,aAAa;AAAA,EACrD;AACF;","names":["import_adapters","import_money","import_money","next","net","steps","Decimal","import_money","gross","taxInput","import_money","import_adapters"]}