Upload shopper registrations, and charge GST to the lines that earned it

Two defects that share a shape: a figure landing on the wrong record.

Bill-level discounts were apportioned across every line by a single
factor, so "20% off Beverages" pulled tax out of the atta line as well.
The bill total was right either way, which is what made it easy to ship
— only the slab split on a filed return was wrong. Targeted campaigns
now reduce the lines they name, and bill-wide reductions still spread
pro rata, so the arithmetic is unchanged wherever it was already right.

Shoppers registered at a till only ever reached the back office as three
fields riding along on a bill. Somebody who signed up and bought nothing
existed on one terminal and nowhere else, and two tills registering the
same mobile each minted their own row. Customers are now an outbox of
their own on pos/{store}/{terminal}/customer, and the id is a UUIDv5
over the normalised mobile number — so a hundred terminals agree on who
a shopper is without talking to each other.

Registrations go up before bills, and a failure there cannot strand a
day's takings. No loyalty figures are sent: they belong to the bill
stream, which is idempotent and knows about every counter.

Two things found while building it. Numbers were keyed on raw digits, so
a cashier typing +91 forked a shopper as effectively as a random id
would. And the sale path wrote the customer with ConflictAlgorithm
.replace, which is a DELETE and an INSERT — every column absent from the
row reverts to its schema default, so the new sync flag would have been
cleared by the shopper's next purchase.

Schema v8. Existing customers are queued rather than assumed sent: the
terminal cannot tell an imported row from a locally registered one, and
only one of those mistakes loses somebody.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Suriya
2026-08-03 11:34:27 +05:30
parent 467d5eee75
commit fe428931ec
24 changed files with 1274 additions and 78 deletions

View File

@@ -49,7 +49,7 @@ mqtt {
authorization {
users = [
{ user: "till", password: "…", permissions: {
publish: ["pos.*.*.order", "pos.*.*.status"]
publish: ["pos.*.*.order", "pos.*.*.customer", "pos.*.*.status"]
subscribe: ["pos.*.*.ack", "pos.*.*.command", "pos.*.catalogue"]
}}
]
@@ -193,6 +193,38 @@ for msg in subscribe("pos.*.*.order"):
`ON CONFLICT DO NOTHING` still counts as accepted — a redelivery of a bill you
already hold is a success, not a rejection.
### Shopper registrations
A second uplink runs on `pos/{store}/{terminal}/customer`, acked on the same
topic by the same rules. Wire it the same way:
```sql
CREATE TABLE customers (
id UUID PRIMARY KEY, -- derived from the mobile number
mobile TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
email TEXT,
gender TEXT,
date_of_birth DATE,
registered_at TIMESTAMPTZ,
registered_by_terminal TEXT
);
```
Insert with `ON CONFLICT (id) DO NOTHING`**never** an upsert. A registration
is replayed freely and must not overwrite a profile corrected at head office.
The id is a UUIDv5 over the shopper's normalised ten-digit mobile, so two tills
registering the same person independently produce the same row. Don't reassign
it. And don't expect loyalty points in this payload: derive those from the bill
stream, which is idempotent and knows about every counter.
```bash
nats sub 'pos.*.*.customer'
```
Add a shopper on the terminal — no sale needed — and it should appear.
**Use `rejected` sparingly.** Naming an id there halts the terminal's drain: it
stops retrying and waits for a person to press Sync. That is right for "this bill
is malformed" and wrong for "my database is having a bad minute" — for the
@@ -264,7 +296,9 @@ and per-bill state — start there before the broker logs.
## Before a fleet rollout
- **Back up `nearle_pos.db` on any terminal already trading.** The schema goes to
v7 on first launch and the migration is one-way.
v8 on first launch and the migration is one-way. It also queues every shopper
already on the terminal for upload, so expect one burst of registrations from
each existing store — collapse those onto the mobile number.
- **Build per-ABI.** `flutter build apk --split-per-abi` gives ~23MB per
architecture instead of a 69MB universal APK — worth it over shop wifi.
- **Change the seed PINs.** `4821` / `5093` / `6274` are in the source. Every

View File

@@ -63,6 +63,7 @@ connection or return 5xx instead, and the terminal will back off and retry.
| Topic | Direction | QoS | Retained |
|---|---|---|---|
| `pos/{store}/{terminal}/order` | till → cloud | 1 | no |
| `pos/{store}/{terminal}/customer` | till → cloud | 1 | no |
| `pos/{store}/{terminal}/ack` | cloud → till | 1 | no |
| `pos/{store}/{terminal}/status` | till → cloud | 1 | **yes** |
| `pos/{store}/{terminal}/command` | cloud → till | 1 | no |
@@ -157,6 +158,58 @@ nothing is marked synced, and the batch goes again.
response. Carries an `idempotency-key` header that is stable across retries of
the same bills.
### Shopper registrations
**Uplink**`pos/{store}/{terminal}/customer`, or `POST {base}/customers`.
Acked on the same topic and by the same rules: only ids you name are marked
sent.
```json
{
"schema": 1,
"batch_id": "3d7a…",
"store_id": "store-01",
"terminal_id": "T4A9",
"customers": [
{
"id": "7a24e082-060f-5503-aa9e-da0ef42df047",
"mobile": "9840012345",
"name": "Meena",
"email": null,
"gender": "female",
"date_of_birth": null,
"registered_at": "2026-08-01T10:14:00.000Z",
"registered_by_terminal": "T4A9"
}
]
}
```
Three things about this payload are load-bearing:
- **`id` is derived from the mobile number**, not minted at random — a UUIDv5
over the normalised ten-digit number in a fixed namespace. Two tills that
register the same shopper independently produce *the same id*, so you
deduplicate on a primary key rather than guessing at a merge later. Do not
reassign it.
- **Treat it as insert-if-absent on `id`.** A registration is not a financial
record: it is replayed freely, and it must never overwrite a profile
corrected at head office. `ON CONFLICT (id) DO NOTHING`.
- **No loyalty figures are sent.** Points, lifetime spend and visit counts are
absent on purpose — derive them from the bill stream, which is authoritative
and idempotent. Accepting a terminal's local balance would make the last till
to sync win, and a shopper who bought at two counters on the same day would
end up with whichever figure happened to arrive second.
Registrations are uploaded *before* bills on every pass, so a bill naming a new
shopper arrives after the shopper does. A failure here is logged and does not
hold up the bills behind it.
Terminals that were trading before schema v8 carry shoppers with random ids
from the old scheme. Those are queued once by the migration and arrive with
their original ids — merge them onto the mobile number. It is a one-off for
existing stores; a new terminal never produces one.
## Catalogue pull
The other direction: products and customers coming down.
@@ -237,15 +290,15 @@ overstate the day.
- **Downlink beyond catalogue-changed and sync-requested.** The plumbing routes
unknown commands to the events log rather than dropping them, so adding one
is a server change plus a case arm.
- **Credentials survive a restart.** The back-office dialog writes the broker
host, port, TLS flag and credentials into `syncConfigProvider`, which is
in-memory. Terminal name and store id persist (they live in the database);
the credentials do not, and must be re-entered after a restart. Persisting
them means encrypting them at rest, which is the next piece of work.
- **Historical correction.** Bills already synced by an older build went up
with an overstated total. Nothing here fixes that; it needs a server-side
reconciliation against `bill_discount`.
- **Pushing customers upward.** A shopper registered at the till stays on that
terminal and rides along on the bills they appear on. There is no
customer-create endpoint yet, so two terminals registering the same mobile
number will each hold their own row until the back office reconciles them.
- **Loyalty balances coming back down.** Points and lifetime spend are computed
per terminal from the bills that terminal rang. A shopper who buys at two
stores has two partial balances until the back office derives the real one
from the bill stream and sends it down in a catalogue pull. The uplink
deliberately does not carry local balances, so nothing is corrupted by this —
but a shopper's points at the till are that till's view, not the group's.
- **Merging pre-v8 shoppers.** Terminals that traded before the customer outbox
carry rows with random ids. They are uploaded once by the migration, but
collapsing them onto the mobile number is the back office's job.