Skip to main content

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.

GroupColumns
KeysorderId, rollupOrderId (the original order, for replacements), channelId, legalEntityId, warehouseId, productId, sku, orderDate, orderDay (workspace-local), fulfilmentMode, commercialModel
Lifecyclestage, gaps[], dispatchedAt, deliveredAt, settledAt
Revenue (ex-GST)productSales, shippingIncome, giftWrapIncome, otherIncome, promotions, netRevenue
FeescommissionFee, fixedFee, collectionFee, logisticsFee, fulfilmentFee, penaltyFee, otherFees
CostunitCost, costSource, costCapturedAt, cogs, freight, freightSource
Returnsrefunds, feesRefunded, reverseLogisticsFee, reverseFreight, cogsRecovered, reimbursements
ResultschannelFees, returnCost, cm1, cm2 (the UI's "Profit"), cm3, marginPct, roiPct
Cash, not profitoutputTax, feeTax, tcs, tds, netPayout
BookkeepinginputsHash, 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 promotions
  • cm1 = netRevenue − forward fees − cogs − freight − gatewayFee
  • returnCost = refunds − feesRefunded + reverseLogisticsFee + reverseFreight − cogsRecovered
  • cm2 = cm1 − returnCost + reimbursements
  • cm3 = 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 (supersededById null). Each takes the confirmed categoryOverride if 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.costPrice now (PRODUCT_COST), or the sum of bundle components (BUNDLE). Rows created by the first-fill sweep record SWEEP. A zero cost counts as missing: the row gets COST_MISSING and 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, gap FREIGHT_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: rollupOrderId is the replaced order, so a replacement's cost and freight count against the original sale. Amazon ingestion sets Order.replacementOrderId once the original is synced.
  • Stage: SETTLED once a sale line is in a payout, else AWAITING_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.

TriggerPath
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 overrideSettlementReconciliationService.recomputeChunk queues an order-profit-recompute job per tenant on the profitability_queue
A product's cost changesproduct.cost.changed local event → ProductCostListener queues orders still missing a cost
A user reprices a product from a datePOST /finance/profitability/costs/reprice releases the captured cost of matching rows and queues them
Nightly, 03:30OrderProfitScheduler 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 mergeProductMergeService 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:

ColumnCategoriesAmazonFlipkartMeesho
commissionFeeCOMMISSIONReferral feeCommissionCommission
fixedFeeCLOSING_FEEClosing feeFixed feeFixed fee
collectionFeeCOLLECTION_FEE—Collection fee—
logisticsFeeSHIPPING_FEEEasy Ship, weight handlingShipping fee (negative shipping)Shipping fee
fulfilmentFeeFULFILMENT_FEEFBA feesSmart Fulfilment—
reverseLogisticsFeeREVERSE_SHIPPING—Reverse shipping—
feeTaxFEE_TAXGST under a fee breakdownTax on feesTax 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​

ComponentPath
Modulesrc/modules/finance/profitability/
Calculatorutils/order-item-profit.calculator.ts
Rebuildservices/order-item-profit.service.ts, repositories/order-item-profit.repository.ts
Readsservices/profitability-query.service.ts, repositories/profitability-query.repository.ts (raw SQL, tenant filtered explicitly)
Workersrc/workers/processors/order-profit.processor.ts
Schedulersrc/workers/schedulers/order-profit.scheduler.ts
Admin pagepnxt-admin/src/features/profitability/, route /settlements/profitability
Admin data layerpnxt-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.

MethodPathPurpose
GET/finance/profitability/summaryKPIs, cost coverage, daily trend, unattributed payout lines
GET/finance/profitability/ordersOrders with profit; filter = LOSS, LOW_MARGIN, COST_MISSING, RETURN_NOT_RECEIVED
GET/finance/profitability/orders/:orderIdOne 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-costsProducts sold without a cost, by revenue at risk
POST/finance/profitability/costs/repriceApply 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.