Skip to main content

Settlements & Financial Reconciliation

List pagination​

Finance screens now request pages instead of loading all rows at once. Bank statement lines accept search, page, and limit (up to 100). Reconciliation runs and gateway reconciliation lines accept page and limit (up to 100); gateway payouts use the same page parameters. The bank statements, runs, and gateway lines endpoints preserve their earlier array response when no paging parameters are supplied; with paging or bank search they return an object containing items and pagination metadata. New clients should request explicit pages and handle that object.

Overview​

Settlements answers one question for every order: who owes the seller money for it, did that money arrive, and is it in the bank and the books?

Money reaches a seller three ways, and all three use the same tables:

PayerPays throughExample
MarketplaceSettlement reportAmazon, Flipkart, Meesho, Shopify Payments
CourierCOD remittanceiThink, Delhivery
Payment gatewayGateway payoutRazorpay, Cashfree, PayU, Stripe

Every source loads into one payout spine:

  • Each partner transfer is a Payout.
  • What the partner reported is a set of PayoutLine rows, never edited.
  • What an order implies a partner owes is a Receivable.
  • Bank credits are matched to payouts.
  • Journal vouchers are posted for each payout.

Data model​

The schema lives in four files. The DB was reset when this model was introduced, so there is no compatibility layer with the old Settlement / CourierRemittance / GatewayPayout tables.

FileModels
prisma/schema/51-settlement.prismaImportBatch, ImportRawRow, Payout, MarketplacePayoutDetail, CourierPayoutDetail, PayoutLine, PayoutLineResolution, ChannelSettlementConfig
prisma/schema/53-receivable.prismaReceivable, ReceivableMatch, FeeAudit, Dispute, DisputeEvent, DisputeAttachment, PlatformFeeSchedule, PlatformFeeRule
prisma/schema/54-reconciliation-ops.prismaReconciliationRun, FinancePeriod, BankAccount, BankStatementLine, BankAllocation, GatewaySettlementMapping
prisma/schema/56-journal.prismaLedgerAccount, JournalVoucher, JournalLine, ErpAccountMapping, ErpSyncLog

The payout spine​

  • ImportBatch is one load of partner data: a file, an API sync, a webhook or a manual entry. The raw rows of a file load go to ImportRawRow, partitioned by createdAt and kept for 13 months, so any line can be traced to the row it came from.
  • Payout is one transfer.
    • source (MARKETPLACE, COURIER_COD, PAYMENT_GATEWAY) says who paid. Exactly one of channelId, courierId and paymentAccountId is set. partnerId repeats it, so (tenantId, source, partnerId, externalPayoutId) is unique.
    • Control total: declaredNet is what the partner said it paid, lineTotal is the sum of current lines, and controlStatus compares the two (UNAVAILABLE, BALANCED, VARIANCE, or INCOMPLETE for COD).
    • Bank: bankAllocated and bankStatus are kept up to date from bank allocations.
    • Source-specific figures live in MarketplacePayoutDetail (report ids) and CourierPayoutDetail (gross COD, the amount remitted to the bank, and the wallet, hold and adjustment amounts).
  • PayoutLine is one amount exactly as reported.
    • Facts: event (sale, refund…), category (principal, commission, TCS…) and subjectType (order, return, SKU, inbound shipment…), plus the partner's own references (externalOrderRef, awbNo, externalPaymentRef, sku).
    • Lines are insert-only, enforced by a trigger. dedupeHash makes a re-import harmless.
    • A partner that restates a line produces a new line with the same identityKey. The old one gets supersededById and drops out of totals.
    • Partitioned monthly by valueDate. The primary key and every foreign key to it include valueDate.
  • PayoutLineResolution is the interpretation of a line, kept apart from the fact:
    • which order and item it belongs to (state: PENDING, RESOLVED, UNRESOLVABLE, NOT_APPLICABLE);
    • how many times resolution was tried;
    • any category correction a person made (categoryOverride with overrideStatus).

What is owed​

  • Receivable is what a payer owes for an order or an event, against what arrived.
    • Expected: expectedGross, dueOn.
    • Settled: settledGross, settledDeductions, settledNet, plus tcsAmount and tdsAmount withheld, and the resulting variance.
    • Provenance: recognisedFrom, the evidence that made it billable.
    • Status: OPEN, PARTIAL, SETTLED, SHORT, OVER, REVERSED, HELD, WRITTEN_OFF, NOT_EXPECTED.
  • ReceivableMatch records which payout lines, and how much of each, settled a receivable.
  • FeeAudit compares each fee charged against the rate card (PlatformFeeSchedule and PlatformFeeRule).
    • Schedules are effective-dated. An exclusion constraint stops two schedules for the same scope from overlapping.
    • A rule can be limited to one fulfilmentMode, for example FBA rates.
  • Dispute is a case against a partner: short payment, fee overcharge, lost return, unreimbursed FBA inventory, COD short remittance and so on.
    • DisputeEvent is its history: opened, status changes, notes, attachments, recoveries.
    • DisputeAttachment holds its evidence files.

Bank and books​

  • BankAccount holds the account's name, bank and the last four digits only. BankStatementLine rows are credits as the bank printed them; they are insert-only except matchStatus. BankAllocation attributes part of a credit to one payout. One credit can pay several payouts.
  • LedgerAccount is the tenant's chart, seeded from PointNXT's default chart on first use.
    • JournalVoucher has a status of POSTED or REVERSED, and a reversal points at the voucher it undoes.
    • JournalLine rows are append-only, partitioned by voucherDate. A deferred trigger refuses a voucher whose debits and credits differ.
    • ErpAccountMapping maps a ledger account to the ERP's ledger name or account id.
    • ErpSyncLog has one row per voucher per system. A partial unique index stops the same voucher being sent to the same system twice.

FinancePeriod locks a month per legal entity; a trigger refuses journal lines dated in a locked month. Partition maintenance (PartitionMaintenanceService) creates the monthly partitions of PayoutLine, JournalLine and ImportRawRow ahead of time.


Who owes what: recognition​

A receivable opens when PointNXT's own order status says the order is billable: fulfilled, delivered, closed, or in a return state. Cancelling the order retires its open receivables (NOT_EXPECTED).

Order status, never channel status

Recognition reads Order.orderStatus. It never reads channelOrderStatus. The order status is already derived from the channel status, and it means the same thing on every channel.

ReceivableRecognitionListener handles order.status.changed from the outbox and calls SettlementReconciliationService.recomputeForOrder. It also handles order.created: an order imported already fulfilled records its first status without emitting a status change, so it is recognised on creation. ReceivableRecognitionService then decides who owes what:

OrderReceivables opened
Paid through a settlement report (expectsSettlementReport): Amazon, Flipkart, Meesho, Shopify PaymentsOne SALE receivable per order item, owed by the marketplace, due by the channel's settlement cycle (ChannelSettlementConfig)
COD shipment with a courierOne COD_COLLECTION receivable per shipment, owed by the courier, due 7 days after delivery
Successful gateway capturesOne order-level SALE receivable owed by the gateway, due 3 days after the last capture

recognisedFrom records the evidence: OMS_SHIPMENT when PointNXT shipped the order, otherwise ORDER_STATUS. The nightly sweep (findUnrecognisedOrderIds) catches billable orders the listener missed.

The expected amount of a marketplace line is orderLineProceeds, in order-line-proceeds.util.ts. It is what the line should bring in before marketplace fees:

  • Credits: item price × quantity, item tax, shipping, COD fee and gift wrap, each with its tax.
  • Reductions: promotions and discounts, with their tax.

History imported at onboarding​

A channel's first order sync backfills weeks of orders that were paid before PointNXT was watching, while the first settlement sync only looks back about 10 days. Expecting money for every backfilled order would show weeks of sales as unpaid.

ChannelSettlementConfig.recognitionStartsOn is the day a channel is reconciled from. SyncJobProcessorWorker sets it to the day of the channel's first order sync (lastOrderSync null), keeping any day already set; when it is null, Channel.createdAt stands in.

  • An order is compared by when it became billable: shipped, else delivered, else placed (billableSince).
  • An order billable on or after the start is owed for as usual.
  • An order billable before it gets no receivable until a payout line resolves to it. Then it is created, matched and fee-audited like any other, so money that does arrive for history is still accounted for.
  • An order that already has receivables keeps them.
  • The nightly sweep excludes pre-start orders in SQL, so it never re-reads them pass after pass.

To reconcile history, move the date earlier (Reconciliation → … → Reconcile from, or PUT /finance/settlement/config/:channelId with recognitionStartsOn) and run a settlement sync for that range. An old order that was genuinely never paid is caught only for the range covered this way.

Orders shipped outside PointNXT​

Sellers ship some orders without PointNXT: Amazon Easy Ship from Seller Central, a courier panel, FBA. These orders still reach a fulfilled status through order sync, so they are recognised exactly like orders PointNXT shipped, with recognisedFrom: ORDER_STATUS.

PointNXT records no shipment for them. A Shipment row always means PointNXT shipped it, and a lot of behaviour keys off whether one exists (fulfilment, NDR, RTO, Courier COD, freight audit, dashboards). A placeholder with no courier, AWB, COD amount or tracking would make those decisions wrong. As a result such orders open no courier COD receivable: the cash was collected by a courier PointNXT does not know about, or by the marketplace, which pays it in its settlement.

Multi-Channel Fulfilment (FBA shipping a non-Amazon order) arrives as a fee line naming PointNXT's order number. It resolves by order number as CROSS_CHANNEL.


Payout lines and their orders​

Loaders resolve each line to its order as they write it:

  • Marketplace: by channel order id and item.
  • COD: by AWB.
  • Gateway: by payment id, then by order number.

Lines that do not resolve stay PENDING, and the nightly job retries them (LineResolutionRepository.retryPending):

  • Retries are at least 20 hours apart, so one night cannot use up the attempts.
  • A line is parked as UNRESOLVABLE after 10 attempts.
  • After the first miss, MissingOrderFetchService asks the channel for the order through the ordinary order sync job on the SYNC queue. Amazon is asked for the one order (amazonOrderId). Other channels re-run their daily order sync.

Settled, no order in PointNXT​

The order may never arrive. Once a fetch has been queued and resolution has failed three times (ORPHAN_AFTER_ATTEMPTS), the lines open an ORDER_CHARGE receivable recognised from PAYOUT_LINE.

  • The receivable is settled at what was paid: nothing independent says what was owed.
  • The cash is still visible, and the fees can still be audited.
  • These are the "settled, no order in PointNXT" bucket on the dashboard and in the receivables filter (withoutOrder=true).

If the order arrives later, its waiting lines resolve and are adopted. The stand-in receivable is retired as NOT_EXPECTED, and the order's own receivables take over.


Matching and status​

SettlementReconciliationService.recomputeForOrders reloads an order's receivables and resolved lines, then recomputes each position from scratch. The calculation is idempotent: run it twice and nothing changes.

PayerPosition computed byStatus rules
MarketplaceSettlementMatcherService, SettlementReconciliationBuilderServiceQuantity settled vs ordered and money vs expected are folded into one status by receivableStatusFrom. The API also returns the two axes (quantityStatus, amountStatus), derived back by axesFromReceivable
Courier CODcodPositionCollected vs expected within ₹1 or 0.01%; a clawed-back collection is REVERSED
GatewaygatewayPositionCaptured vs settled before fees, within ₹0.50; refunds and chargebacks net against the capture

A payout whose lines do not add up to its declared total (controlStatus = VARIANCE) does not mark receivables settled. Its lines are not trusted until the gap is explained.


FBA reimbursements​

Amazon owes the seller for units it loses or damages in its warehouses, and for returns its carrier damages. These are uploaded as files, either the FBA Inventory Adjustments report or the FBA Customer Returns report (POST /finance/settlement/import/fba). FbaReportParser reads them and FbaReimbursementService turns them into receivables:

  • Every loss event becomes a REIMBURSEMENT receivable valued at the SKU's recent selling price, due 60 days after the event.
  • Units Amazon later finds (F, N adjustments) retire the matching losses.
  • Reimbursement credits on Amazon payouts settle receivables first-in, first-out per SKU.
  • The nightly sweep opens an UNREIMBURSED_INVENTORY case for each receivable still unpaid after its window.

Fees and cases​

SettlementFeeAuditorService compares each fee charged against the current schedule (SettlementFeeResolverService) and records a FeeAudit.

  • An overcharge opens a FEE_OVERCHARGE case automatically, marked isSystemOpened.
  • The RTO rule stays in force: reverse shipping on a shipment returned before delivery must be ₹0.
  • Short payments are not opened as cases automatically; a person opens them from the receivable.

A case moves OPEN → FILED → APPROVED → RECOVERED, or ends REJECTED or WRITTEN_OFF (DisputeService).

  • Recovered needs a recovery reference.
  • Written off needs a note, and a second approver from ₹5,000. Writing off closes the receivable as WRITTEN_OFF and posts a RECEIVABLE_WRITE_OFF voucher (Dr 5950 Receivable Write-offs, Cr the payer's clearing account).
  • A receivable has at most one active case, OPEN or FILED. Once a case is rejected, recovered or written off, a new one can be opened.
  • reconcileRecoveries links reimbursement credits that arrived after a case was opened, and marks those cases recovered.

Bank matching​

BankAllocationService:

  • importStatement stores credits per bank account. A credit whose reference names payouts (UTR or payout id), and whose amount equals what those payouts should bank within ₹1, is allocated at once. Otherwise it is AMOUNT_MISMATCH or UNMATCHED.
  • allocateLine lets a person split a credit across payouts of any source. The allocations must add up to the credit within ₹1.
  • matchPayout records a credit from the payout's side, creating the statement line if the statement was never imported.

What a payout should put in the bank is its declared net. For COD it is the courier's remitted amount: wallet credits and holds never reach the bank (bankAmountOf).


Journal and ERP​

SettlementJournalService.postForPayout builds balanced vouchers for a payout (journal-builder.util.ts).

Accounts used:

  • Clearing accounts are separate per source: marketplace 1120, COD 1121, gateway 1122.
  • COD and gateway cash post to customer receivables: 1140 for COD, 1150 for prepaid.

Dating:

  • A payout spanning two months posts each month's lines in that month and carries the balance forward through 1250.
  • A voucher whose date falls in a locked month is posted on today's date instead.

Changes and categories:

  • When a payout's lines change (a restated line, a category correction), its posted vouchers are reversed and fresh ones posted. Nothing posted is ever edited.
  • A line's category is the person's confirmed correction if there is one, else the parser's.
  • GST a channel charges on its own fees is FEE_TAX and posts to 1320 (input credit). TAX is GST collected on the sale and posts to 2200. Lines imported before FEE_TAX existed keep TAX.

The default chart (DEFAULT_LEDGER_CHART in accounting-system.util.ts):

CodeAccountCodeAccount
1120Marketplace Payout Clearing4300Marketplace Reimbursements
1121Courier COD Clearing5000Marketplace Commission
1122Payment Gateway Clearing5010Marketplace Shipping Fees
1140Customer Receivables (COD)5020Fixed / Closing Fees
1150Customer Receivables (Prepaid)5030Fulfilment & Pick-Pack Fees
1250Settlement Carried Forward5040Reverse Shipping & Restocking
1300GST TCS Receivable (s.52)5050Collection Fees
1310Income Tax TDS Receivable (s.194-O)5100Marketplace Advertising
1320GST Input Credit on Charges5200Storage & Warehousing (FBA)
2200Output Tax Payable5300Payment Gateway Charges
4000Marketplace Sales5400Marketplace Subscriptions
4100Shipping Revenue Recovered5800Chargebacks
4200Promotional Discounts5900Other Marketplace Charges
5950Receivable Write-offs

Tenants rename or retire accounts and add their own (/finance/ledger-accounts). Each accounting system maps ledger accounts to its own ledgers.

Vouchers go out per payout, per voucher or per date range (ErpIntegrationService). The ErpSyncLog index makes a re-push skip vouchers already sent.


Code map​

ComponentPath
Domain modulesrc/modules/finance/settlement/
Repositories (one per aggregate)payout, line-resolution, import-batch, receivable, dispute, bank, journal under settlement/repositories/
Recognitionservices/receivable-recognition.service.ts, listeners/receivable-recognition.listener.ts
Positionsservices/settlement-reconciliation.service.ts, utils/receivable-position.util.ts
Missing ordersservices/missing-order-fetch.service.ts
FBAparsers/fba-report.parser.ts, services/fba-reimbursement.service.ts
Casesservices/dispute.service.ts
Bankservices/bank-allocation.service.ts
Journalservices/settlement-journal.service.ts, utils/journal-builder.util.ts, services/erp-integration.service.ts
Ledger accountssrc/modules/finance/accounting-system/services/ledger-account.service.ts
Workerssrc/workers/processors/settlement-import.processor.ts (marketplace and FBA files), gateway-settlement.processor.ts
Schedulerssettlement-reconciliation.scheduler.ts (02:00: line retries, unrecognised and overdue orders, FBA reimbursement sweep), cod-remittance.scheduler.ts (04:00), gateway-settlement.scheduler.ts (05:00), erp-auto-push.scheduler.ts (06:00)
Adminpnxt-admin/src/features/settlements/
Order profitRebuilt after every reconciliation; see Profitability

API surface​

Versioned under /v1, tenant-scoped, guarded by SETTLEMENT:* permissions.

MethodEndpointDescription
GET/finance/settlementPayouts of every source (source, channelId, courierId, paymentAccountId, controlStatus, bankStatus, search)
GET/finance/settlement/:id · /:id/linesOne payout; its lines (includeSuperseded to see restated ones)
POST/finance/settlement/:id/bank-matchRecord the bank credit a payout arrived as
GET/finance/settlement/control-exceptionsPayouts whose lines disagree with the declared total
GET · POST/finance/settlement/groups · /groups/linkChannel orders whose lines found no order; link them to an order item
POST/finance/settlement/lines/:id/categoryCorrect a line's category; the journal is re-posted
GET · POST/finance/settlement/suggestions · /suggestions/:id/confirmSuggested categories for OTHER lines
GET/finance/settlement/leakage · /anomalies · /return-gapsMoney lost by kind; fee anomalies; refunds with no returned unit
GET/finance/settlement/reconciliationReceivables (source, kind, status, recognisedFrom, overdueOnly, withoutOrder, disputed)
GET/finance/settlement/reconciliation/:id · /:id/fee-auditsOne receivable; its fee checks
PATCH/finance/settlement/reconciliation/:id/disputeOpen or move the receivable's case
GET/finance/settlement/reconciliation/queueException queue: RECEIVABLE, LINE, CONTROL, FEE, DISPUTE
GET · POST/finance/settlement/reconciliation/runsReconciliation runs; start one
GET · POST/finance/settlement/disputesCases; open one on a receivable or a payout line
GET · PATCH/finance/settlement/disputes/:idA case with its history and evidence; move it
POST/finance/settlement/disputes/:id/comments · /:id/filesAdd a note; attach evidence (upload purpose dispute-evidence)
PATCH/finance/settlement/disputes/bulk-statusMove several cases (not to written off)
POST/finance/settlement/disputes/recoveries · /sweeps/fba-reimbursementsLink recovery credits; open cases for unpaid FBA reimbursements
POST/finance/settlement/import · /import/fbaRegister a settlement file or an FBA report
GET · POST · PUT/finance/settlement/bank/accountsBank accounts
POST · GET/finance/settlement/bank/statements/import · /statementsImport statement credits; list them
GET · POST/finance/settlement/bank/statements/:id/candidates · /:id/allocatePayouts a credit could pay; allocate it
GET/finance/settlement/:id/journal · /journal/trial-balanceA payout's vouchers; the trial balance
GET · POST · PUT/finance/ledger-accountsThe tenant's chart of accounts
GET · POST/finance/settlement/erp/:systemId/{tally,zoho}/… · /erp/sync-logsExport or push vouchers (payoutId, voucherId or from/to); the push log

COD endpoints are under /v1/finance/cod-remittance and gateway endpoints under /v1/finance/gateway-settlements. See Payment gateway settlements.