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,388 lines (1,378 loc) • 40.1 kB
// src/core/truth-mode.ts var QUPS_TRUTH_MODES = [ "quantity+unitPrice", "quantity+subtotal", "unitPrice+subtotal" ]; function isQupsTruthMode(value) { return typeof value === "string" && QUPS_TRUTH_MODES.includes(value); } // src/core/errors.ts var QupsError = class extends Error { code; constructor(code, message) { super(message); this.name = "QupsError"; this.code = code; } }; var InvalidTruthError = class extends QupsError { constructor(message) { super("INVALID_TRUTH", message); this.name = "InvalidTruthError"; } }; var CurrencyMismatchError = class extends QupsError { constructor(message) { super("CURRENCY_MISMATCH", message); this.name = "CurrencyMismatchError"; } }; var MissingDependencyError = class extends QupsError { constructor(dependency) { super("MISSING_DEPENDENCY", `Missing dependency: ${dependency}`); this.name = "MissingDependencyError"; } }; var ProfileNotFoundError = class extends QupsError { constructor(entityKeyOrId) { super("PROFILE_NOT_FOUND", `Pricing profile not found: ${entityKeyOrId}`); this.name = "ProfileNotFoundError"; } }; var LineNotFoundError = class extends QupsError { constructor(id) { super("LINE_NOT_FOUND", `Pricing line not found: ${id}`); this.name = "LineNotFoundError"; } }; // src/core/qups.ts import Decimal from "decimal.js"; var QtyDecimal = Decimal.clone({ precision: 40, rounding: Decimal.ROUND_HALF_EVEN }); function assertQuantity(quantity) { if (quantity.trim() === "") { throw new InvalidTruthError("quantity is required"); } try { new QtyDecimal(quantity); } catch { throw new InvalidTruthError(`Invalid quantity: ${quantity}`); } } function sameCurrency(a, b) { if (a.currency.currencyCode !== b.currency.currencyCode) { throw new CurrencyMismatchError( `Currency mismatch: ${a.currency.currencyCode} vs ${b.currency.currencyCode}` ); } } function ratioString(ratio) { return new QtyDecimal(ratio.numerator).div(ratio.denominator).toFixed(); } var Qups = class _Qups { truth; unitPrice; subtotal; /** * Decimal string view of quantity (high precision). * Prefer `quantityRatio` when truth is `unitPrice+subtotal`. */ quantity; /** Exact ratio when quantity was derived from unitPrice+subtotal; else null. */ quantityRatio; constructor(truth, quantity, unitPrice, subtotal, quantityRatio) { this.truth = truth; this.quantity = quantity; this.unitPrice = unitPrice; this.subtotal = subtotal; this.quantityRatio = quantityRatio; } get currency() { return this.unitPrice.currency; } static of(input) { if (input.truth === "quantity+unitPrice") { assertQuantity(input.quantity); const quantity = input.quantity.trim(); const subtotal = input.unitPrice.multiply(quantity); return new _Qups( "quantity+unitPrice", quantity, input.unitPrice, subtotal, null ); } if (input.truth === "quantity+subtotal") { assertQuantity(input.quantity); const quantity = input.quantity.trim(); if (new QtyDecimal(quantity).isZero()) { throw new InvalidTruthError( "Cannot derive unitPrice when quantity is 0" ); } const unitPrice = input.subtotal.divide(quantity); return new _Qups( "quantity+subtotal", quantity, unitPrice, input.subtotal, null ); } sameCurrency(input.unitPrice, input.subtotal); if (input.unitPrice.isZero()) { throw new InvalidTruthError( "Cannot derive quantity when unitPrice is zero" ); } const numerator = input.subtotal.getNumber().toString(); const denominator = input.unitPrice.getNumber().toString(); const quantityRatio = { numerator, denominator }; return new _Qups( "unitPrice+subtotal", ratioString(quantityRatio), input.unitPrice, input.subtotal, quantityRatio ); } withTruth(input) { return _Qups.of(input); } /** * `quantity × unitPrice` using SoT when possible so UP+S never drifts. */ product() { if (this.truth === "unitPrice+subtotal") return this.subtotal; if (this.truth === "quantity+subtotal") return this.subtotal; return this.unitPrice.multiply(this.quantity); } /** * Common UI edits. Single-field defaults: * - qty or unitPrice → recompute subtotal (`quantity+unitPrice`) * - subtotal → keep unitPrice, recompute qty (`unitPrice+subtotal`) * unless `prefer: "quantity"` */ edit(patch, options) { const prefer = options?.prefer ?? "unitPrice"; const keys = ["quantity", "unitPrice", "subtotal"].filter((k) => patch[k] !== void 0); if (keys.length === 0) return this; if (keys.length >= 3) { throw new InvalidTruthError( "edit() accepts at most two of quantity, unitPrice, subtotal" ); } if (keys.length === 2) { if (keys.includes("quantity") && keys.includes("unitPrice")) { return _Qups.of({ truth: "quantity+unitPrice", quantity: patch.quantity, unitPrice: patch.unitPrice }); } if (keys.includes("quantity") && keys.includes("subtotal")) { return _Qups.of({ truth: "quantity+subtotal", quantity: patch.quantity, subtotal: patch.subtotal }); } return _Qups.of({ truth: "unitPrice+subtotal", unitPrice: patch.unitPrice, subtotal: patch.subtotal }); } if (patch.quantity !== void 0) { return _Qups.of({ truth: "quantity+unitPrice", quantity: patch.quantity, unitPrice: this.unitPrice }); } if (patch.unitPrice !== void 0) { return _Qups.of({ truth: "quantity+unitPrice", quantity: this.quantity, unitPrice: patch.unitPrice }); } if (prefer === "quantity") { return _Qups.of({ truth: "quantity+subtotal", quantity: this.quantity, subtotal: patch.subtotal }); } return _Qups.of({ truth: "unitPrice+subtotal", unitPrice: this.unitPrice, subtotal: patch.subtotal }); } asTruth(truth) { if (truth === "quantity+unitPrice") { return _Qups.of({ truth, quantity: this.quantity, unitPrice: this.unitPrice }); } if (truth === "quantity+subtotal") { return _Qups.of({ truth, quantity: this.quantity, subtotal: this.subtotal }); } return _Qups.of({ truth, unitPrice: this.unitPrice, subtotal: this.subtotal }); } withRounding(round) { const unitPrice = round.apply(this.unitPrice); const subtotal = round.apply(this.subtotal); if (this.truth === "quantity+unitPrice") { return _Qups.of({ truth: this.truth, quantity: this.quantity, unitPrice }); } if (this.truth === "quantity+subtotal") { return _Qups.of({ truth: this.truth, quantity: this.quantity, subtotal }); } return _Qups.of({ truth: this.truth, unitPrice, subtotal }); } toJSON() { return { truth: this.truth, quantity: this.quantity, quantityRatio: this.quantityRatio, unitPrice: this.unitPrice.toJSON(), subtotal: this.subtotal.toJSON() }; } }; // src/core/modifier.ts import { Money, Discount, Markup } from "@eristack/money"; function applyOne(running, spec) { if (spec.type === "percent") { if (spec.kind === "discount") { const next3 = running.with(Discount.ofPercent(spec.percent)); return { amount: running.subtract(next3), next: next3 }; } const next2 = running.with(Markup.ofPercent(spec.percent)); return { amount: next2.subtract(running), next: next2 }; } if (spec.amount.currency.currencyCode !== running.currency.currencyCode) { throw new CurrencyMismatchError( `Modifier currency ${spec.amount.currency.currencyCode} != base ${running.currency.currencyCode}` ); } if (spec.kind === "discount") { const next2 = running.subtract(spec.amount); return { amount: spec.amount, next: next2 }; } const next = running.add(spec.amount); return { amount: spec.amount, next }; } function applyForward(base, modifiers) { let running = base; const steps = []; for (const spec of modifiers) { const { amount, next } = applyOne(running, spec); running = next; steps.push({ spec, amount, running }); } return { net: running, steps }; } function reverseModifiers(net, modifiers) { let running = net; for (let i = modifiers.length - 1; i >= 0; i--) { const spec = modifiers[i]; if (spec.type === "percent") { if (spec.kind === "discount") { const factor = Money.of("100", running.currency).subtract(Money.of(spec.percent, running.currency)).divide("100").getNumber().toString(); running = running.divide(factor); } else { const factor = Money.of("100", running.currency).add(Money.of(spec.percent, running.currency)).divide("100").getNumber().toString(); running = running.divide(factor); } } else if (spec.kind === "discount") { running = running.add(spec.amount); } else { running = running.subtract(spec.amount); } } return running; } var AdjustedAmount = class _AdjustedAmount { truth; base; net; modifiers; steps; discountTotal; surchargeTotal; constructor(truth, base, net, modifiers, steps) { this.truth = truth; this.base = base; this.net = net; this.modifiers = modifiers; this.steps = steps; let discountTotal = Money.zero(base.currency); let surchargeTotal = Money.zero(base.currency); for (const step of steps) { if (step.spec.kind === "discount") { discountTotal = discountTotal.add(step.amount); } else { surchargeTotal = surchargeTotal.add(step.amount); } } this.discountTotal = discountTotal; this.surchargeTotal = surchargeTotal; } static of(input) { if (input.truth === "base+modifiers") { const { net: net2, steps: steps2 } = applyForward(input.base, input.modifiers); return new _AdjustedAmount( "base+modifiers", input.base, net2, input.modifiers, steps2 ); } if (input.truth === "base+net") { sameMoneyCurrency(input.base, input.net); const diff = input.base.subtract(input.net); let kind = input.kind; let amount; if (diff.isZero()) { kind = kind ?? "discount"; amount = Money.zero(input.base.currency); } else if (diff.isPositive()) { kind = "discount"; amount = diff; } else { kind = "surcharge"; amount = diff.abs(); } const modifiers = [ { id: input.id, kind, type: "nominal", amount } ]; const { net: net2, steps: steps2 } = applyForward(input.base, modifiers); return new _AdjustedAmount( "base+net", input.base, net2, modifiers, steps2 ); } if (!input.modifiers.length) { throw new InvalidTruthError( "modifiers+net requires at least one modifier to reverse" ); } const base = reverseModifiers(input.net, input.modifiers); const { net, steps } = applyForward(base, input.modifiers); return new _AdjustedAmount( "modifiers+net", base, net, input.modifiers, steps ); } toJSON() { return { truth: this.truth, base: this.base.toJSON(), net: this.net.toJSON(), discountTotal: this.discountTotal.toJSON(), surchargeTotal: this.surchargeTotal.toJSON(), modifiers: this.modifiers.map( (m) => m.type === "percent" ? { id: m.id, kind: m.kind, type: m.type, percent: m.percent } : { id: m.id, kind: m.kind, type: m.type, amount: m.amount.toJSON() } ) }; } }; function sameMoneyCurrency(a, b) { if (a.currency.currencyCode !== b.currency.currencyCode) { throw new CurrencyMismatchError( `Currency mismatch: ${a.currency.currencyCode} vs ${b.currency.currencyCode}` ); } } // src/core/tax.ts import { Tax, Rounding } from "@eristack/money"; var LineTax = class _LineTax { truth; net; tax; gross; /** Percent points when known from rate-based truth. */ ratePercent; constructor(truth, net, tax, gross, ratePercent) { this.truth = truth; this.net = net; this.tax = tax; this.gross = gross; this.ratePercent = ratePercent; } static of(input) { if (input.truth === "net+rate") { const tax = input.net.with(Tax.onExclusive(input.ratePercent)); const gross2 = input.net.add(tax); return new _LineTax( "net+rate", input.net, tax, gross2, input.ratePercent ); } if (input.truth === "gross+rate") { const net = input.gross.with(Tax.netFromInclusive(input.ratePercent)); const tax = input.gross.with(Tax.extractFromInclusive(input.ratePercent)); return new _LineTax( "gross+rate", net, tax, input.gross, input.ratePercent ); } if (input.net.currency.currencyCode !== input.tax.currency.currencyCode) { throw new CurrencyMismatchError("net and tax currencies must match"); } const gross = input.net.add(input.tax); return new _LineTax("net+tax", input.net, input.tax, gross, null); } withRounding(round = Rounding.currencyDefault()) { return new _LineTax( this.truth, this.net.with(round), this.tax.with(round), this.gross.with(round), this.ratePercent ); } toJSON() { return { truth: this.truth, net: this.net.toJSON(), tax: this.tax.toJSON(), gross: this.gross.toJSON(), ratePercent: this.ratePercent }; } }; // src/core/line.ts import { Money as Money3, Rounding as Rounding2 } from "@eristack/money"; var PricingLine = class _PricingLine { qups; adjusted; tax; /** Payable total (tax.gross). */ total; constructor(qups, adjusted, tax) { this.qups = qups; this.adjusted = adjusted; this.tax = tax; this.total = tax.gross; } static of(input) { const qups = Qups.of(input.qups); const adjusted = AdjustedAmount.of({ truth: "base+modifiers", base: qups.subtotal, modifiers: input.modifiers ?? [] }); const taxInput2 = input.tax; let tax; if (!taxInput2) { tax = LineTax.of({ truth: "net+tax", net: adjusted.net, tax: Money3.zero(adjusted.net.currency) }); } else if (taxInput2.mode === "inclusive") { tax = LineTax.of({ truth: "gross+rate", gross: adjusted.net, ratePercent: taxInput2.ratePercent, mode: "inclusive" }); } else { tax = LineTax.of({ truth: "net+rate", net: adjusted.net, ratePercent: taxInput2.ratePercent }); } return new _PricingLine(qups, adjusted, tax); } editQups(patch, options) { return _PricingLine.of({ qups: truthFromQups(this.qups.edit(patch, options)), modifiers: this.adjusted.modifiers, tax: taxOptsFrom(this.tax) }); } withModifiers(modifiers) { return _PricingLine.of({ qups: truthFromQups(this.qups), modifiers, tax: taxOptsFrom(this.tax) }); } withRounding(round = Rounding2.currencyDefault()) { const apply = (m) => m.with(round); return new _PricingLine( this.qups.withRounding({ apply }), AdjustedAmount.of({ truth: "base+modifiers", base: apply(this.adjusted.base), modifiers: this.adjusted.modifiers.map( (m) => m.type === "nominal" ? { ...m, amount: apply(m.amount) } : m ) }), this.tax.withRounding(round) ); } toJSON() { return { qups: this.qups.toJSON(), adjusted: this.adjusted.toJSON(), tax: this.tax.toJSON(), total: this.total.toJSON() }; } }; function truthFromQups(q) { if (q.truth === "quantity+unitPrice") { return { truth: "quantity+unitPrice", quantity: q.quantity, unitPrice: q.unitPrice }; } if (q.truth === "quantity+subtotal") { return { truth: "quantity+subtotal", quantity: q.quantity, subtotal: q.subtotal }; } return { truth: "unitPrice+subtotal", unitPrice: q.unitPrice, subtotal: q.subtotal }; } function taxOptsFrom(tax) { if (!tax.ratePercent) { if (tax.tax.isZero()) return void 0; return void 0; } if (tax.truth === "gross+rate") { return { ratePercent: tax.ratePercent, mode: "inclusive" }; } return { ratePercent: tax.ratePercent, mode: "exclusive" }; } // src/core/stores/fields.ts function qupsRolesFor(truth) { if (truth === "quantity+unitPrice") { return { quantity: "source", unit_price: "source", subtotal: "derived" }; } if (truth === "quantity+subtotal") { return { quantity: "source", unit_price: "derived", subtotal: "source" }; } return { quantity: "derived", unit_price: "source", subtotal: "source" }; } var BUILTIN_KEYS = /* @__PURE__ */ new Set([ "quantity", "unit_price", "subtotal", "modifiers", "tax", "net", "gross", "total" ]); function isBuiltinFieldKey(key) { return BUILTIN_KEYS.has(key); } function moneyField(key, label, role, position) { return { key, label, kind: "money", role, enabled: true, required: role === "source", position }; } function fieldsForTruth(truth, options) { const roles = qupsRolesFor(truth); const fields = [ { key: "quantity", label: "Quantity", kind: "quantity", role: roles.quantity, enabled: true, required: roles.quantity === "source", position: 0 }, moneyField("unit_price", "Unit price", roles.unit_price, 1), moneyField("subtotal", "Subtotal", roles.subtotal, 2) ]; let pos = 3; if (options?.includeModifiers !== false) { fields.push({ key: "modifiers", label: "Modifiers", kind: "modifiers", role: "independent", enabled: true, position: pos++ }); } if (options?.includeTax !== false) { fields.push({ key: "tax", label: "Tax", kind: "percent", role: "independent", enabled: true, position: pos++ }); } if (options?.includeNetGross !== false) { fields.push({ key: "net", label: "Net", kind: "money", role: "derived", enabled: true, position: pos++ }); fields.push({ key: "gross", label: "Gross", kind: "money", role: "derived", enabled: true, position: pos++ }); } if (options?.includeTotal !== false) { fields.push({ key: "total", label: "Total", kind: "derived", role: "derived", enabled: true, position: pos++ }); } for (const extra of options?.extras ?? []) { fields.push({ key: extra.key, label: extra.label ?? extra.key, kind: extra.kind ?? "text", role: "independent", enabled: true, required: extra.required, position: pos++ }); } return fields; } function syncFieldRoles(fields, truth) { const roles = qupsRolesFor(truth); return fields.map((f) => { if (f.key === "quantity") { return { ...f, role: roles.quantity, required: roles.quantity === "source" ? true : f.required }; } if (f.key === "unit_price") { return { ...f, role: roles.unit_price, required: roles.unit_price === "source" ? true : f.required }; } if (f.key === "subtotal") { return { ...f, role: roles.subtotal, required: roles.subtotal === "source" ? true : f.required }; } if (f.key === "total" || f.key === "net" || f.key === "gross") { return { ...f, role: "derived" }; } return { ...f }; }); } function editableFieldKeys(fields) { return fields.filter((f) => f.enabled && f.role !== "derived").map((f) => f.key); } function moneyColumnPair(key) { if (key === "unit_price") { return { amount: "unit_price_amount", currency: "currency" }; } if (key === "subtotal") { return { amount: "subtotal_amount", currency: "currency" }; } if (key === "tax") { return { amount: "tax_amount", currency: "currency" }; } if (key === "net") { return { amount: "net_amount", currency: "currency" }; } return { amount: "gross_amount", currency: "currency" }; } // src/core/calculate.ts import { Money as Money4, Rounding as Rounding3 } from "@eristack/money"; function toPricingLine(input) { const { truth, currency } = input; let line; if (truth === "quantity+unitPrice") { if (input.quantity == null || input.unitPrice == null) { throw new Error("truth quantity+unitPrice requires quantity and unitPrice"); } line = PricingLine.of({ qups: { truth, quantity: input.quantity, unitPrice: Money4.of(input.unitPrice, currency) }, modifiers: mapModifiers(input.modifiers, currency), tax: taxInput(input) }); } else if (truth === "quantity+subtotal") { if (input.quantity == null || input.subtotal == null) { throw new Error("truth quantity+subtotal requires quantity and subtotal"); } line = PricingLine.of({ qups: { truth, quantity: input.quantity, subtotal: Money4.of(input.subtotal, currency) }, modifiers: mapModifiers(input.modifiers, currency), tax: taxInput(input) }); } else { if (input.unitPrice == null || input.subtotal == null) { throw new Error("truth unitPrice+subtotal requires unitPrice and subtotal"); } line = PricingLine.of({ qups: { truth, unitPrice: Money4.of(input.unitPrice, currency), subtotal: Money4.of(input.subtotal, currency) }, modifiers: mapModifiers(input.modifiers, currency), tax: taxInput(input) }); } return input.round ? line.withRounding(Rounding3.currencyDefault()) : line; } function mapModifiers(modifiers, currency) { return (modifiers ?? []).map((m) => { if (m.type === "percent") { return { id: m.id, kind: m.kind, type: "percent", percent: m.percent }; } return { id: m.id, kind: m.kind, type: "nominal", amount: Money4.of(m.amount, m.currency ?? currency) }; }); } function taxInput(input) { if (!input.taxRatePercent) return void 0; if (input.taxMode === "inclusive") { return { ratePercent: input.taxRatePercent, mode: "inclusive" }; } return { ratePercent: input.taxRatePercent, mode: "exclusive" }; } function snapshotFromLine(line, currency, taxRatePercent, taxMode) { const amount = (m) => m.toJSON().amount; const qtyRatio = line.qups.quantityRatio; const resolvedTaxMode = taxMode ?? (line.tax.truth === "gross+rate" ? "inclusive" : line.tax.ratePercent ? "exclusive" : null); const resolvedRate = taxRatePercent ?? line.tax.ratePercent; const modifiers = line.adjusted.modifiers.map((m) => { if (m.type === "percent") { return { id: m.id, kind: m.kind, type: "percent", percent: m.percent }; } return { id: m.id, kind: m.kind, type: "nominal", amount: amount(m.amount), currency: m.amount.currency.currencyCode }; }); return { truth: line.qups.truth, currency, quantity: line.qups.quantity, quantityRatio: qtyRatio, unitPrice: amount(line.qups.unitPrice), subtotal: amount(line.qups.subtotal), discountTotal: amount(line.adjusted.discountTotal), surchargeTotal: amount(line.adjusted.surchargeTotal), net: amount(line.tax.net), taxAmount: amount(line.tax.tax), taxRatePercent: resolvedRate, taxMode: resolvedTaxMode, total: amount(line.total), modifiers, roles: qupsRolesFor(line.qups.truth), columns: { truth: line.qups.truth, quantity: line.qups.quantity, quantityRatioNumerator: qtyRatio?.numerator ?? null, quantityRatioDenominator: qtyRatio?.denominator ?? null, currency, unitPriceAmount: amount(line.qups.unitPrice), subtotalAmount: amount(line.qups.subtotal), taxRatePercent: resolvedRate, taxMode: resolvedTaxMode, taxAmount: amount(line.tax.tax), netAmount: amount(line.tax.net), grossAmount: amount(line.total) } }; } function calculateLine(input) { const line = toPricingLine(input); return snapshotFromLine( line, input.currency, input.taxRatePercent ?? null, input.taxMode ?? null ); } function asCalculateInput(current) { if ("columns" in current) { return { truth: current.truth, currency: current.currency, quantity: current.quantity, unitPrice: current.unitPrice, subtotal: current.subtotal, modifiers: current.modifiers, taxRatePercent: current.taxRatePercent ?? void 0, taxMode: current.taxMode ?? void 0 }; } return current; } function patchLine(current, patch) { const base = asCalculateInput(current); const currency = patch.currency ?? base.currency; const modifiers = patch.modifiers ?? base.modifiers; const taxRatePercent = patch.taxRatePercent === null ? void 0 : patch.taxRatePercent ?? base.taxRatePercent; const taxMode = patch.taxMode === null ? void 0 : patch.taxMode ?? base.taxMode; const round = patch.round ?? base.round; const qupsChanged = patch.quantity !== void 0 || patch.unitPrice !== void 0 || patch.subtotal !== void 0 || patch.truth !== void 0; if (!qupsChanged) { return calculateLine({ truth: patch.truth ?? base.truth, currency, quantity: base.quantity, unitPrice: base.unitPrice, subtotal: base.subtotal, modifiers, taxRatePercent, taxMode, round }); } let live = toPricingLine({ ...base // keep base tax while editing qups; tax applied again below }); if (patch.truth && patch.truth !== live.qups.truth) { const q = live.qups.asTruth(patch.truth); live = toPricingLine({ truth: q.truth, currency: base.currency, quantity: q.quantity, unitPrice: q.unitPrice.toJSON().amount, subtotal: q.subtotal.toJSON().amount, modifiers: base.modifiers, taxRatePercent: base.taxRatePercent, taxMode: base.taxMode }); } const editPatch = {}; if (patch.quantity !== void 0) editPatch.quantity = patch.quantity; if (patch.unitPrice !== void 0) { editPatch.unitPrice = Money4.of(patch.unitPrice, currency); } if (patch.subtotal !== void 0) { editPatch.subtotal = Money4.of(patch.subtotal, currency); } if (Object.keys(editPatch).length) { live = live.editQups(editPatch, { prefer: patch.prefer }); } return calculateLine({ truth: live.qups.truth, currency, quantity: live.qups.quantity, unitPrice: live.qups.unitPrice.toJSON().amount, subtotal: live.qups.subtotal.toJSON().amount, modifiers, taxRatePercent, taxMode, round }); } function withQupsColumns(row, line) { const columns = "columns" in line ? line.columns : line; return { ...row, ...columns }; } // src/core/stores/serialize.ts import { Money as Money5 } from "@eristack/money"; function modifiersToRecords(modifiers, idFactory) { return modifiers.map((m, position) => { if (m.type === "percent") { return { id: m.id ?? idFactory(), position, kind: m.kind, type: "percent", percent: m.percent }; } return { id: m.id ?? idFactory(), position, kind: m.kind, type: "nominal", amount: m.amount.toJSON().amount, currency: m.amount.currency.currencyCode }; }); } function recordsToModifiers(modifiers, fallbackCurrency) { return [...modifiers].sort((a, b) => a.position - b.position).map((m) => { if (m.type === "percent") { return { id: m.id, kind: m.kind, type: "percent", percent: m.percent ?? "0" }; } return { id: m.id, kind: m.kind, type: "nominal", amount: Money5.of(m.amount ?? "0", m.currency || fallbackCurrency) }; }); } function qupsInputFromRecord(record) { const unitPrice = Money5.of(record.unitPriceAmount, record.currency); const subtotal = Money5.of(record.subtotalAmount, record.currency); if (record.truth === "quantity+unitPrice") { return { truth: "quantity+unitPrice", quantity: record.quantity, unitPrice }; } if (record.truth === "quantity+subtotal") { return { truth: "quantity+subtotal", quantity: record.quantity, subtotal }; } return { truth: "unitPrice+subtotal", unitPrice, subtotal }; } function taxFromRecord(record) { if (!record.taxRatePercent) return void 0; if (record.taxMode === "inclusive") { return { ratePercent: record.taxRatePercent, mode: "inclusive" }; } return { ratePercent: record.taxRatePercent, mode: "exclusive" }; } function pricingLineFromRecord(record) { return PricingLine.of({ qups: qupsInputFromRecord(record), modifiers: recordsToModifiers(record.modifiers, record.currency), tax: taxFromRecord(record) }); } function recordFromPricingLine(options) { const { line } = options; const currency = line.qups.unitPrice.currency.currencyCode; const tax = taxOpts(line); return { id: options.id, ownerKey: options.ownerKey, profileId: options.profileId, truth: line.qups.truth, quantity: line.qups.quantity, quantityRatioNumerator: line.qups.quantityRatio?.numerator, quantityRatioDenominator: line.qups.quantityRatio?.denominator, currency, unitPriceAmount: line.qups.unitPrice.toJSON().amount, subtotalAmount: line.qups.subtotal.toJSON().amount, taxRatePercent: tax?.ratePercent, taxMode: tax?.mode, taxAmount: line.tax.tax.toJSON().amount, netAmount: line.tax.net.toJSON().amount, grossAmount: line.tax.gross.toJSON().amount, modifiers: modifiersToRecords(line.adjusted.modifiers, options.idFactory), fieldValues: options.fieldValues ?? [], position: options.position, createdAt: options.createdAt, updatedAt: options.updatedAt }; } function taxOpts(line) { if (!line.tax.ratePercent) return void 0; if (line.tax.truth === "gross+rate") { return { ratePercent: line.tax.ratePercent, mode: "inclusive" }; } return { ratePercent: line.tax.ratePercent, mode: "exclusive" }; } function pricingLineInputFromParts(input) { let qups; if (input.truth === "quantity+unitPrice") { if (input.quantity == null || input.unitPrice == null) { throw new Error("quantity+unitPrice requires quantity and unitPrice"); } qups = { truth: "quantity+unitPrice", quantity: input.quantity, unitPrice: Money5.of(input.unitPrice, input.currency) }; } else if (input.truth === "quantity+subtotal") { if (input.quantity == null || input.subtotal == null) { throw new Error("quantity+subtotal requires quantity and subtotal"); } qups = { truth: "quantity+subtotal", quantity: input.quantity, subtotal: Money5.of(input.subtotal, input.currency) }; } else { if (input.unitPrice == null || input.subtotal == null) { throw new Error("unitPrice+subtotal requires unitPrice and subtotal"); } qups = { truth: "unitPrice+subtotal", unitPrice: Money5.of(input.unitPrice, input.currency), subtotal: Money5.of(input.subtotal, input.currency) }; } return { qups, modifiers: input.modifiers, tax: input.tax ? input.tax.mode === "inclusive" ? { ratePercent: input.tax.ratePercent, mode: "inclusive" } : { ratePercent: input.tax.ratePercent, mode: "exclusive" } : void 0 }; } function lineFieldMap(record) { const map = { quantity: { value: record.quantity }, unit_price: { value: record.unitPriceAmount, currency: record.currency }, subtotal: { value: record.subtotalAmount, currency: record.currency } }; if (record.taxRatePercent != null) { map.tax = { value: record.taxRatePercent }; } if (record.taxAmount != null) { map.tax_amount = { value: record.taxAmount, currency: record.currency }; } if (record.netAmount != null) { map.net = { value: record.netAmount, currency: record.currency }; } if (record.grossAmount != null) { map.gross = { value: record.grossAmount, currency: record.currency }; map.total = { value: record.grossAmount, currency: record.currency }; } for (const fv of record.fieldValues) { map[fv.fieldKey] = { value: fv.value, currency: fv.currency }; } return map; } // src/core/create-qups.ts import { entityIdFactory } from "@eristack/entity-id"; function attachFieldIds(profileId, seeds, idFactory) { return seeds.map((f) => ({ ...f, id: idFactory(), profileId })); } function createQups(options = {}) { const clock = options.clock ?? (() => /* @__PURE__ */ new Date()); const idFactory = options.idFactory ?? entityIdFactory; const profiles = options.profiles; const lines = options.lines; function requireProfiles() { if (!profiles) { throw new MissingDependencyError("profiles (PricingProfileStore)"); } return profiles; } function requireLines() { if (!lines) throw new MissingDependencyError("lines (PricingLineStore)"); return lines; } async function deactivateSiblings(entityKey, exceptId) { const store = requireProfiles(); const siblings = await store.listByEntityKey(entityKey); const now = clock(); await Promise.all( siblings.filter((p) => p.id !== exceptId && p.active).map( (p) => store.save({ ...p, active: false, updatedAt: now }) ) ); } return { async registerProfile(input) { const store = requireProfiles(); const now = clock(); const truth = input.defaultTruth ?? "quantity+unitPrice"; const profileId = input.id ?? idFactory(); const seeds = input.fields?.length ? syncFieldRoles(input.fields, truth) : fieldsForTruth(truth); const record = { id: profileId, entityKey: input.entityKey, defaultTruth: truth, defaultCurrencyCode: input.defaultCurrencyCode, fields: attachFieldIds(profileId, seeds, idFactory), defaultTaxRatePercent: input.defaultTaxRatePercent, defaultTaxMode: input.defaultTaxMode, allowedModifierKinds: input.allowedModifierKinds, active: input.activate !== false, createdAt: now, updatedAt: now }; if (record.active) { await deactivateSiblings(record.entityKey, record.id); } await store.save(record); return record; }, async updateProfile(input) { const store = requireProfiles(); const existing = await store.findById(input.id); if (!existing) throw new ProfileNotFoundError(input.id); const truth = input.defaultTruth ?? existing.defaultTruth; let fields = existing.fields; if (input.fields) { fields = attachFieldIds( existing.id, syncFieldRoles(input.fields, truth), idFactory ); } else if (input.defaultTruth) { fields = attachFieldIds( existing.id, syncFieldRoles( existing.fields.map(({ id: _id, profileId: _p, ...rest }) => rest), truth ), idFactory ); } const now = clock(); const next = { ...existing, defaultTruth: truth, defaultCurrencyCode: input.defaultCurrencyCode ?? existing.defaultCurrencyCode, fields, defaultTaxRatePercent: input.defaultTaxRatePercent === null ? void 0 : input.defaultTaxRatePercent ?? existing.defaultTaxRatePercent, defaultTaxMode: input.defaultTaxMode === null ? void 0 : input.defaultTaxMode ?? existing.defaultTaxMode, allowedModifierKinds: input.allowedModifierKinds === null ? void 0 : input.allowedModifierKinds ?? existing.allowedModifierKinds, active: input.active ?? existing.active, updatedAt: now }; if (next.active) { await deactivateSiblings(next.entityKey, next.id); } await store.save(next); return next; }, async getProfile(entityKey) { return requireProfiles().findActiveByEntityKey(entityKey); }, async getProfileById(id) { return requireProfiles().findById(id); }, async listProfiles(entityKey) { return requireProfiles().listByEntityKey(entityKey); }, async saveLine(input) { const store = requireLines(); const now = clock(); const existing = input.id ? await store.findById(input.id) : null; let line; if (input.line) { line = input.line; } else { const currency = input.currency ?? existing?.currency ?? (() => { throw new Error("currency is required when line is omitted"); })(); const truth = input.truth ?? existing?.truth ?? "quantity+unitPrice"; line = PricingLine.of( pricingLineInputFromParts({ truth, currency, quantity: input.quantity ?? existing?.quantity, unitPrice: input.unitPrice ?? existing?.unitPriceAmount, subtotal: input.subtotal ?? existing?.subtotalAmount, modifiers: input.modifiers ?? (existing ? pricingLineFromRecord(existing).adjusted.modifiers : []), tax: input.tax ?? (existing?.taxRatePercent ? { ratePercent: existing.taxRatePercent, mode: existing.taxMode } : void 0) }) ); } const record = recordFromPricingLine({ id: input.id ?? existing?.id ?? idFactory(), ownerKey: input.ownerKey, line, profileId: input.profileId ?? existing?.profileId, fieldValues: input.fieldValues ?? existing?.fieldValues ?? [], position: input.position ?? existing?.position, createdAt: existing?.createdAt ?? now, updatedAt: now, idFactory }); record.rowExtras = input.rowExtras ?? existing?.rowExtras; await store.save(record); return record; }, async getLine(id) { return requireLines().findById(id); }, async listLines(ownerKey) { return requireLines().listByOwnerKey(ownerKey); }, async deleteLine(id) { const store = requireLines(); const existing = await store.findById(id); if (!existing) throw new LineNotFoundError(id); await store.delete(id); }, hydrateLine(record) { return pricingLineFromRecord(record); }, lineFields(record) { return lineFieldMap(record); }, fieldsFor(truth, profile) { if (!profile) return fieldsForTruth(truth); return syncFieldRoles( profile.fields.map(({ id: _i, profileId: _p, ...rest }) => rest), truth ); }, editableKeys: editableFieldKeys }; } export { QUPS_TRUTH_MODES, isQupsTruthMode, QupsError, InvalidTruthError, CurrencyMismatchError, MissingDependencyError, ProfileNotFoundError, LineNotFoundError, Qups, AdjustedAmount, LineTax, PricingLine, qupsRolesFor, isBuiltinFieldKey, fieldsForTruth, syncFieldRoles, editableFieldKeys, moneyColumnPair, calculateLine, patchLine, withQupsColumns, modifiersToRecords, recordsToModifiers, pricingLineFromRecord, recordFromPricingLine, pricingLineInputFromParts, lineFieldMap, createQups }; //# sourceMappingURL=chunk-UP24CFOV.js.map