Profitability (order P&L)
Overview
Profitability answers: what did this order earn after marketplace fees, cost of goods, freight and returns?
It is a projection over the settlements spine. Nothing in it is a source of truth: every OrderItemProfit row is rebuilt from payout lines, the order, its shipments and its returns. The only value a rebuild keeps is the unit cost captured when the line became billable, so editing a product's cost never rewrites a margin already reported unless someone asks.
Phase 1 covers settled orders on marketplaces that settle through reports (Amazon, Flipkart, Meesho), self-shipped and channel-shipped (Easy Ship). Rows are also built for FBA orders, but the API leaves them out unless asked: FBA returns and reimbursements are not covered yet.
Data model
One table, 57-profitability.prisma, migration 20261019120000_add_order_item_profit.
OrderItemProfit has one row per channel order line, keyed by orderItemId. Bundle component lines roll into their parent line.
| Group | Columns |
|---|---|
| Keys | orderId, rollupOrderId (the original order, for replacements), channelId, legalEntityId, warehouseId, productId, sku, orderDate, orderDay (workspace-local), fulfilmentMode, commercialModel |
| Lifecycle | stage, gaps[], dispatchedAt, deliveredAt, settledAt |
| Revenue (ex-GST) | productSales, shippingIncome, giftWrapIncome, otherIncome, promotions, netRevenue |
| Fees | commissionFee, fixedFee, collectionFee, logisticsFee, fulfilmentFee, penaltyFee, otherFees |
| Cost | unitCost, costSource, costCapturedAt, cogs, freight, freightSource |
| Returns | refunds, feesRefunded, reverseLogisticsFee, reverseFreight, cogsRecovered, reimbursements |
| Results | channelFees, returnCost, cm1, cm2 (the UI's "Profit"), cm3, marginPct, roiPct |
| Cash, not profit | outputTax, feeTax, tcs, tds, netPayout |
| Bookkeeping | inputsHash, computeVersion, computedAt |
Columns for later phases exist already and keep their defaults: fee estimates (estimatedChannelFees, feeVariance), allocated period costs (allocatedAdvertising, allocatedStorage, allocatedOverhead), packagingCost, codCharges, gatewayFee.
Money convention: income is positive, costs are positive magnitudes, and only the results (cm1, cm2, cm3) are signed. PayoutLine uses one signed amount instead.
Formulas:
netRevenue= sales + shipping + gift wrap + other income − seller-funded promotionscm1=netRevenue− forward fees −cogs−freight−gatewayFeereturnCost=refunds−feesRefunded+reverseLogisticsFee+reverseFreight−cogsRecoveredcm2=cm1−returnCost+reimbursementscm3=cm2(no period costs are allocated yet)
The table has the same row-level security policy as every tenant table. A row cascades away with its order line, order or product: it is a projection, never a reason to block a delete, and the sweep rebuilds what is still billable.
How a row is built
computeOrderProfit in order-item-profit.calculator.ts is pure and holds every rule:
- Lines read: current payout lines resolved to the order (
supersededByIdnull). Each takes the confirmedcategoryOverrideif there is one, else its own category. Courier COD lines are ignored: that cash is the buyer paying, not profit. - Order-level lines (no order item) are split across items by item value, or by quantity when every item is free.
- Refund lines: a fee line on a refund is the fee being given back (
feesRefunded), not a negative forward fee. - Cost: a captured cost is kept. A row without one takes
Product.costPricenow (PRODUCT_COST), or the sum of bundle components (BUNDLE). Rows created by the first-fill sweep recordSWEEP. A zero cost counts as missing: the row getsCOST_MISSINGand no margin, never a 100% margin. - Quantity shipped: an order shipped outside PointNXT (Easy Ship from Seller Central, FBA) has no
quantityShipped, so a billable status counts the ordered units, less cancelled ones. - Freight: self-shipped orders only. The courier invoice (
ShipmentFreightAudit.billedAmount) is used, else the booking quote (Shipment.shippingCharges, gapFREIGHT_QUOTED). Channel-shipped and FBA freight is inside the channel's fee (FreightSource.CHANNEL). - Returns: a refunded unit's cost stays a loss until a return is received. Sellable units recover their cost; refurbishable ones recover 50%. A refund with no return received sets
RETURN_NOT_RECEIVED. Amazon customer returns are not synced into PointNXT, so this is the usual case for them. - Replacements:
rollupOrderIdis the replaced order, so a replacement's cost and freight count against the original sale. Amazon ingestion setsOrder.replacementOrderIdonce the original is synced. - Stage:
SETTLEDonce a sale line is in a payout, elseAWAITING_SETTLEMENT. Awaiting rows are listed but left out of the KPIs.
Triggers
A rebuild is full and idempotent. A row whose inputsHash is unchanged is not rewritten, only its computedAt is touched.
| Trigger | Path |
|---|---|
| Anything reconciliation sees: a payout line import (API or file, every channel), an order status change (dispatch, delivery, return, cancellation), a manual line link, a category override | SettlementReconciliationService.recomputeChunk queues an order-profit-recompute job per tenant on the profitability_queue |
| A product's cost changes | product.cost.changed local event → ProductCostListener queues orders still missing a cost |
| A user reprices a product from a date | POST /finance/profitability/costs/reprice releases the captured cost of matching rows and queues them |
| Nightly, 03:30 | OrderProfitScheduler gives rows to billable orders with none (first fill), then rebuilds rows that are awaiting settlement, have a gap, have no cost, or were written by an older PROFIT_COMPUTE_VERSION, and rows built before a change that does not pass through reconciliation: a return line graded later, a courier invoice imported later, a replacement linked to its original later |
| A product merge | ProductMergeService moves the rows to the retained product with the order lines, keeping their captured cost |
Settlement does not import profitability. The job name and payload live in src/app/constants/profitability-queue.constant.ts. Profitability reads settlement's vocabulary, never the other way round.
Rebuilds of the same order never run at once: withOrderLocks takes a transaction-scoped advisory lock per order, sorted so overlapping sets cannot deadlock. Jobs carry no job id, so a rebuild requested while another runs is still processed afterwards.
Fee categories
P&L columns are named for the kind of fee, not one channel's term. Each parser maps its channel's fees to PayoutLineCategory:
| Column | Categories | Amazon | Flipkart | Meesho |
|---|---|---|---|---|
commissionFee | COMMISSION | Referral fee | Commission | Commission |
fixedFee | CLOSING_FEE | Closing fee | Fixed fee | Fixed fee |
collectionFee | COLLECTION_FEE | — | Collection fee | — |
logisticsFee | SHIPPING_FEE | Easy Ship, weight handling | Shipping fee (negative shipping) | Shipping fee |
fulfilmentFee | FULFILMENT_FEE | FBA fees | Smart Fulfilment | — |
reverseLogisticsFee | REVERSE_SHIPPING | — | Reverse shipping | — |
feeTax | FEE_TAX | GST under a fee breakdown | Tax on fees | Tax on fees |
FEE_TAX is GST a channel charges on its own fees: input credit, posted to ledger 1320. TAX stays GST collected on the sale (2200). Lines imported before FEE_TAX existed keep TAX.
Code map
| Component | Path |
|---|---|
| Module | src/modules/finance/profitability/ |
| Calculator | utils/order-item-profit.calculator.ts |
| Rebuild | services/order-item-profit.service.ts, repositories/order-item-profit.repository.ts |
| Reads | services/profitability-query.service.ts, repositories/profitability-query.repository.ts (raw SQL, tenant filtered explicitly) |
| Worker | src/workers/processors/order-profit.processor.ts |
| Scheduler | src/workers/schedulers/order-profit.scheduler.ts |
| Admin page | pnxt-admin/src/features/profitability/, route /settlements/profitability |
| Admin data layer | pnxt-admin/src/lib/profitability/, also used by the order page's P&L card |
API surface
Versioned under /v1, tenant-scoped. Reads need PROFITABILITY:READ; repricing needs PROFITABILITY:UPDATE. Only the Owner role template gets these, through its wildcard.
| Method | Path | Purpose |
|---|---|---|
| GET | /finance/profitability/summary | KPIs, cost coverage, daily trend, unattributed payout lines |
| GET | /finance/profitability/orders | Orders with profit; filter = LOSS, LOW_MARGIN, COST_MISSING, RETURN_NOT_RECEIVED |
| GET | /finance/profitability/orders/:orderId | One order's P&L by item, with its payout lines. An original order includes its replacements; a replacement shows its own lines |
| GET | /finance/profitability/missing-costs | Products sold without a cost, by revenue at risk |
| POST | /finance/profitability/costs/reprice | Apply a product's current cost to its orders from a date |
Every read takes from and to (order days, default the last 30, at most 366), channelId and fulfilmentMode. Without a fulfilmentMode, FBA rows are excluded.