@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,585 lines (1,565 loc) • 48.9 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/backseat/index.ts
var backseat_exports = {};
__export(backseat_exports, {
QUPS_COLLECTIONS: () => QUPS_COLLECTIONS,
createBackseatPricingLineStore: () => createBackseatPricingLineStore,
createBackseatPricingProfileStore: () => createBackseatPricingProfileStore,
createBackseatQupsStores: () => createBackseatQupsStores,
registerQupsBackseat: () => registerQupsBackseat
});
module.exports = __toCommonJS(backseat_exports);
var import_testing = require("@eristack/backseat/testing");
// src/backseat/stores.ts
var import_adapters = require("@eristack/backseat/adapters");
// src/backseat/collections.ts
var QUPS_COLLECTIONS = {
profiles: "qups.profiles",
lines: "qups.lines"
};
// src/backseat/stores.ts
function profileFromDoc(doc) {
return {
id: String(doc.id),
entityKey: String(doc.entityKey),
defaultTruth: String(doc.defaultTruth),
defaultCurrencyCode: String(doc.defaultCurrencyCode),
fields: Array.isArray(doc.fields) ? doc.fields : [],
defaultTaxRatePercent: doc.defaultTaxRatePercent == null ? void 0 : String(doc.defaultTaxRatePercent),
defaultTaxMode: doc.defaultTaxMode == null ? void 0 : String(doc.defaultTaxMode),
allowedModifierKinds: Array.isArray(doc.allowedModifierKinds) ? doc.allowedModifierKinds : void 0,
active: Boolean(doc.active),
createdAt: (0, import_adapters.asDate)(doc.createdAt),
updatedAt: (0, import_adapters.asDate)(doc.updatedAt)
};
}
function profileToDoc(record) {
return {
id: record.id,
entityKey: record.entityKey,
defaultTruth: record.defaultTruth,
defaultCurrencyCode: record.defaultCurrencyCode,
fields: record.fields,
defaultTaxRatePercent: record.defaultTaxRatePercent ?? null,
defaultTaxMode: record.defaultTaxMode ?? null,
allowedModifierKinds: record.allowedModifierKinds ?? null,
active: record.active,
createdAt: record.createdAt.toISOString(),
updatedAt: record.updatedAt.toISOString()
};
}
function createBackseatPricingProfileStore(store, options = {}) {
const collection = options.collection ?? QUPS_COLLECTIONS.profiles;
async function allProfiles() {
const docs = await store.list(collection);
return docs.map(profileFromDoc);
}
return {
async save(record) {
const doc = profileToDoc(record);
const existing = await store.get(collection, record.id);
if (existing) {
await store.update(collection, record.id, doc);
return;
}
await store.create(collection, doc);
},
async findById(id) {
const doc = await store.get(collection, id);
return doc ? profileFromDoc(doc) : null;
},
async findActiveByEntityKey(entityKey) {
const matches = (await allProfiles()).filter((row) => row.entityKey === entityKey && row.active).sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
return matches[0] ?? null;
},
async listByEntityKey(entityKey) {
return (await allProfiles()).filter((row) => row.entityKey === entityKey).sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
}
};
}
function lineFromDoc(doc) {
return {
id: String(doc.id),
ownerKey: String(doc.ownerKey),
profileId: doc.profileId == null ? void 0 : String(doc.profileId),
truth: String(doc.truth),
quantity: String(doc.quantity),
quantityRatioNumerator: doc.quantityRatioNumerator == null ? void 0 : String(doc.quantityRatioNumerator),
quantityRatioDenominator: doc.quantityRatioDenominator == null ? void 0 : String(doc.quantityRatioDenominator),
currency: String(doc.currency),
unitPriceAmount: String(doc.unitPriceAmount),
subtotalAmount: String(doc.subtotalAmount),
taxRatePercent: doc.taxRatePercent == null ? void 0 : String(doc.taxRatePercent),
taxMode: doc.taxMode == null ? void 0 : String(doc.taxMode),
taxAmount: doc.taxAmount == null ? void 0 : String(doc.taxAmount),
netAmount: doc.netAmount == null ? void 0 : String(doc.netAmount),
grossAmount: doc.grossAmount == null ? void 0 : String(doc.grossAmount),
modifiers: Array.isArray(doc.modifiers) ? doc.modifiers : [],
fieldValues: Array.isArray(doc.fieldValues) ? doc.fieldValues : [],
rowExtras: doc.rowExtras && typeof doc.rowExtras === "object" ? doc.rowExtras : void 0,
position: doc.position == null ? void 0 : Number(doc.position),
createdAt: (0, import_adapters.asDate)(doc.createdAt),
updatedAt: (0, import_adapters.asDate)(doc.updatedAt)
};
}
function lineToDoc(record) {
return {
id: record.id,
ownerKey: record.ownerKey,
profileId: record.profileId ?? null,
truth: record.truth,
quantity: record.quantity,
quantityRatioNumerator: record.quantityRatioNumerator ?? null,
quantityRatioDenominator: record.quantityRatioDenominator ?? null,
currency: record.currency,
unitPriceAmount: record.unitPriceAmount,
subtotalAmount: record.subtotalAmount,
taxRatePercent: record.taxRatePercent ?? null,
taxMode: record.taxMode ?? null,
taxAmount: record.taxAmount ?? null,
netAmount: record.netAmount ?? null,
grossAmount: record.grossAmount ?? null,
modifiers: record.modifiers,
fieldValues: record.fieldValues,
rowExtras: record.rowExtras ?? null,
position: record.position ?? null,
createdAt: record.createdAt.toISOString(),
updatedAt: record.updatedAt.toISOString()
};
}
function createBackseatPricingLineStore(store, options = {}) {
const collection = options.collection ?? QUPS_COLLECTIONS.lines;
async function allLines() {
const docs = await store.list(collection);
return docs.map(lineFromDoc);
}
return {
async save(record) {
const doc = lineToDoc(record);
const existing = await store.get(collection, record.id);
if (existing) {
await store.update(collection, record.id, doc);
return;
}
await store.create(collection, doc);
},
async findById(id) {
const doc = await store.get(collection, id);
return doc ? lineFromDoc(doc) : null;
},
async listByOwnerKey(ownerKey) {
return (await allLines()).filter((row) => row.ownerKey === ownerKey);
},
async delete(id) {
const existing = await store.get(collection, id);
if (existing) await store.delete(collection, id);
}
};
}
// src/backseat/register.ts
var import_adapters3 = require("@eristack/backseat/adapters");
// src/core/calculate.ts
var import_money4 = require("@eristack/money");
// src/core/line.ts
var import_money3 = require("@eristack/money");
// src/core/modifier.ts
var import_money = require("@eristack/money");
// 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/modifier.ts
function applyOne(running, spec) {
if (spec.type === "percent") {
if (spec.kind === "discount") {
const next3 = running.with(import_money.Discount.ofPercent(spec.percent));
return { amount: running.subtract(next3), next: next3 };
}
const next2 = running.with(import_money.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 = import_money.Money.of("100", running.currency).subtract(import_money.Money.of(spec.percent, running.currency)).divide("100").getNumber().toString();
running = running.divide(factor);
} else {
const factor = import_money.Money.of("100", running.currency).add(import_money.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 = import_money.Money.zero(base.currency);
let surchargeTotal = import_money.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 = import_money.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/qups.ts
var import_decimal = __toESM(require("decimal.js"), 1);
var QtyDecimal = import_decimal.default.clone({
precision: 40,
rounding: import_decimal.default.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/tax.ts
var import_money2 = require("@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(import_money2.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(import_money2.Tax.netFromInclusive(input.ratePercent));
const tax = input.gross.with(import_money2.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 = import_money2.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
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: import_money3.Money.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 = import_money3.Rounding.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" };
}
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);
}
// src/core/calculate.ts
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: import_money4.Money.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: import_money4.Money.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: import_money4.Money.of(input.unitPrice, currency),
subtotal: import_money4.Money.of(input.subtotal, currency)
},
modifiers: mapModifiers(input.modifiers, currency),
tax: taxInput(input)
});
}
return input.round ? line.withRounding(import_money4.Rounding.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: import_money4.Money.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 = import_money4.Money.of(patch.unitPrice, currency);
}
if (patch.subtotal !== void 0) {
editPatch.subtotal = import_money4.Money.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
});
}
// src/core/stores/serialize.ts
var import_money5 = require("@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: import_money5.Money.of(m.amount ?? "0", m.currency || fallbackCurrency)
};
});
}
function qupsInputFromRecord(record) {
const unitPrice = import_money5.Money.of(record.unitPriceAmount, record.currency);
const subtotal = import_money5.Money.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: import_money5.Money.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: import_money5.Money.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: import_money5.Money.of(input.unitPrice, input.currency),
subtotal: import_money5.Money.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
var import_entity_id = require("@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 ?? import_entity_id.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
};
}
// src/backseat/qups-routes.ts
var import_adapters2 = require("@eristack/backseat/adapters");
function createQupsRoutes(qups) {
return [
{
method: "POST",
segment: "/calculate-line",
name: "qups.calculate-line",
handler: async (ctx) => ({
status: 200,
body: calculateLine(ctx.json())
})
},
{
method: "POST",
segment: "/patch-line",
name: "qups.patch-line",
handler: async (ctx) => {
const body = ctx.json();
return { status: 200, body: patchLine(body.current, body.patch) };
}
},
{
method: "GET",
segment: "/lines/:ownerKey",
name: "qups.list-lines",
handler: async (ctx) => {
const ownerKey = (0, import_adapters2.requireParam)(ctx.params.ownerKey, "ownerKey required");
if (typeof ownerKey !== "string") return ownerKey;
return { status: 200, body: await qups.listLines(ownerKey) };
}
}
];
}
// src/backseat/register.ts
function registerQupsBackseat(api, options = {}) {
const profiles = options.profiles ?? createBackseatPricingProfileStore(api.store);
const lines = options.lines ?? createBackseatPricingLineStore(api.store);
const qups = options.qups ?? createQups({
profiles,
lines,
clock: options.clock,
idFactory: options.idFactory
});
(0, import_adapters3.registerMountedRoutes)(api, options.basePath ?? "/qups", createQupsRoutes(qups));
api.registerAction(
"qups.calculateLine",
async ({ input }) => calculateLine(input)
);
return qups;
}
// src/backseat/index.ts
function createBackseatQupsStores(options = {}) {
const backseatStore = options.store ?? (0, import_testing.createMemoryBackseatStore)();
return {
backseatStore,
profiles: createBackseatPricingProfileStore(backseatStore),
lines: createBackseatPricingLineStore(backseatStore)
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
QUPS_COLLECTIONS,
createBackseatPricingLineStore,
createBackseatPricingProfileStore,
createBackseatQupsStores,
registerQupsBackseat
});
//# sourceMappingURL=index.cjs.map