UNPKG

@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 • 67.1 kB
{"version":3,"sources":["../../../src/backseat/store/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/qups.ts","../../../src/core/tax.ts","../../../src/core/stores/serialize.ts","../../../src/core/create-qups.ts","../../../src/backseat/qups-routes.ts"],"sourcesContent":["import { createIndexedDbBackseatStore } from \"@eristack/backseat/store\";\nimport type { PricingLineStore, PricingProfileStore } from \"../../core/stores/types.js\";\nimport {\n  createBackseatPricingLineStore,\n  createBackseatPricingProfileStore,\n} from \"../stores.js\";\n\nexport type CreateIndexedDbQupsStoresOptions = {\n  dbName?: string;\n};\n\nexport function createIndexedDbQupsStores(\n  options: CreateIndexedDbQupsStoresOptions = {},\n): {\n  backseatStore: ReturnType<typeof createIndexedDbBackseatStore>;\n  profiles: PricingProfileStore;\n  lines: PricingLineStore;\n} {\n  const backseatStore = createIndexedDbBackseatStore({\n    dbName: options.dbName,\n  });\n  return {\n    backseatStore,\n    profiles: createBackseatPricingProfileStore(backseatStore),\n    lines: createBackseatPricingLineStore(backseatStore),\n  };\n}\n\nexport {\n  createBackseatPricingLineStore,\n  createBackseatPricingProfileStore,\n  QUPS_COLLECTIONS,\n} 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","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 { 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,mBAA6C;;;ACA7C,sBAAuB;;;ACAhB,IAAM,mBAAmB;AAAA,EAC9B,UAAU;AAAA,EACV,OAAO;AACT;;;ADWA,SAAS,eAAe,KAA8C;AACpE,SAAO;AAAA,IACL,IAAI,OAAO,IAAI,EAAE;AAAA,IACjB,WAAW,OAAO,IAAI,SAAS;AAAA,IAC/B,cAAc,OAAO,IAAI,YAAY;AAAA,IACrC,qBAAqB,OAAO,IAAI,mBAAmB;AAAA,IACnD,QAAQ,MAAM,QAAQ,IAAI,MAAM,IAC3B,IAAI,SACL,CAAC;AAAA,IACL,uBACE,IAAI,yBAAyB,OACzB,SACA,OAAO,IAAI,qBAAqB;AAAA,IACtC,gBACE,IAAI,kBAAkB,OAClB,SACC,OAAO,IAAI,cAAc;AAAA,IAChC,sBAAsB,MAAM,QAAQ,IAAI,oBAAoB,IACvD,IA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