The problem
A lot of small businesses in Bangladesh sell through chat. An order starts as a Facebook or WhatsApp message, gets written into a notebook, is handed to a courier, and is paid for in cash on delivery — which the courier remits days later, in a lump sum, net of their charges.
So the seller’s real questions are hard to answer: what is still in transit, which parcels failed and are worth chasing, did the courier pay me for everything they collected, and — after product cost, courier fees, and expenses — did I actually make money this month? Finox Business puts the whole path, from the first message to the settled payout, in one place.
Constraints
Most of the design followed from who the users are and what already existed.
- Still one engineer, still alongside a full-time job — so it had to reuse Finox Personal’s API, authentication, subscription billing, and deploy pipeline rather than stand up a second backend.
- A cash-on-delivery audience: an order at “shipped” is a parcel in a van, not money. The numbers have to reflect that or they mislead.
- Sellers arrive with history — hundreds of orders and customers in spreadsheets — and will upload the same file more than once.
- Buyers have no account and never will, but still need to track their parcel.
Architecture
The backend is 13 new NestJS feature modules — orders, customers, products, stock, deliveries, invoices, expenses, payouts, reports, import, tracking, notifications, and the shop profile — inside the existing Finox API, backed by 14 new Prisma models over 8 migrations. The frontend is a separate zoneless Angular 21 app on its own subdomain, with 25 lazy-loaded routes and its own deploy.
Subscriptions had already moved into a table keyed by (userId, product), so one account can hold Finox Personal, Finox Business, or both, and the refresh cookie already carried sign-in across subdomains. Access is three route guards, each answering one question and redirecting somewhere different: who are you (sign in), have you paid (subscribe), and who is your shop (one-time setup).
Every table is scoped by userId, and order, invoice, and payout numbers are sequential per shop — sellers quote “#41” to a customer, and a global counter would leak how many orders every other shop has taken. Numbering is max+1 inside the transaction with a unique index as the race safety net and a single retry on conflict.
Orders and an append-only stock ledger
The order lifecycle only moves forward, plus the two ways an order can end badly. Shipped cannot go back to packed — once a parcel is with a courier, “un-shipping” is not a thing that happens, and allowing it would let stock and delivery records disagree about reality.
Stock is a materialised count on the product plus an append-only movement ledger, and there is exactly one function that changes it. Every write path — order confirmation, edits, cancellations and returns, purchases, manual adjustments, CSV import — goes through it.
- The change is a database-side increment, so two concurrent writers can’t read-modify-write the same stale count, and the ledger’s balance-after is taken from the value the increment returned.
- Stock moves once, when an order is confirmed — the first moment a unit is promised to a buyer. A timestamp on the order makes that idempotent: confirm, pack, ship deducts once, and a cancellation gives units back exactly once.
- Negative stock is logged, never blocked. A seller who forgot to record a purchase still has to be able to record the sale that happened; refusing would make the app lie to protect a number.
- Order lines snapshot product name, price, and cost, so restocking at a new price next month doesn’t rewrite the margin on orders already sold.
- A drift check lists any product whose ledger no longer sums to its count. It should always be empty; if it isn’t, some write path bypassed the ledger.
const product = await tx.commerceProduct.update({
where: { id: input.productId },
data: { stockQty: { increment: input.quantity } },
select: { stockQty: true },
});Reconciling cash on delivery
The payout feature exists to answer one question: did the courier pay me for everything they collected? It compares four independent figures, none of them stored as a derived total — what the courier was told to collect (snapshotted when an order is attached, so a later edit can’t rewrite history), what the seller marked as collected, what the courier says they remitted line by line, and what actually landed.
- “Unallocated” catches a data-entry mistake — the lines don’t add up to the lump sum. “Variance” catches the thing worth chasing — the courier is short. They are different questions, reported separately on purpose.
- An order drops out of the payout picker the moment it is attached, and a unique index backs that up, so the same cash can’t be settled twice.
- Every rejection is a named, actionable error — “Order SO-00014 is already on payout P-00003” — instead of a raw database constraint code.
Import that is safe to run twice
Importing is split into preview and commit. Preview parses and validates the file and stores the batch without writing a single order, product, or customer, so commit writes exactly what the seller saw — not a file that may have changed in between.
- Commit runs one transaction per row, not per file, so “row 47 failed; the other 899 landed” is actually true. The row’s fingerprint is written in the same transaction as the entity, so creating it and remembering it can never come apart.
- Each row is reduced to a canonical form — phone numbers normalised, currency symbols stripped, line items sorted — and hashed with SHA-256 under a version prefix. Re-uploading the same spreadsheet, even reformatted, doesn’t duplicate anything.
- Customers are matched on a canonical phone key, so “01712-345678” and “+880 1712 345678” are one repeat buyer, not two.
- Files are capped at 1,000 rows because the stack has no job queue yet; since fingerprints outlive batches, splitting a larger file is safe.
A public page with a deliberate boundary
Each order gets an unguessable token, and the buyer’s tracking page needs nothing else — no account, no guards, and not even the maintenance screen, because a buyer waiting on a parcel shouldn’t see one.
- The response is an interface mapped field by field, never a spread of the order row, so adding a column to orders can never silently start publishing it to the internet.
- The phone number is masked to confirm identity without handing the full number to whoever the link gets forwarded to.
- A malformed token and an unknown token return the same error, so probing the endpoint reveals nothing about the token format.
An online shop for every seller
Added later, Finox Store gives each seller their own shop at {name}.myfinox.com, built from the products they already keep in Finox Business. It is a separate Angular 21 app on Cloudflare Workers: one wildcard route serves every shop, and the app reads which shop it is from the hostname. On the API side it is one store module, covered by 7 test suites.
- A shop order takes the same path as an order the seller types in. The buyer sends only product ids and quantities; prices, offers, and totals are recomputed from the product rows, and stock is checked under a row lock inside the order transaction, so a buyer can’t order what the seller has already sold.
- The public shop API maps every field by hand, like the tracking page, so a column such as cost price can never reach buyers by accident.
- Whether a shop is open is derived on every read — the seller’s plan, Finox’s review, a suspension, the seller’s own switch — never stored as a flag that something has to remember to flip.
- Shop names become hostnames on Finox’s own domain, so they follow DNS label rules and refuse reserved Finox subdomains and bank or payment-provider names anywhere in the name.
- Product photos go to Cloudflare R2 as content-hashed WebP renditions, and each shop’s storage cap is claimed in one conditional UPDATE, so two uploads racing at the limit can’t both get through.
Reporting that doesn’t flatter
Revenue counts delivered orders only; order volume is reported separately and labelled as volume. Cost of goods and courier fees are computed over the same delivered set as revenue — mixing sets is the classic way to produce a margin that looks great and isn’t — and expenses turn gross profit into net.
Return rate is measured against orders that have reached an outcome, not everything shipped, so it doesn’t drift down just because the shop is busy. Invoices are generated client-side as PDFs with pdfmake, and a daily digest and trial-ending push notifications run as scheduled jobs.
What I’d do differently
- Move import commits onto a job queue so the 1,000-row cap can go, instead of asking sellers to split files.
- Wrap scheduled jobs in a Postgres advisory lock before the API scales past one machine — today every machine would fire them.
- Value stock with FIFO cost layers instead of current cost × quantity; the purchase ledger already records unit cost, so the input exists.
- Extract the shared Angular UI, auth, and HTTP code into a library now that two apps port the same fixes by hand.
Want to see it running?
View the live product
