Files
ERP/tests/sync.test.ts
T
denis_ireri 8817c0f52f 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>
2026-10-11 18:39:11 +03:00

130 lines
6.5 KiB
TypeScript

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 });
});
});