Add a stock ledger, inter-branch transfers and a sync protocol that cannot jam

Stock (PRD 5.2): a branch's stock of a product is now the sum of its
StockMovement rows. Every movement names the document that caused it and
(type, refId) is unique, so replaying a sale, retrying a transfer or a
second M-Pesa callback never moves the same stock twice.

- Cash sales and confirmed M-Pesa payments deduct stock; purchases of a
  catalogue product add it.
- POST /api/stock/transfers moves stock between two branches (owner: any
  two; manager: out of their own) and refuses to send more than the
  sending branch holds. Double submits are applied once.
- POST /api/stock/adjustments records opening stock, breakage or a
  physical count (the ledger is corrected to the counted number).
- GET /api/stock returns every branch x product with LOW/OUT flags
  (per-product lowStockThreshold, default 10); GET /api/stock/movements
  is the history.

Sync (PRD 5.3/5.5): POST /api/transactions/cash now returns a result per
sale - saved, duplicate or rejected - instead of silently skipping
replays. The old client never learned a replayed sale had synced, so
rows piled up until the batch passed the 100-sale limit and every flush
failed with 400. Also:
- A sale can hold several products (one Transaction per line, grouped by
  saleId); the old single-product payload is still accepted.
- One bad sale is rejected on its own instead of failing the batch.
- A queued sale is only accepted from the cashier who recorded it, and
  stays with the branch where it happened.
- A product deactivated while offline is still recorded at its price; an
  invalid phone is dropped rather than losing the sale; the phone is now
  optional for cash sales.
- The price the device showed is kept and a difference is flagged
  (priceMismatch) instead of being silently overwritten.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-11 18:39:11 +03:00
parent d4808b3e46
commit 8817c0f52f
15 changed files with 982 additions and 69 deletions
+134
View File
@@ -0,0 +1,134 @@
import { describe, expect, it } from "vitest";
import { stockOf } from "@/lib/server/stock";
import * as stock from "@/app/api/stock/route";
import * as adjustments from "@/app/api/stock/adjustments/route";
import * as transfers from "@/app/api/stock/transfers/route";
import * as purchases from "@/app/api/purchases/route";
import { json, makeTenant, req, uuid, type Actor, type Tenant } from "./helpers";
async function addStock(t: Tenant, as: Actor, branchId: string, productId: string, quantity: number) {
const res = await adjustments.POST(
req("POST", "/x", { as, body: { clientUuid: uuid(), branchId, productId, mode: "DELTA", quantity, note: "opening" } })
);
expect(res.status).toBe(201);
}
describe("stock ledger", () => {
it("adds purchased stock to the receiving branch", async () => {
const t = await makeTenant();
const res = await purchases.POST(
req("POST", "/x", {
as: t.managerA,
body: { supplierName: "Kiwanja Water", productId: t.water20, quantity: 40, unitCost: 120 },
})
);
expect(res.status).toBe(201);
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(40);
});
it("corrects stock to a physical count, once per submit", async () => {
const t = await makeTenant();
await addStock(t, t.owner, t.branchA, t.water20, 50);
const body = { clientUuid: uuid(), productId: t.water20, mode: "COUNT", quantity: 47, note: "evening count" };
const first = await json(await adjustments.POST(req("POST", "/x", { as: t.managerA, body })));
expect(first.body.quantity).toBe(47);
// A double-submit of the same count changes nothing further.
const again = await json(await adjustments.POST(req("POST", "/x", { as: t.managerA, body })));
expect(again.body.quantity).toBe(47);
});
it("does not let a manager adjust another branch", async () => {
const t = await makeTenant();
const res = await adjustments.POST(
req("POST", "/x", {
as: t.managerA,
body: { clientUuid: uuid(), branchId: t.branchB, productId: t.water20, mode: "DELTA", quantity: 5 },
})
);
expect(res.status).toBe(403);
});
it("reports stock per branch with low and out-of-stock flags", async () => {
const t = await makeTenant();
await addStock(t, t.owner, t.branchA, t.water20, 8); // threshold defaults to 10
await addStock(t, t.owner, t.branchA, t.water5, 30);
const { body } = await json(await stock.GET(req("GET", "/api/stock", { as: t.owner })));
const find = (b: string, p: string) => body.levels.find((l: any) => l.branchId === b && l.productId === p);
expect(body.levels).toHaveLength(4); // 2 branches x 2 products, zero rows included
expect(find(t.branchA, t.water20)).toMatchObject({ quantity: 8, status: "LOW" });
expect(find(t.branchA, t.water5)).toMatchObject({ quantity: 30, status: "OK" });
expect(find(t.branchB, t.water20)).toMatchObject({ quantity: 0, status: "OUT" });
});
it("shows a cashier only their own branch's stock", async () => {
const t = await makeTenant();
const { body } = await json(await stock.GET(req("GET", "/api/stock?branchId=" + t.branchB, { as: t.cashierA })));
expect(new Set(body.levels.map((l: any) => l.branchId))).toEqual(new Set([t.branchA]));
});
});
describe("inter-branch transfers", () => {
it("moves stock out of one branch and into the other", async () => {
const t = await makeTenant();
await addStock(t, t.owner, t.branchA, t.water20, 30);
const res = await transfers.POST(
req("POST", "/x", {
as: t.owner,
body: { clientUuid: uuid(), fromBranchId: t.branchA, toBranchId: t.branchB, productId: t.water20, quantity: 12 },
})
);
expect(res.status).toBe(201);
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(18);
expect(await stockOf(t.businessId, t.branchB, t.water20)).toBe(12);
});
it("applies a double-submitted transfer once", async () => {
const t = await makeTenant();
await addStock(t, t.owner, t.branchA, t.water20, 30);
const body = { clientUuid: uuid(), toBranchId: t.branchB, productId: t.water20, quantity: 10 };
await transfers.POST(req("POST", "/x", { as: t.managerA, body }));
const second = await transfers.POST(req("POST", "/x", { as: t.managerA, body }));
expect(second.status).toBe(200);
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(20);
expect(await stockOf(t.businessId, t.branchB, t.water20)).toBe(10);
});
it("refuses to send more than the branch has", async () => {
const t = await makeTenant();
await addStock(t, t.owner, t.branchA, t.water20, 5);
const res = await transfers.POST(
req("POST", "/x", {
as: t.managerA,
body: { clientUuid: uuid(), toBranchId: t.branchB, productId: t.water20, quantity: 6 },
})
);
expect(res.status).toBe(409);
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(5);
});
it("only lets a manager send from their own branch", async () => {
const t = await makeTenant();
await addStock(t, t.owner, t.branchB, t.water20, 5);
const res = await transfers.POST(
req("POST", "/x", {
as: t.managerA,
body: { clientUuid: uuid(), fromBranchId: t.branchB, toBranchId: t.branchA, productId: t.water20, quantity: 1 },
})
);
expect(res.status).toBe(403);
});
it("cannot move stock into another tenant's branch", async () => {
const t = await makeTenant("Alpha");
const other = await makeTenant("Beta");
await addStock(t, t.owner, t.branchA, t.water20, 5);
const res = await transfers.POST(
req("POST", "/x", {
as: t.owner,
body: { clientUuid: uuid(), fromBranchId: t.branchA, toBranchId: other.branchA, productId: t.water20, quantity: 1 },
})
);
expect(res.status).toBe(404);
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(5);
});
});
+129
View File
@@ -0,0 +1,129 @@
import { describe, expect, it } from "vitest";
import { Transaction } from "@/lib/server/models/Transaction";
import { Product, BranchPricing } from "@/lib/server/models/Product";
import { stockOf } from "@/lib/server/stock";
import * as cash from "@/app/api/transactions/cash/route";
import type { SaleResult } from "@/lib/syncProtocol";
import { json, makeTenant, req, uuid, type Actor, type Tenant } from "./helpers";
function sale(t: Tenant, cashier: Actor, lines: { productId: string; quantity: number; unitPrice?: number }[], extra = {}) {
return {
clientUuid: uuid(),
staffId: cashier.id,
branchId: cashier.branchId!,
clientSubmittedAt: new Date().toISOString(),
lines,
...extra,
};
}
async function post(as: Actor, sales: unknown[]) {
return json<{ results: SaleResult[] }>(await cash.POST(req("POST", "/api/transactions/cash", { as, body: { sales } })));
}
describe("offline sale sync", () => {
it("records a multi-item sale as one line per product and deducts each from stock", async () => {
const t = await makeTenant();
const s = sale(t, t.cashierA, [
{ productId: t.water20, quantity: 2, unitPrice: 200 },
{ productId: t.water5, quantity: 3, unitPrice: 60 },
]);
const { status, body } = await post(t.cashierA, [s]);
expect(status).toBe(200);
expect(body.results).toEqual([{ clientUuid: s.clientUuid, status: "saved", amountTotal: 580, priceMismatch: false }]);
expect(await Transaction.countDocuments({ saleId: s.clientUuid })).toBe(2);
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(-2);
expect(await stockOf(t.businessId, t.branchA, t.water5)).toBe(-3);
});
it("reports a replayed sale as duplicate, so the device can stop resending it", async () => {
const t = await makeTenant();
const s = sale(t, t.cashierA, [{ productId: t.water20, quantity: 1 }]);
await post(t.cashierA, [s]);
const replay = await post(t.cashierA, [s]);
expect(replay.body.results[0]).toMatchObject({ clientUuid: s.clientUuid, status: "duplicate" });
expect(await Transaction.countDocuments({ saleId: s.clientUuid })).toBe(1);
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(-1);
});
it("syncs a 120-sale backlog in chunks with no duplicates (the old 100-row dead end)", async () => {
const t = await makeTenant();
const backlog = Array.from({ length: 120 }, () => sale(t, t.cashierA, [{ productId: t.water20, quantity: 1 }]));
// An over-sized batch is refused outright...
const tooBig = await cash.POST(req("POST", "/x", { as: t.cashierA, body: { sales: backlog } }));
expect(tooBig.status).toBe(400);
// ...and the device sends it in chunks of 50, twice over (a full replay).
for (let pass = 0; pass < 2; pass++) {
for (let i = 0; i < backlog.length; i += 50) {
const { status } = await post(t.cashierA, backlog.slice(i, i + 50));
expect(status).toBe(200);
}
}
expect(await Transaction.countDocuments({ businessId: t.businessId })).toBe(120);
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(-120);
});
it("rejects one bad sale without blocking the rest of the batch", async () => {
const t = await makeTenant();
const good = sale(t, t.cashierA, [{ productId: t.water20, quantity: 1 }]);
const malformed = { clientUuid: uuid(), lines: [] };
const { body } = await post(t.cashierA, [malformed, good]);
const byId = Object.fromEntries(body.results.map((r) => [r.clientUuid, r.status]));
expect(byId[malformed.clientUuid]).toBe("rejected");
expect(byId[good.clientUuid]).toBe("saved");
});
it("refuses to credit a queued sale to whoever happens to be signed in", async () => {
const t = await makeTenant();
const otherCashiersSale = sale(t, t.cashierB, [{ productId: t.water20, quantity: 1 }]);
const { body } = await post(t.cashierA, [otherCashiersSale]);
expect(body.results[0].status).toBe("rejected");
expect(await Transaction.countDocuments({})).toBe(0);
});
it("keeps a sale at the branch where it happened after the cashier is moved", async () => {
const t = await makeTenant();
const s = sale(t, t.cashierA, [{ productId: t.water20, quantity: 1 }]); // recorded at branch A
const moved = { ...t.cashierA, branchId: t.branchB };
await post(moved, [s]);
const txn = await Transaction.findOne({ saleId: s.clientUuid });
expect(txn!.branchId.toString()).toBe(t.branchA);
});
it("rejects a sale naming another tenant's product or branch", async () => {
const t = await makeTenant("Alpha");
const other = await makeTenant("Beta");
const foreignProduct = sale(t, t.cashierA, [{ productId: other.water20, quantity: 1 }]);
const foreignBranch = sale(t, t.cashierA, [{ productId: t.water20, quantity: 1 }], { branchId: other.branchA });
const { body } = await post(t.cashierA, [foreignProduct, foreignBranch]);
expect(body.results.map((r) => r.status)).toEqual(["rejected", "rejected"]);
expect(await Transaction.countDocuments({})).toBe(0);
});
it("uses the branch price, flags a price the device showed differently, and keeps deactivated products sellable", async () => {
const t = await makeTenant();
await BranchPricing.create({ businessId: t.businessId, branchId: t.branchA, productId: t.water20, unitPrice: 180 });
await Product.updateOne({ _id: t.water5 }, { isActive: false });
const s = sale(t, t.cashierA, [
{ productId: t.water20, quantity: 1, unitPrice: 200 }, // stale price on the device
{ productId: t.water5, quantity: 1, unitPrice: 60 },
]);
const { body } = await post(t.cashierA, [s]);
expect(body.results[0]).toMatchObject({ status: "saved", amountTotal: 240, priceMismatch: true });
});
it("accepts a cash sale with no customer phone, and keeps one with a bad phone", async () => {
const t = await makeTenant();
const noPhone = sale(t, t.cashierA, [{ productId: t.water20, quantity: 1 }]);
const badPhone = sale(t, t.cashierA, [{ productId: t.water20, quantity: 1 }], { customerPhone: "12" });
const { body } = await post(t.cashierA, [noPhone, badPhone]);
expect(body.results.map((r) => r.status)).toEqual(["saved", "saved"]);
});
it("still accepts the old single-product payload", async () => {
const t = await makeTenant();
const legacy = { clientUuid: uuid(), customerPhone: "0712345678", productId: t.water20, quantity: 2 };
const { body } = await post(t.cashierA, [legacy]);
expect(body.results[0]).toMatchObject({ status: "saved", amountTotal: 400 });
});
});