Files
ERP/tests/sync.test.ts
T
denis_ireri 83ec5ecd36 Enforce tenant isolation in the data layer instead of per route
Every route had to remember to add the business filter to every query;
nothing stopped one that forgot. The audit for this change found several
that had: the M-Pesa status re-check, the stock ledger's duplicate checks,
the daily-inventory and branch-price upserts, a cash-sale replay lookup,
several load-by-id lookups, and every populate().

- tenantGuard: a Mongoose plugin on all ten business-scoped models. Any
  find/update/delete/count/distinct, or an aggregate whose first stage is
  not a $match, that does not pin exactly one businessId throws
  TenantScopeError before reaching the database ($in, $exists and other
  operators do not count).
- crossTenant("reason", fn): the explicit, documented exemption for the
  queries that must span businesses - login's email lookup, refresh and
  invite-token lookups, the M-Pesa callback, the platform console and the
  maintenance scripts. git grep crossTenant lists them all.
- scopedPopulate: populated branch, product and staff names are also
  restricted to the business.
- Every flagged query site now names the business (or is exempted with a
  reason).
- Tests: a check that every model with a businessId field carries the
  guard; the guard refusing unscoped queries of every kind; and a route
  sweep where business A sends business B's ids to every read route
  (nothing of B's comes back) and every write route (all refused, B's
  data unchanged). Test-side database inspections go through db(), an
  explicit test exemption. Removing one route's business filter makes the
  suite fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 11:52:35 +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, db } 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 db(() => 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 db(() => 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 db(() => 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 db(() => 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 db(() => 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 db(() => 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 });
});
});