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:
| Payer | Pays through | Example |
|---|---|---|
| Marketplace | Settlement report | Amazon, Flipkart, Meesho, Shopify Payments |
| Courier | COD remittance | iThink, Delhivery |
| Payment gateway | Gateway payout | Razorpay, Cashfree, PayU, Stripe |
Every source loads into one payout spine:
- Each partner transfer is a
Payout. - What the partner reported is a set of
PayoutLinerows, 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.
| File | Models |
|---|---|
prisma/schema/51-settlement.prisma | ImportBatch, ImportRawRow, Payout, MarketplacePayoutDetail, CourierPayoutDetail, PayoutLine, PayoutLineResolution, ChannelSettlementConfig |
prisma/schema/53-receivable.prisma | Receivable, ReceivableMatch, FeeAudit, Dispute, DisputeEvent, DisputeAttachment, PlatformFeeSchedule, PlatformFeeRule |
prisma/schema/54-reconciliation-ops.prisma | ReconciliationRun, FinancePeriod, BankAccount, BankStatementLine, BankAllocation, GatewaySettlementMapping |
prisma/schema/56-journal.prisma | LedgerAccount, JournalVoucher, JournalLine, ErpAccountMapping, ErpSyncLog |
The payout spine
ImportBatchis one load of partner data: a file, an API sync, a webhook or a manual entry. The raw rows of a file load go toImportRawRow, partitioned bycreatedAtand kept for 13 months, so any line can be traced to the row it came from.Payoutis one transfer.source(MARKETPLACE,COURIER_COD,PAYMENT_GATEWAY) says who paid. Exactly one ofchannelId,courierIdandpaymentAccountIdis set.partnerIdrepeats it, so(tenantId, source, partnerId, externalPayoutId)is unique.- Control total:
declaredNetis what the partner said it paid,lineTotalis the sum of current lines, andcontrolStatuscompares the two (UNAVAILABLE,BALANCED,VARIANCE, orINCOMPLETEfor COD). - Bank:
bankAllocatedandbankStatusare kept up to date from bank allocations. - Source-specific figures live in
MarketplacePayoutDetail(report ids) andCourierPayoutDetail(gross COD, the amount remitted to the bank, and the wallet, hold and adjustment amounts).
PayoutLineis one amount exactly as reported.- Facts:
event(sale, refund…),category(principal, commission, TCS…) andsubjectType(order, return, SKU, inbound shipment…), plus the partner's own references (externalOrderRef,awbNo,externalPaymentRef,sku). - Lines are insert-only, enforced by a trigger.
dedupeHashmakes a re-import harmless. - A partner that restates a line produces a new line with the same
identityKey. The old one getssupersededByIdand drops out of totals. - Partitioned monthly by
valueDate. The primary key and every foreign key to it includevalueDate.
- Facts:
PayoutLineResolutionis 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 (
categoryOverridewithoverrideStatus).
- which order and item it belongs to (
What is owed
Receivableis what a payer owes for an order or an event, against what arrived.- Expected:
expectedGross,dueOn. - Settled:
settledGross,settledDeductions,settledNet, plustcsAmountandtdsAmountwithheld, and the resultingvariance. - Provenance:
recognisedFrom, the evidence that made it billable. - Status:
OPEN,PARTIAL,SETTLED,SHORT,OVER,REVERSED,HELD,WRITTEN_OFF,NOT_EXPECTED.
- Expected:
ReceivableMatchrecords which payout lines, and how much of each, settled a receivable.FeeAuditcompares each fee charged against the rate card (PlatformFeeScheduleandPlatformFeeRule).- 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.
Disputeis a case against a partner: short payment, fee overcharge, lost return, unreimbursed FBA inventory, COD short remittance and so on.DisputeEventis its history: opened, status changes, notes, attachments, recoveries.DisputeAttachmentholds its evidence files.
Bank and books
BankAccountholds the account's name, bank and the last four digits only.BankStatementLinerows are credits as the bank printed them; they are insert-only exceptmatchStatus.BankAllocationattributes part of a credit to one payout. One credit can pay several payouts.LedgerAccountis the tenant's chart, seeded from PointNXT's default chart on first use.JournalVoucherhas a status ofPOSTEDorREVERSED, and a reversal points at the voucher it undoes.JournalLinerows are append-only, partitioned byvoucherDate. A deferred trigger refuses a voucher whose debits and credits differ.ErpAccountMappingmaps a ledger account to the ERP's ledger name or account id.ErpSyncLoghas 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).
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:
| Order | Receivables opened |
|---|---|
Paid through a settlement report (expectsSettlementReport): Amazon, Flipkart, Meesho, Shopify Payments | One SALE receivable per order item, owed by the marketplace, due by the channel's settlement cycle (ChannelSettlementConfig) |
| COD shipment with a courier | One COD_COLLECTION receivable per shipment, owed by the courier, due 7 days after delivery |
| Successful gateway captures | One 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
UNRESOLVABLEafter 10 attempts. - After the first miss,
MissingOrderFetchServiceasks 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.
| Payer | Position computed by | Status rules |
|---|---|---|
| Marketplace | SettlementMatcherService, SettlementReconciliationBuilderService | Quantity 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 COD | codPosition | Collected vs expected within ₹1 or 0.01%; a clawed-back collection is REVERSED |
| Gateway | gatewayPosition | Captured 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
REIMBURSEMENTreceivable valued at the SKU's recent selling price, due 60 days after the event. - Units Amazon later finds (
F,Nadjustments) retire the matching losses. - Reimbursement credits on Amazon payouts settle receivables first-in, first-out per SKU.
- The nightly sweep opens an
UNREIMBURSED_INVENTORYcase 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_OVERCHARGEcase automatically, markedisSystemOpened. - 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_OFFand posts aRECEIVABLE_WRITE_OFFvoucher (Dr 5950 Receivable Write-offs, Cr the payer's clearing account). - A receivable has at most one active case,
OPENorFILED. Once a case is rejected, recovered or written off, a new one can be opened. reconcileRecoverieslinks reimbursement credits that arrived after a case was opened, and marks those cases recovered.
Bank matching
BankAllocationService:
importStatementstores 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 isAMOUNT_MISMATCHorUNMATCHED.allocateLinelets a person split a credit across payouts of any source. The allocations must add up to the credit within ₹1.matchPayoutrecords 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_TAXand posts to 1320 (input credit).TAXis GST collected on the sale and posts to 2200. Lines imported beforeFEE_TAXexisted keepTAX.
The default chart (DEFAULT_LEDGER_CHART in accounting-system.util.ts):
| Code | Account | Code | Account |
|---|---|---|---|
| 1120 | Marketplace Payout Clearing | 4300 | Marketplace Reimbursements |
| 1121 | Courier COD Clearing | 5000 | Marketplace Commission |
| 1122 | Payment Gateway Clearing | 5010 | Marketplace Shipping Fees |
| 1140 | Customer Receivables (COD) | 5020 | Fixed / Closing Fees |
| 1150 | Customer Receivables (Prepaid) | 5030 | Fulfilment & Pick-Pack Fees |
| 1250 | Settlement Carried Forward | 5040 | Reverse Shipping & Restocking |
| 1300 | GST TCS Receivable (s.52) | 5050 | Collection Fees |
| 1310 | Income Tax TDS Receivable (s.194-O) | 5100 | Marketplace Advertising |
| 1320 | GST Input Credit on Charges | 5200 | Storage & Warehousing (FBA) |
| 2200 | Output Tax Payable | 5300 | Payment Gateway Charges |
| 4000 | Marketplace Sales | 5400 | Marketplace Subscriptions |
| 4100 | Shipping Revenue Recovered | 5800 | Chargebacks |
| 4200 | Promotional Discounts | 5900 | Other Marketplace Charges |
| 5950 | Receivable 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
| Component | Path |
|---|---|
| Domain module | src/modules/finance/settlement/ |
| Repositories (one per aggregate) | payout, line-resolution, import-batch, receivable, dispute, bank, journal under settlement/repositories/ |
| Recognition | services/receivable-recognition.service.ts, listeners/receivable-recognition.listener.ts |
| Positions | services/settlement-reconciliation.service.ts, utils/receivable-position.util.ts |
| Missing orders | services/missing-order-fetch.service.ts |
| FBA | parsers/fba-report.parser.ts, services/fba-reimbursement.service.ts |
| Cases | services/dispute.service.ts |
| Bank | services/bank-allocation.service.ts |
| Journal | services/settlement-journal.service.ts, utils/journal-builder.util.ts, services/erp-integration.service.ts |
| Ledger accounts | src/modules/finance/accounting-system/services/ledger-account.service.ts |
| Workers | src/workers/processors/settlement-import.processor.ts (marketplace and FBA files), gateway-settlement.processor.ts |
| Schedulers | settlement-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) |
| Admin | pnxt-admin/src/features/settlements/ |
| Order profit | Rebuilt after every reconciliation; see Profitability |
API surface
Versioned under /v1, tenant-scoped, guarded by SETTLEMENT:* permissions.
| Method | Endpoint | Description |
|---|---|---|
GET | /finance/settlement | Payouts of every source (source, channelId, courierId, paymentAccountId, controlStatus, bankStatus, search) |
GET | /finance/settlement/:id · /:id/lines | One payout; its lines (includeSuperseded to see restated ones) |
POST | /finance/settlement/:id/bank-match | Record the bank credit a payout arrived as |
GET | /finance/settlement/control-exceptions | Payouts whose lines disagree with the declared total |
GET · POST | /finance/settlement/groups · /groups/link | Channel orders whose lines found no order; link them to an order item |
POST | /finance/settlement/lines/:id/category | Correct a line's category; the journal is re-posted |
GET · POST | /finance/settlement/suggestions · /suggestions/:id/confirm | Suggested categories for OTHER lines |
GET | /finance/settlement/leakage · /anomalies · /return-gaps | Money lost by kind; fee anomalies; refunds with no returned unit |
GET | /finance/settlement/reconciliation | Receivables (source, kind, status, recognisedFrom, overdueOnly, withoutOrder, disputed) |
GET | /finance/settlement/reconciliation/:id · /:id/fee-audits | One receivable; its fee checks |
PATCH | /finance/settlement/reconciliation/:id/dispute | Open or move the receivable's case |
GET | /finance/settlement/reconciliation/queue | Exception queue: RECEIVABLE, LINE, CONTROL, FEE, DISPUTE |
GET · POST | /finance/settlement/reconciliation/runs | Reconciliation runs; start one |
GET · POST | /finance/settlement/disputes | Cases; open one on a receivable or a payout line |
GET · PATCH | /finance/settlement/disputes/:id | A case with its history and evidence; move it |
POST | /finance/settlement/disputes/:id/comments · /:id/files | Add a note; attach evidence (upload purpose dispute-evidence) |
PATCH | /finance/settlement/disputes/bulk-status | Move several cases (not to written off) |
POST | /finance/settlement/disputes/recoveries · /sweeps/fba-reimbursements | Link recovery credits; open cases for unpaid FBA reimbursements |
POST | /finance/settlement/import · /import/fba | Register a settlement file or an FBA report |
GET · POST · PUT | /finance/settlement/bank/accounts | Bank accounts |
POST · GET | /finance/settlement/bank/statements/import · /statements | Import statement credits; list them |
GET · POST | /finance/settlement/bank/statements/:id/candidates · /:id/allocate | Payouts a credit could pay; allocate it |
GET | /finance/settlement/:id/journal · /journal/trial-balance | A payout's vouchers; the trial balance |
GET · POST · PUT | /finance/ledger-accounts | The tenant's chart of accounts |
GET · POST | /finance/settlement/erp/:systemId/{tally,zoho}/… · /erp/sync-logs | Export 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.