Pricing engine internals
The PricingStageContract stage order, exact arithmetic and rounding, rule revisions and bindings, provenance, base-rate and rental previews, accepted pricing manifests and preview concurrency.
Overview
This is the engine reference behind Pricing & Discounts. Signals applies pricing through an eleven-stage pipeline. Stages run in the versioned order published by PricingStageContract; each stage receives the output of the preceding one. Current calculations run strategy and modifiers before the matching tier. Pricing replay uses the arithmetic order recorded by each event. Rental totals recalculate when lines, dates, discount groups, bundles, surcharges, or agreed prices change.
Pipeline stages
| Order | Stage | What it does |
|---|---|---|
| 1 | Context and rate resolution | Resolves tenant, warehouse, account, currency, date, and a valid pinned or current rate revision. |
| 2 | Rate strategy and modifiers | Runs the selected versioned strategy and ordered modifiers. |
| 3 | Rate-band tier | Applies the matching versioned tier multiplier. |
| 4 | Quantity and duration | Multiplies the completed, tier-adjusted strategy result by exact decimal quantity; strategy already includes chargeable duration. |
| 5 | Bundle adjustment | Applies eligible fixed or percentage bundles before line discounts. |
| 6 | Group or manual discount | Uses the highest eligible discount, limited by the global line-discount cap. |
| 7 | Proportional deal discount | Applies the separately authorised proportional deal adjustment. |
| 8 | Inclusive-tax extraction | Converts tax-inclusive input to the stored net amount. |
| 9 | Surcharge evaluation | Applies eligible fixed and percentage surcharges to the post-discount net. |
| 10 | Flat deal headline | Replaces the document net headline when that deal mode is active. |
| 11 | Tax and document rollup | Groups tax once, reconciles allocations, and persists the document totals. |
Rounding strategy
PricingSettings controls rounding: half-up (default) or banker's rounding (round half to even). Applied at each declared minor-unit boundary, including tier adjustment, quantity subtotal, discount amount, bundle discount amount, and surcharge amount. Tax and allocation have their own boundaries described below.
All supported stored and intermediate amounts are checked against the signed 32-bit non-negative minor-unit range before persistence. Calculations use decimal strings and BCMath; quantity, duration, multipliers, bundles, discounts, surcharges, tax, allocation residuals, and document sums do not pass through floating-point arithmetic.
Rule revisions and manual decisions
Rate-band tiers, discount rules, surcharge groups and definitions, and bundle rules have stable logical UUIDs and immutable content-addressed revisions. An edit publishes a new revision; it does not rewrite prior evidence. Draft revisions are not visible to live pricing.
Manual line discounts and surcharge decisions use an explicit rule_binding:
| Binding | Behaviour |
|---|---|
pinned |
Keeps the captured logical rule and revision until an authorised user changes the decision. |
follow |
Keeps the logical rule identity and refreshes its revision evidence when a later revision becomes current. |
REST rental-line responses expose discount logical ID, revision ID, and binding. Loaded surcharge decisions expose the same information under each line's surcharges list. MCP get-rental returns the same REST contract. The surcharge override endpoint accepts rule_binding; rental-line discount updates accept it with discount_percent.
Time and provenance
Rate, discount, surcharge, and bundle validity boundaries are inclusive. Null means unbounded. Rate dates are evaluated as business dates in the selected warehouse timezone; timestamp rules use the shared instant policy. An inverted interval is rejected by actions and by PostgreSQL constraints.
RentalTotalsCalculator::repriceRental() returns an immutable RentalPricingResult. Every canonical stage returns evidence containing its line/document key, applied or excluded status, logical rule and revision where relevant, input base, canonical formula/config hash, exact unrounded result, rounding mode, rounded amount, and explicit exclusion reason. This result is the input to the calculation manifest introduced at commercial acceptance; it is not itself a mutable operator waterfall.
Rule revision backfill commands are in Finance operations → Pricing commands.
Base-rate and full-rental previews
POST /api/v1/catalogue_items/{catalogue_item}/calculate_rate and MCP calculate-rate apply the selected strategy, duration, modifiers and exact requested quantity. Their response uses preview_scope=base_rate; price_status is resolved, unresolved or missing_source_precision. Missing original precision yields null formatted money, not a free price. They exclude rental tier adjustment, bundles, discounts, surcharges, tax, costs and document rollup. Use the full rental preview for acceptance. See the OpenAPI reference.
For a complete document calculation, use the authorised rental preview. GET /api/v1/rentals/{rental}/pricing_preview uses the rental's stored context. POST to the same path may preview an account, rate band/tier, ISO currency, and per-line decimal quantities without saving any of them. It may also carry expected_version and accepted_manifest_hash so a stale client fails before calculation. The preview clones the rental calculation state and runs the normal pricing pipeline in memory; it does not write rows, events, totals, or cache state. For accepted terms, the preview clone calculates tax from the proposed successor amounts rather than reusing the order’s locked tax total. The persisted tax lock, current manifest and previously issued invoices stay unchanged until an authorised rebase publishes the successor terms.
Every priceable line is labelled resolved, manual, intentional_zero, or unresolved. Quote acceptance and pricing rebase fail when any priceable line is unresolved. A manual zero is allowed only when it was explicitly set as a manual price.
Accepted pricing manifests
Accepting a quote version publishes an immutable, content-addressed pricing manifest. The manifest freezes the selected rule and rate revisions, quantities and dates, currency and rounding rules, exact line and document projections, invoice handoff values, price-book generation, aggregate version, and safe historical labels. Each later manifest links to the preceding revision and records an explicit commercial diff. Acceptance requires recorded original source and base money units before calculation; missing facts return HTTP 422 rental.pricing.original_money_units_missing without writing or inferring current currency precision. Shared-document approval refuses with rental_document_precision_missing when original document precision is absent.
Full projection replay restores accepted and rebased amounts from their stored manifest-bearing events, even after source revisions change or a captured extension becomes unavailable. Prior pricing events defer only to a later stored event for the same rental with valid manifest schema, hash and identity. Scoped rebuilds use only events in their selected stream; a later projection row or an event outside that stream grants no authority. Manifestless histories retain their existing repricing behavior. Live previews and acceptance still require the configured pricing providers.
Initial acceptance, latest-term preview and explicit rebase record the immutable revision of the rate actually resolved for that calculation. A resolved rate without a published revision makes the line unresolved and prevents acceptance or rebase. Later quote-version amendments retain copied lines' captured terms, and previously accepted manifests keep their frozen evidence.
Manifests are immutable: the application refuses to change them (there is no database trigger). Clearing demo data can remove a demo rental and its manifests; it never deletes manifests for ordinary rentals.
Accepted reads also require the stored price-book generation, money exponent, rounding mode, business and publication times, and aggregate version to match the captured manifest context. A mismatch is invalid evidence and uses the existing accepted_terms_locked refusal before pricing or invoice snapshotting; verification does not rewrite the manifest. Direct pricing previews apply the same guard after locking the rental, before reading the accepted baseline or calculating proposed terms.
Manifest publication and projection reject unsupported values, non-serialisable JSON and excessive payload depth with HTTP 422 rental.pricing.manifest_payload_invalid before any projection or manifest write. The refusal retains the codec's specific diagnostic; valid captured envelopes retain their existing publication and projection behaviour.
An accepted quote version cannot be edited commercially in place — see Pricing & Discounts → Accepted quotes, recalculation and rebase for the operator view and the Recalculate, Preview latest and Rebase latest permissions.
Within that new quote version, copied lines retain captured rate/specification, tier, effective discount, rounding, surcharge, tax and FX facts. Quantity changes scale the captured per-unit bundle adjustment; adding or removing another line does not redistribute it across untouched lines. New automatic lines capture a published approved rate and commercial facts before their item event is stored or fired. Missing or unpublished rates refuse with rental.pricing.amendment_rate_required before writes; explicit manual prices, including zero, remain manual. Later publication changes and replay preserve these captured facts. Draft edits create no provisional manifest. Acceptance publishes the next immutable revision with added, removed and changed lines identified against original accepted identities; an untouched clone is omitted from the commercial diff.
Locked calculations retain the accepted manifest's rate identities and amounts even when current catalogue definitions change or are archived. Missing or corrupt retained evidence refuses calculation; it never selects a replacement live rate. Credit exposure reports incomplete evidence rather than treating it as zero. A manually locked or prior document without a manifest returns rental.pricing.invalid_locked_rate when its stored or requested pin is invalid, before pricing writes. A valid pinned rate that is republished remains the provenance for stored snapshots, invoices, document merges, and credit exposure; these consumers preserve stored amounts and the recorded revision without applying the new price. Quantity changes, recalculation, and pricing previews refuse revision drift when they would reprice a manifest-less locked document. Unlocked drafts retain their current-rate fallback.
The rate breakdown panel is unavailable for locked or accepted terms and leaves stored document amounts unchanged. An authorised latest-book preview keeps the accepted before amount separate from its current comparison. A comparison that falls back to stored amounts without a published rate is labelled unresolved and cannot be accepted or rebased.
API routes:
GET /api/v1/rentals/{rental}/pricing_previewPOST /api/v1/rentals/{rental}/pricing_previewPOST /api/v1/rentals/{rental}/pricing_rebase
Use POST for contextual what-if input. Its response uses preview_scope=full_rental, includes preview_context, and returns an acceptance assessment with per-line status and blockers.
Both rental preview routes are read-only. The POST preview neither requires an HTTP Idempotency-Key header nor records a response receipt, even when strict API key enforcement is enabled. Supplying or repeating a key does not change that behavior. Recalculate, rebase, and other mutating POST routes retain normal HTTP idempotency handling.
Accepted recalculation is idempotent in its pricing projection: each explicit call restores the same manifest values and records one recalculation event, one audit entry, and one aggregate version increment. The generic rental.pricing_recalculated event distinguishes accepted_terms_recomputation, rebase, and permitted_net_override through mutation_class; webhook, plugin, and workflow payloads also expose pricing_manifest_hash. Recalculation's optional event actor, reason, and key remain null; its audit identifies the acting user.
Stable rebase error codes include rental.pricing.stale_preview, rental.pricing.stale_price_book, rental.pricing.idempotency_conflict, rental.pricing.evidence_disposition_required, and rental.pricing.evidence_disposition_not_applicable. Partial or unrecoverable prior evidence requires evidence_disposition=adopt_current_terms_as_new_baseline.
An exact idempotent rebase retry rechecks current permission, warehouse access, closed-rental status, and applicable guard rules before returning its stored manifest. Revoked permission or warehouse access refuses the retry; hidden rentals retain the transport's redacted not-found response. A completed or cancelled rental also refuses replay. A permitted retry returns the original result without another manifest, pricing event, audit, or version advance. Direct action calls validate the same input rules after authorization.
Manifest verification and repair (signals:pricing-manifests:verify) is an operator command, described in Finance operations → Pricing commands.
Existing line amount, rate, tier, surcharge, FX-lock, and tax-lock fields remain additive contract fields throughout v1.x.
Missing stored surcharge names or types give a coded refusal in dry run and apply; today's definition is never substituted. Nullable percentage, fixed-value and currency snapshots remain nullable when the stored name, type and observed amount can support valid partial evidence, including a known zero amount. Apply validates the persisted evidence inside the same transaction and rolls back the manifest and accepted pointers if validation fails. Capture reads stored amounts only; the subsequent validator may read source identities and immutable revisions to verify their references, without repricing or filling missing terms. A refused rental keeps its prior invoiceability and commercial rows.
Pricing preview concurrency
The preview's line_changes include adjustments_before and adjustments_after as nullable integer amounts in minor currency units. The before and after document totals use the shared net, tax, gross, agreed and by_kind shape.
Rental pricing previews return the document version, preview hash and price-book generation without changing stored pricing or dispatching work. Rebase requires both version and generation pins; missing pins return rental_pricing_precondition_required with HTTP 422 and field errors. Review a fresh preview after a stale refusal. Repeating the same accepted request returns its original manifest without another acceptance; an issued invoice keeps its frozen snapshot after subsequent pricing changes.