ADR-0006: Order profit is a rebuilt projection
Status
Accepted. The table is in 57-profitability.prisma, created by migration 20261019120000_add_order_item_profit.
Context
Sellers need each order's profit after marketplace fees, cost of goods, freight and returns. Every input already exists elsewhere: payout lines and their resolutions (ADR-0005), the order, shipments with freight audits, return lines, and the product's cost price. Lists sorted and filtered by margin over months of orders cannot be aggregated live from partitioned payout lines on every request. Product.costPrice is a single mutable number, so computing with today's cost would rewrite every past margin whenever someone corrects it.
Decision
OrderItemProfitstores one row per channel order line. It is a projection:OrderItemProfitServicerebuilds a whole order from source facts, and nothing else writes the table.- The one value carried across rebuilds is the unit cost captured when the line became billable. A later cost edit fills only rows still missing a cost. Changing captured costs is an explicit reprice from a date.
- Rebuilds are requested, not computed inline. Settlement reconciliation queues a job after it reconciles, through a constant in
src/app/constants, so settlement never imports profitability. - A rebuild of an order holds a transaction-scoped advisory lock, so concurrent triggers serialise. An unchanged
inputsHashskips the write. - The table is created with the columns later phases need (estimates, allocated period costs, purchase-order and direct channels), so those phases add no migration.
- Fee columns are named for the kind of fee, not a channel's term. Parsers map each channel's fees to
PayoutLineCategory, including a newFEE_TAXfor GST charged on fees.
Alternatives
- Computing profit live from payout lines on each request. Rejected: sorting by margin needs indexed columns.
- A dated cost-history table. Not adopted for Phase 1: storing the cost on the row covers the "an edit must not rewrite history" need with one table fewer.
Consequences
- Any change that moves profit must reach a rebuild: through reconciliation, the product cost event, or the nightly sweep, which also catches lost requests.
- Changing a formula means bumping
PROFIT_COMPUTE_VERSION; the sweep rebuilds older rows. - Profit columns use magnitudes, unlike
PayoutLine's signed amounts. Readers of both must not mix the conventions. - Raw SQL reads must filter on the tenant themselves: the Prisma tenancy extension does not reach them.