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
+140
View File
@@ -0,0 +1,140 @@
import mongoose, { Types } from "mongoose";
import { StockMovement, type MovementType } from "@/lib/server/models/StockMovement";
import { Branch } from "@/lib/server/models/Branch";
import { Product } from "@/lib/server/models/Product";
import type { ITransaction } from "@/lib/server/models/Transaction";
type Id = Types.ObjectId | string;
export interface MovementInput {
businessId: Id;
branchId: Id;
productId: Id;
type: MovementType;
quantity: number; // signed
refId: string;
note?: string | null;
recordedBy?: Id | null;
}
/**
* Write one ledger movement, idempotently: if a movement with the same
* (type, refId) already exists nothing changes. Safe to call again on any
* retry or replay.
*/
export async function recordMovement(m: MovementInput): Promise<void> {
await StockMovement.updateOne(
{ type: m.type, refId: m.refId },
{
$setOnInsert: {
businessId: m.businessId,
branchId: m.branchId,
productId: m.productId,
quantity: m.quantity,
note: m.note ?? null,
recordedBy: m.recordedBy ?? null,
},
},
{ upsert: true }
);
}
/**
* Deduct a completed sale from its branch's stock. Only SUCCESS sales move
* stock — a PENDING or FAILED M-Pesa prompt never does.
*/
export async function recordSaleMovement(
txn: Pick<ITransaction, "_id" | "businessId" | "branchId" | "productId" | "quantity" | "paymentStatus" | "staffId">
): Promise<void> {
if (txn.paymentStatus !== "SUCCESS") return;
await recordMovement({
businessId: txn.businessId,
branchId: txn.branchId,
productId: txn.productId,
type: "SALE",
quantity: -Math.abs(txn.quantity),
refId: txn._id.toString(),
recordedBy: txn.staffId,
});
}
/** Ledger refIds derived from client-generated keys are namespaced by tenant. */
export function clientRefId(businessId: Id, clientUuid: string): string {
return `${businessId.toString()}:${clientUuid}`;
}
/** Current stock of one product at one branch (the sum of its movements). */
export async function stockOf(businessId: Id, branchId: Id, productId: Id): Promise<number> {
const [row] = await StockMovement.aggregate<{ total: number }>([
{
$match: {
businessId: new mongoose.Types.ObjectId(businessId.toString()),
branchId: new mongoose.Types.ObjectId(branchId.toString()),
productId: new mongoose.Types.ObjectId(productId.toString()),
},
},
{ $group: { _id: null, total: { $sum: "$quantity" } } },
]);
return row?.total ?? 0;
}
export type StockStatus = "OK" | "LOW" | "OUT";
export interface StockLevel {
branchId: string;
branchName: string;
productId: string;
productLabel: string;
unit: string;
quantity: number;
lowStockThreshold: number;
status: StockStatus;
}
export function stockStatus(quantity: number, threshold: number): StockStatus {
if (quantity <= 0) return "OUT";
if (quantity <= threshold) return "LOW";
return "OK";
}
/**
* Stock of every active product at every branch in scope — including
* zero rows, so an owner sees "0" rather than a missing product. A
* negative quantity is reported as-is: it means sales were recorded
* (typically offline) for stock the ledger never received, and the branch
* needs a count/adjustment.
*/
export async function getStockLevels(businessId: Id, branchId?: Id | null): Promise<StockLevel[]> {
const bizObj = new mongoose.Types.ObjectId(businessId.toString());
const branchFilter: Record<string, unknown> = { businessId: bizObj };
if (branchId) branchFilter._id = new mongoose.Types.ObjectId(branchId.toString());
const [branches, products, totals] = await Promise.all([
Branch.find(branchFilter).sort({ branchName: 1 }).lean(),
Product.find({ businessId: bizObj, isActive: true }).sort({ sortOrder: 1 }).lean(),
StockMovement.aggregate<{ _id: { branchId: Types.ObjectId; productId: Types.ObjectId }; total: number }>([
{ $match: branchId ? { businessId: bizObj, branchId: branchFilter._id } : { businessId: bizObj } },
{ $group: { _id: { branchId: "$branchId", productId: "$productId" }, total: { $sum: "$quantity" } } },
]),
]);
const totalByKey = new Map(totals.map((t) => [`${t._id.branchId}:${t._id.productId}`, t.total]));
const levels: StockLevel[] = [];
for (const b of branches) {
for (const p of products) {
const quantity = totalByKey.get(`${b._id}:${p._id}`) ?? 0;
const lowStockThreshold = p.lowStockThreshold ?? 10;
levels.push({
branchId: b._id.toString(),
branchName: b.branchName,
productId: p._id.toString(),
productLabel: p.label,
unit: p.unit ?? "L",
quantity,
lowStockThreshold,
status: stockStatus(quantity, lowStockThreshold),
});
}
}
return levels;
}