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:
@@ -0,0 +1,136 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { Product } from "@/lib/server/models/Product";
|
||||
import { StockTransfer, IStockTransfer } from "@/lib/server/models/StockTransfer";
|
||||
import { authorize, branchParam, MANAGERS } from "@/lib/server/auth";
|
||||
import { objectId } from "@/lib/server/validation";
|
||||
import { recordMovement, stockOf } from "@/lib/server/stock";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// GET /api/stock/transfers?branchId= — recent transfers into or out of the branch(es) in scope.
|
||||
export async function GET(req: NextRequest) {
|
||||
await connectDb();
|
||||
const gate = authorize(req, MANAGERS);
|
||||
if (!gate.ok) return gate.response;
|
||||
const auth = gate.auth;
|
||||
|
||||
const scope = branchParam(auth, req.nextUrl.searchParams.get("branchId"));
|
||||
if (!scope.ok) return scope.response;
|
||||
|
||||
const filter: Record<string, unknown> = { businessId: auth.businessId };
|
||||
if (scope.branchId) filter.$or = [{ fromBranchId: scope.branchId }, { toBranchId: scope.branchId }];
|
||||
|
||||
const transfers = await StockTransfer.find(filter)
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(100)
|
||||
.populate("fromBranchId", "branchName")
|
||||
.populate("toBranchId", "branchName")
|
||||
.populate("productId", "label unit")
|
||||
.populate("recordedBy", "name")
|
||||
.lean();
|
||||
return NextResponse.json({ transfers });
|
||||
}
|
||||
|
||||
const transferSchema = z.object({
|
||||
clientUuid: z.string().uuid(),
|
||||
fromBranchId: objectId.optional(), // owners must give one; managers send from their own branch
|
||||
toBranchId: objectId,
|
||||
productId: objectId,
|
||||
quantity: z.number().int().min(1).max(1_000_000),
|
||||
note: z.string().trim().max(300).optional(),
|
||||
});
|
||||
|
||||
/** Both ledger sides of a transfer. Idempotent, so it is safe to re-run on a retry. */
|
||||
async function applyTransfer(t: IStockTransfer) {
|
||||
const common = {
|
||||
businessId: t.businessId,
|
||||
productId: t.productId,
|
||||
refId: t._id.toString(),
|
||||
recordedBy: t.recordedBy,
|
||||
note: t.note,
|
||||
};
|
||||
await recordMovement({ ...common, branchId: t.fromBranchId, type: "TRANSFER_OUT", quantity: -t.quantity });
|
||||
await recordMovement({ ...common, branchId: t.toBranchId, type: "TRANSFER_IN", quantity: t.quantity });
|
||||
}
|
||||
|
||||
// POST /api/stock/transfers — move stock from one branch to another.
|
||||
// Owners: between any two branches. Managers: out of their own branch only.
|
||||
export async function POST(req: NextRequest) {
|
||||
await connectDb();
|
||||
const gate = authorize(req, MANAGERS);
|
||||
if (!gate.ok) return gate.response;
|
||||
const auth = gate.auth;
|
||||
|
||||
const parsed = transferSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: parsed.error.issues[0]?.message ?? "Invalid request" }, { status: 400 });
|
||||
}
|
||||
const data = parsed.data;
|
||||
|
||||
// A retried submit returns the transfer that already happened.
|
||||
const existing = await StockTransfer.findOne({ businessId: auth.businessId, clientUuid: data.clientUuid });
|
||||
if (existing) {
|
||||
await applyTransfer(existing);
|
||||
return NextResponse.json({ transfer: existing }, { status: 200 });
|
||||
}
|
||||
|
||||
let fromBranchId: string | null;
|
||||
if (auth.role === "SUPER_ADMIN") {
|
||||
fromBranchId = data.fromBranchId ?? null;
|
||||
if (!fromBranchId) return NextResponse.json({ error: "fromBranchId is required" }, { status: 400 });
|
||||
} else {
|
||||
fromBranchId = auth.branchId;
|
||||
if (data.fromBranchId && data.fromBranchId !== auth.branchId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Branch managers can only transfer stock out of their own branch" },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!fromBranchId) return NextResponse.json({ error: "No branch assignment for this account" }, { status: 403 });
|
||||
if (fromBranchId === data.toBranchId) {
|
||||
return NextResponse.json({ error: "Choose two different branches" }, { status: 400 });
|
||||
}
|
||||
|
||||
const [branchCount, product] = await Promise.all([
|
||||
Branch.countDocuments({ _id: { $in: [fromBranchId, data.toBranchId] }, businessId: auth.businessId }),
|
||||
Product.exists({ _id: data.productId, businessId: auth.businessId }),
|
||||
]);
|
||||
if (branchCount !== 2) return NextResponse.json({ error: "Branch not found in your business" }, { status: 404 });
|
||||
if (!product) return NextResponse.json({ error: "Product not found in your business" }, { status: 404 });
|
||||
|
||||
// Transfers are made online by a manager, so unlike offline sales they
|
||||
// can be refused when the sending branch does not have the stock.
|
||||
const available = await stockOf(auth.businessId, fromBranchId, data.productId);
|
||||
if (available < data.quantity) {
|
||||
return NextResponse.json(
|
||||
{ error: `Only ${Math.max(available, 0)} in stock at the sending branch`, available },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
let transfer: IStockTransfer;
|
||||
try {
|
||||
transfer = await StockTransfer.create({
|
||||
businessId: auth.businessId,
|
||||
fromBranchId,
|
||||
toBranchId: data.toBranchId,
|
||||
productId: data.productId,
|
||||
quantity: data.quantity,
|
||||
clientUuid: data.clientUuid,
|
||||
note: data.note ?? null,
|
||||
recordedBy: auth.sub,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
// Two identical submits raced and the other one created it.
|
||||
if ((err as { code?: number })?.code !== 11000) throw err;
|
||||
transfer = (await StockTransfer.findOne({ businessId: auth.businessId, clientUuid: data.clientUuid }))!;
|
||||
}
|
||||
await applyTransfer(transfer);
|
||||
|
||||
return NextResponse.json({ transfer }, { status: 201 });
|
||||
}
|
||||
Reference in New Issue
Block a user