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:
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { isMpesaEnabled } from "@/lib/server/env";
|
||||
import { Transaction } from "@/lib/server/models/Transaction";
|
||||
import { recordSaleMovement } from "@/lib/server/stock";
|
||||
import { MpesaCallbackLog } from "@/lib/server/models/MpesaCallbackLog";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
@@ -99,6 +100,7 @@ export async function POST(req: NextRequest) {
|
||||
txn.mpesaDetails.resultDesc = resultDesc;
|
||||
txn.mpesaDetails.receiptNumber = mpesaReceiptNumber;
|
||||
await txn.save();
|
||||
await recordSaleMovement(txn);
|
||||
|
||||
await MpesaCallbackLog.create({
|
||||
sourceIp,
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { isValidObjectId } from "mongoose";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { isMpesaEnabled } from "@/lib/server/env";
|
||||
import { Transaction } from "@/lib/server/models/Transaction";
|
||||
import { getAuth } from "@/lib/server/auth";
|
||||
import { queryStkStatus } from "@/lib/server/mpesa";
|
||||
import { recordSaleMovement } from "@/lib/server/stock";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -14,6 +16,7 @@ export async function GET(req: NextRequest, { params }: { params: { transactionI
|
||||
const auth = getAuth(req);
|
||||
if (!auth) return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
|
||||
|
||||
if (!isValidObjectId(params.transactionId)) return NextResponse.json({ error: "Transaction not found" }, { status: 404 });
|
||||
const txn = await Transaction.findOne({ _id: params.transactionId, businessId: auth.businessId });
|
||||
if (!txn) return NextResponse.json({ error: "Transaction not found" }, { status: 404 });
|
||||
|
||||
@@ -29,6 +32,7 @@ export async function GET(req: NextRequest, { params }: { params: { transactionI
|
||||
fresh.mpesaDetails.resultCode = code;
|
||||
fresh.mpesaDetails.resultDesc = result.ResultDesc;
|
||||
await fresh.save();
|
||||
await recordSaleMovement(fresh);
|
||||
return NextResponse.json(fresh);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Purchase } from "@/lib/server/models/Purchase";
|
||||
import { Product } from "@/lib/server/models/Product";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { objectId } from "@/lib/server/validation";
|
||||
import { recordMovement } from "@/lib/server/stock";
|
||||
import { authorize, branchParam, MANAGERS } from "@/lib/server/auth";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
@@ -57,8 +58,9 @@ const createSchema = z.object({
|
||||
|
||||
// POST /api/purchases — records a supplier purchase. The buying price is
|
||||
// snapshotted (unitCost/totalCost) so historical records never shift when
|
||||
// product prices change later. A completed purchase conceptually increases
|
||||
// branch stock.
|
||||
// product prices change later. A purchase of a catalogue product adds its
|
||||
// quantity to the branch's stock ledger; a free-text item (no productId)
|
||||
// is recorded as a cost only.
|
||||
export async function POST(req: NextRequest) {
|
||||
await connectDb();
|
||||
const gate = authorize(req, MANAGERS);
|
||||
@@ -125,5 +127,18 @@ export async function POST(req: NextRequest) {
|
||||
recordedBy: auth.sub,
|
||||
});
|
||||
|
||||
if (productId) {
|
||||
await recordMovement({
|
||||
businessId: auth.businessId,
|
||||
branchId: branchId!,
|
||||
productId,
|
||||
type: "PURCHASE",
|
||||
quantity: parsed.data.quantity,
|
||||
refId: purchase._id.toString(),
|
||||
note: `From ${parsed.data.supplierName}`,
|
||||
recordedBy: auth.sub,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ purchase }, { status: 201 });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
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 { StockMovement } from "@/lib/server/models/StockMovement";
|
||||
import { authorize, MANAGERS } from "@/lib/server/auth";
|
||||
import { objectId } from "@/lib/server/validation";
|
||||
import { clientRefId, recordMovement, stockOf } from "@/lib/server/stock";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
const adjustmentSchema = z.object({
|
||||
clientUuid: z.string().uuid(),
|
||||
branchId: objectId.optional(), // owners must give one; managers default to their own branch
|
||||
productId: objectId,
|
||||
// COUNT: "we physically counted N", so the ledger is corrected to N.
|
||||
// DELTA: "add or remove N", e.g. opening stock, breakage, or a delivery
|
||||
// that was not recorded as a purchase.
|
||||
mode: z.enum(["COUNT", "DELTA"]),
|
||||
quantity: z.number().int().min(-1_000_000).max(1_000_000),
|
||||
note: z.string().trim().max(300).optional(),
|
||||
});
|
||||
|
||||
// POST /api/stock/adjustments — managers (own branch) and owners (any branch).
|
||||
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 = adjustmentSchema.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;
|
||||
if (data.mode === "COUNT" && data.quantity < 0) {
|
||||
return NextResponse.json({ error: "A counted quantity cannot be negative" }, { status: 400 });
|
||||
}
|
||||
|
||||
let branchId: string | null;
|
||||
if (auth.role === "SUPER_ADMIN") {
|
||||
branchId = data.branchId ?? null;
|
||||
if (!branchId) return NextResponse.json({ error: "branchId is required" }, { status: 400 });
|
||||
} else {
|
||||
branchId = auth.branchId;
|
||||
if (data.branchId && data.branchId !== auth.branchId) {
|
||||
return NextResponse.json({ error: "Cannot adjust stock for another branch" }, { status: 403 });
|
||||
}
|
||||
}
|
||||
if (!branchId) return NextResponse.json({ error: "No branch assignment for this account" }, { status: 403 });
|
||||
|
||||
const [branch, product] = await Promise.all([
|
||||
Branch.exists({ _id: branchId, businessId: auth.businessId }),
|
||||
Product.exists({ _id: data.productId, businessId: auth.businessId }),
|
||||
]);
|
||||
if (!branch) 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 });
|
||||
|
||||
// A retried submit with the same clientUuid is a no-op.
|
||||
const refId = clientRefId(auth.businessId, data.clientUuid);
|
||||
const already = await StockMovement.exists({ type: "ADJUSTMENT", refId });
|
||||
if (!already) {
|
||||
const before = await stockOf(auth.businessId, branchId, data.productId);
|
||||
const delta = data.mode === "COUNT" ? data.quantity - before : data.quantity;
|
||||
if (delta !== 0) {
|
||||
const label = data.mode === "COUNT" ? `Count: ${before} -> ${data.quantity}` : "Adjustment";
|
||||
await recordMovement({
|
||||
businessId: auth.businessId,
|
||||
branchId,
|
||||
productId: data.productId,
|
||||
type: "ADJUSTMENT",
|
||||
quantity: delta,
|
||||
refId,
|
||||
note: data.note ? `${label}. ${data.note}` : label,
|
||||
recordedBy: auth.sub,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const quantity = await stockOf(auth.businessId, branchId, data.productId);
|
||||
return NextResponse.json({ branchId, productId: data.productId, quantity }, { status: 201 });
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { StockMovement } from "@/lib/server/models/StockMovement";
|
||||
import { authorize, branchParam, MANAGERS } from "@/lib/server/auth";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// GET /api/stock/movements?branchId=&limit= — recent ledger entries, newest first.
|
||||
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 limit = Math.min(Number(req.nextUrl.searchParams.get("limit")) || 50, 200);
|
||||
|
||||
const filter: Record<string, unknown> = { businessId: auth.businessId };
|
||||
if (scope.branchId) filter.branchId = scope.branchId;
|
||||
|
||||
const movements = await StockMovement.find(filter)
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(limit)
|
||||
.populate("branchId", "branchName")
|
||||
.populate("productId", "label unit")
|
||||
.populate("recordedBy", "name")
|
||||
.lean();
|
||||
return NextResponse.json({ movements });
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { authorize, branchParam } from "@/lib/server/auth";
|
||||
import { getStockLevels } from "@/lib/server/stock";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// GET /api/stock?branchId= — current stock per branch and product.
|
||||
// Owners see every branch (or one, via branchId); everyone else sees only
|
||||
// their own branch.
|
||||
export async function GET(req: NextRequest) {
|
||||
await connectDb();
|
||||
const gate = authorize(req);
|
||||
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;
|
||||
if (auth.role !== "SUPER_ADMIN" && !scope.branchId) return NextResponse.json({ levels: [] });
|
||||
|
||||
const levels = await getStockLevels(auth.businessId, scope.branchId);
|
||||
return NextResponse.json({ levels });
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -1,29 +1,67 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { Transaction } from "@/lib/server/models/Transaction";
|
||||
import { Transaction, ITransaction } from "@/lib/server/models/Transaction";
|
||||
import { Product, BranchPricing } from "@/lib/server/models/Product";
|
||||
import { getAuth, requireRole, resolveBranchScope } from "@/lib/server/auth";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { authorize } from "@/lib/server/auth";
|
||||
import { normalizeKenyanPhone } from "@/lib/server/phone";
|
||||
import { objectId } from "@/lib/server/validation";
|
||||
import { recordSaleMovement } from "@/lib/server/stock";
|
||||
import { MAX_LINES_PER_SALE, MAX_SALES_PER_REQUEST, type SaleResult } from "@/lib/syncProtocol";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
const saleSchema = z.object({
|
||||
clientUuid: z.string().uuid(),
|
||||
customerName: z.string().trim().max(120).optional(),
|
||||
customerPhone: z.string().trim().min(9).max(15),
|
||||
productId: z.string().min(1),
|
||||
const lineSchema = z.object({
|
||||
productId: objectId,
|
||||
quantity: z.number().int().min(1).max(500),
|
||||
clientSubmittedAt: z.string().datetime().optional(),
|
||||
unitPrice: z.number().nonnegative().optional(), // what the device showed; informational
|
||||
});
|
||||
const bodySchema = z.object({ sales: z.array(saleSchema).min(1).max(100) });
|
||||
|
||||
const saleSchema = z.preprocess(
|
||||
// Older clients sent one product per sale at the top level.
|
||||
(raw) => {
|
||||
const r = raw as Record<string, unknown> | null;
|
||||
if (r && !Array.isArray(r.lines) && r.productId) {
|
||||
return { ...r, lines: [{ productId: r.productId, quantity: r.quantity }] };
|
||||
}
|
||||
return raw;
|
||||
},
|
||||
z.object({
|
||||
clientUuid: z.string().uuid(),
|
||||
staffId: objectId.optional(), // who recorded it on the device
|
||||
branchId: objectId.optional(), // where it was recorded
|
||||
customerName: z.string().trim().max(120).optional(),
|
||||
customerPhone: z.string().trim().max(20).optional(),
|
||||
clientSubmittedAt: z.string().datetime().optional(),
|
||||
lines: z.array(lineSchema).min(1).max(MAX_LINES_PER_SALE),
|
||||
})
|
||||
);
|
||||
type SaleInput = z.infer<typeof saleSchema>;
|
||||
|
||||
const bodySchema = z.object({ sales: z.array(z.unknown()).min(1).max(MAX_SALES_PER_REQUEST) });
|
||||
|
||||
/**
|
||||
* POST /api/transactions/cash — record cash sales, one or many, live or
|
||||
* replayed from the device's offline queue.
|
||||
*
|
||||
* Every sale gets its own result so the device knows exactly what to do
|
||||
* with each queued row:
|
||||
* saved newly recorded -> mark synced
|
||||
* duplicate already recorded earlier -> mark synced (this is a replay)
|
||||
* rejected can never be recorded -> stop retrying, show the cashier
|
||||
* One bad sale never blocks the others in the batch.
|
||||
*
|
||||
* Idempotency: each line's clientUuid is `${saleUuid}:${index}` and is
|
||||
* unique in the database; the stock movement for each line is keyed on
|
||||
* the transaction id. Replaying a sale any number of times records it,
|
||||
* and deducts its stock, exactly once.
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
await connectDb();
|
||||
const auth = getAuth(req);
|
||||
if (!requireRole(auth, "DELIVERY", "BRANCH_MANAGER")) {
|
||||
return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
|
||||
}
|
||||
const gate = authorize(req, ["DELIVERY", "BRANCH_MANAGER"]);
|
||||
if (!gate.ok) return gate.response;
|
||||
const auth = gate.auth;
|
||||
|
||||
const json = await req.json().catch(() => null);
|
||||
const normalized = Array.isArray(json?.sales) ? json : { sales: [json] };
|
||||
@@ -31,61 +69,124 @@ export async function POST(req: NextRequest) {
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: parsed.error.issues[0]?.message ?? "Invalid request" }, { status: 400 });
|
||||
}
|
||||
|
||||
const branchId = resolveBranchScope(auth!);
|
||||
if (!branchId) {
|
||||
if (!auth.branchId) {
|
||||
return NextResponse.json({ error: "No active branch assignment for this account" }, { status: 403 });
|
||||
}
|
||||
|
||||
const { sales } = parsed.data;
|
||||
const productIds = Array.from(new Set(sales.map((s) => s.productId)));
|
||||
const products = await Product.find({ _id: { $in: productIds }, businessId: auth!.businessId }).lean();
|
||||
const overrides = await BranchPricing.find({ branchId, productId: { $in: productIds }, businessId: auth!.businessId }).lean();
|
||||
const productMap = new Map(products.map((p) => [p._id.toString(), p]));
|
||||
const overrideMap = new Map(overrides.map((o) => [o.productId.toString(), o.unitPrice]));
|
||||
|
||||
const rejected: { clientUuid: string; error: string }[] = [];
|
||||
const inserted: any[] = [];
|
||||
|
||||
for (const sale of sales) {
|
||||
let phone: string;
|
||||
try {
|
||||
phone = normalizeKenyanPhone(sale.customerPhone);
|
||||
} catch (e: any) {
|
||||
rejected.push({ clientUuid: sale.clientUuid, error: e.message });
|
||||
continue;
|
||||
}
|
||||
const product = productMap.get(sale.productId);
|
||||
if (!product || !product.isActive) {
|
||||
rejected.push({ clientUuid: sale.clientUuid, error: "Product not available" });
|
||||
continue;
|
||||
}
|
||||
const unitPrice = overrideMap.get(sale.productId) ?? product.unitPrice;
|
||||
|
||||
try {
|
||||
const created = await Transaction.create({
|
||||
businessId: auth!.businessId,
|
||||
branchId,
|
||||
staffId: auth!.sub,
|
||||
customerName: sale.customerName ?? null,
|
||||
customerPhone: phone,
|
||||
productId: product._id,
|
||||
sizeLiters: product.sizeLiters,
|
||||
quantity: sale.quantity,
|
||||
unitPrice,
|
||||
amountTotal: Math.round(sale.quantity * unitPrice * 100) / 100,
|
||||
paymentMethod: "CASH",
|
||||
paymentStatus: "SUCCESS",
|
||||
clientUuid: sale.clientUuid,
|
||||
syncedFromOffline: !!sale.clientSubmittedAt,
|
||||
clientSubmittedAt: sale.clientSubmittedAt ? new Date(sale.clientSubmittedAt) : null,
|
||||
});
|
||||
inserted.push(created);
|
||||
} catch (err: any) {
|
||||
if (err?.code === 11000) continue;
|
||||
rejected.push({ clientUuid: sale.clientUuid, error: "Could not save this sale" });
|
||||
const sales: SaleInput[] = [];
|
||||
const results: SaleResult[] = [];
|
||||
for (const raw of parsed.data.sales) {
|
||||
const sale = saleSchema.safeParse(raw);
|
||||
if (sale.success) {
|
||||
sales.push(sale.data);
|
||||
} else {
|
||||
const clientUuid = String((raw as { clientUuid?: unknown })?.clientUuid ?? "");
|
||||
results.push({ clientUuid, status: "rejected", error: sale.error.issues[0]?.message ?? "Invalid sale" });
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ inserted, rejected });
|
||||
// Tenant data needed to price every line in the batch, in three queries.
|
||||
const productIds = Array.from(new Set(sales.flatMap((s) => s.lines.map((l) => l.productId))));
|
||||
const branchIds = Array.from(new Set([auth.branchId, ...sales.map((s) => s.branchId ?? auth.branchId!)]));
|
||||
const [products, overrides, branches] = await Promise.all([
|
||||
Product.find({ _id: { $in: productIds }, businessId: auth.businessId }).lean(),
|
||||
BranchPricing.find({ branchId: { $in: branchIds }, productId: { $in: productIds }, businessId: auth.businessId }).lean(),
|
||||
Branch.find({ _id: { $in: branchIds }, businessId: auth.businessId }).select("_id").lean(),
|
||||
]);
|
||||
const productMap = new Map(products.map((p) => [p._id.toString(), p]));
|
||||
const overrideMap = new Map(overrides.map((o) => [`${o.branchId}:${o.productId}`, o.unitPrice]));
|
||||
const tenantBranches = new Set(branches.map((b) => b._id.toString()));
|
||||
|
||||
for (const sale of sales) {
|
||||
results.push(await recordSale(sale));
|
||||
}
|
||||
|
||||
async function recordSale(sale: SaleInput): Promise<SaleResult> {
|
||||
const reject = (error: string): SaleResult => ({ clientUuid: sale.clientUuid, status: "rejected", error });
|
||||
|
||||
// A queued sale belongs to the cashier who made it. The device only
|
||||
// sends its signed-in user's rows; anything else is refused rather than
|
||||
// credited to the wrong person.
|
||||
if (sale.staffId && sale.staffId !== auth.sub) {
|
||||
return reject("This sale was recorded by a different user. Sign in as them to sync it.");
|
||||
}
|
||||
// The sale stays with the branch where it happened, even if the
|
||||
// cashier has since been moved — as long as that branch is in this business.
|
||||
const branchId = sale.branchId ?? auth.branchId!;
|
||||
if (!tenantBranches.has(branchId)) return reject("This sale's branch is not part of your business.");
|
||||
|
||||
for (const line of sale.lines) {
|
||||
if (!productMap.has(line.productId)) return reject("A product in this sale no longer exists.");
|
||||
}
|
||||
|
||||
// A bad phone number must not lose a sale that physically happened.
|
||||
let customerPhone: string | null = null;
|
||||
if (sale.customerPhone) {
|
||||
try {
|
||||
customerPhone = normalizeKenyanPhone(sale.customerPhone);
|
||||
} catch {
|
||||
customerPhone = null;
|
||||
}
|
||||
}
|
||||
|
||||
let newLines = 0;
|
||||
let amountTotal = 0;
|
||||
let priceMismatch = false;
|
||||
for (const [index, line] of sale.lines.entries()) {
|
||||
// A product deactivated while the device was offline is still
|
||||
// recorded at its price: the sale already happened.
|
||||
const product = productMap.get(line.productId)!;
|
||||
const unitPrice = overrideMap.get(`${branchId}:${line.productId}`) ?? product.unitPrice;
|
||||
const lineTotal = Math.round(line.quantity * unitPrice * 100) / 100;
|
||||
const mismatch = line.unitPrice !== undefined && line.unitPrice !== unitPrice;
|
||||
|
||||
let txn: ITransaction;
|
||||
try {
|
||||
txn = await Transaction.create({
|
||||
businessId: auth.businessId,
|
||||
branchId,
|
||||
staffId: auth.sub,
|
||||
customerName: sale.customerName || null,
|
||||
customerPhone,
|
||||
productId: product._id,
|
||||
sizeLiters: product.sizeLiters,
|
||||
quantity: line.quantity,
|
||||
unitPrice,
|
||||
amountTotal: lineTotal,
|
||||
paymentMethod: "CASH",
|
||||
paymentStatus: "SUCCESS",
|
||||
clientUuid: `${sale.clientUuid}:${index}`,
|
||||
saleId: sale.clientUuid,
|
||||
lineIndex: index,
|
||||
syncedFromOffline: !!sale.clientSubmittedAt,
|
||||
clientSubmittedAt: sale.clientSubmittedAt ? new Date(sale.clientSubmittedAt) : null,
|
||||
clientUnitPrice: line.unitPrice ?? null,
|
||||
priceMismatch: mismatch,
|
||||
});
|
||||
newLines += 1;
|
||||
} catch (err: unknown) {
|
||||
if ((err as { code?: number })?.code !== 11000) throw err;
|
||||
// Already recorded by an earlier attempt: reuse it.
|
||||
const existing = await Transaction.findOne({ clientUuid: `${sale.clientUuid}:${index}` });
|
||||
if (!existing || existing.businessId.toString() !== auth.businessId) {
|
||||
return reject("This sale id is already in use.");
|
||||
}
|
||||
txn = existing;
|
||||
}
|
||||
// Idempotent, and also repairs a line whose stock movement was not
|
||||
// written because an earlier attempt failed midway.
|
||||
await recordSaleMovement(txn);
|
||||
amountTotal += txn.amountTotal;
|
||||
priceMismatch = priceMismatch || txn.priceMismatch;
|
||||
}
|
||||
|
||||
return {
|
||||
clientUuid: sale.clientUuid,
|
||||
status: newLines === 0 ? "duplicate" : "saved",
|
||||
amountTotal: Math.round(amountTotal * 100) / 100,
|
||||
priceMismatch,
|
||||
};
|
||||
}
|
||||
|
||||
return NextResponse.json({ results });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Schema, model, models, Model, Types, Document } from "mongoose";
|
||||
|
||||
export const MOVEMENT_TYPES = ["SALE", "PURCHASE", "TRANSFER_OUT", "TRANSFER_IN", "ADJUSTMENT"] as const;
|
||||
export type MovementType = (typeof MOVEMENT_TYPES)[number];
|
||||
|
||||
export interface IStockMovement extends Document {
|
||||
_id: Types.ObjectId;
|
||||
businessId: Types.ObjectId;
|
||||
branchId: Types.ObjectId;
|
||||
productId: Types.ObjectId;
|
||||
type: MovementType;
|
||||
quantity: number; // signed: + adds stock to the branch, - removes it
|
||||
refId: string; // the document that caused it (transaction, purchase, transfer, adjustment)
|
||||
note: string | null;
|
||||
recordedBy: Types.ObjectId | null;
|
||||
createdAt: Date; // authoritative — server clock
|
||||
}
|
||||
|
||||
/**
|
||||
* The stock ledger. A branch's stock of a product is the SUM of its
|
||||
* movements — there is no separately stored balance that could drift out
|
||||
* of step with history.
|
||||
*
|
||||
* Every movement names the document that caused it, and (type, refId) is
|
||||
* unique. Writing a movement is therefore idempotent: replaying an offline
|
||||
* sale, retrying a transfer, or a second M-Pesa callback can never deduct
|
||||
* or add the same stock twice. A transfer writes two movements with the
|
||||
* same refId but different types (TRANSFER_OUT, TRANSFER_IN).
|
||||
*/
|
||||
const stockMovementSchema = new Schema<IStockMovement>(
|
||||
{
|
||||
businessId: { type: Schema.Types.ObjectId, ref: "Business", required: true },
|
||||
branchId: { type: Schema.Types.ObjectId, ref: "Branch", required: true },
|
||||
productId: { type: Schema.Types.ObjectId, ref: "Product", required: true },
|
||||
type: { type: String, enum: MOVEMENT_TYPES, required: true },
|
||||
quantity: { type: Number, required: true },
|
||||
refId: { type: String, required: true },
|
||||
note: { type: String, default: null, trim: true },
|
||||
recordedBy: { type: Schema.Types.ObjectId, ref: "User", default: null },
|
||||
},
|
||||
{ timestamps: { createdAt: true, updatedAt: false } }
|
||||
);
|
||||
|
||||
stockMovementSchema.index({ type: 1, refId: 1 }, { unique: true });
|
||||
// Stock-level aggregation and the per-branch movement history.
|
||||
stockMovementSchema.index({ businessId: 1, branchId: 1, productId: 1 });
|
||||
stockMovementSchema.index({ businessId: 1, branchId: 1, createdAt: -1 });
|
||||
|
||||
export const StockMovement =
|
||||
(models.StockMovement as Model<IStockMovement>) ||
|
||||
model<IStockMovement>("StockMovement", stockMovementSchema);
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Schema, model, models, Model, Types, Document } from "mongoose";
|
||||
|
||||
export interface IStockTransfer extends Document {
|
||||
_id: Types.ObjectId;
|
||||
businessId: Types.ObjectId;
|
||||
fromBranchId: Types.ObjectId;
|
||||
toBranchId: Types.ObjectId;
|
||||
productId: Types.ObjectId;
|
||||
quantity: number;
|
||||
clientUuid: string; // idempotency key from the form, so a double-submit moves stock once
|
||||
note: string | null;
|
||||
recordedBy: Types.ObjectId;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* An inter-branch stock transfer. The stock itself moves through two
|
||||
* StockMovement rows (TRANSFER_OUT at the source, TRANSFER_IN at the
|
||||
* destination) whose refId is this transfer's id.
|
||||
*/
|
||||
const stockTransferSchema = new Schema<IStockTransfer>(
|
||||
{
|
||||
businessId: { type: Schema.Types.ObjectId, ref: "Business", required: true },
|
||||
fromBranchId: { type: Schema.Types.ObjectId, ref: "Branch", required: true },
|
||||
toBranchId: { type: Schema.Types.ObjectId, ref: "Branch", required: true },
|
||||
productId: { type: Schema.Types.ObjectId, ref: "Product", required: true },
|
||||
quantity: { type: Number, required: true, min: 1 },
|
||||
clientUuid: { type: String, required: true },
|
||||
note: { type: String, default: null, trim: true },
|
||||
recordedBy: { type: Schema.Types.ObjectId, ref: "User", required: true },
|
||||
},
|
||||
{ timestamps: { createdAt: true, updatedAt: false } }
|
||||
);
|
||||
|
||||
stockTransferSchema.index({ businessId: 1, clientUuid: 1 }, { unique: true });
|
||||
stockTransferSchema.index({ businessId: 1, createdAt: -1 });
|
||||
|
||||
export const StockTransfer =
|
||||
(models.StockTransfer as Model<IStockTransfer>) ||
|
||||
model<IStockTransfer>("StockTransfer", stockTransferSchema);
|
||||
@@ -9,7 +9,7 @@ export interface ITransaction extends Document {
|
||||
branchId: Types.ObjectId;
|
||||
staffId: Types.ObjectId;
|
||||
customerName: string | null;
|
||||
customerPhone: string;
|
||||
customerPhone: string | null; // optional for cash sales; required for M-Pesa
|
||||
productId: Types.ObjectId;
|
||||
sizeLiters: number; // snapshotted at sale time
|
||||
quantity: number;
|
||||
@@ -26,8 +26,15 @@ export interface ITransaction extends Document {
|
||||
resultDesc: string | null;
|
||||
};
|
||||
|
||||
clientUuid: string; // idempotency key generated on-device
|
||||
clientUuid: string; // idempotency key for this line: `${saleId}:${lineIndex}` for cash sales
|
||||
saleId: string | null; // groups the lines of one multi-item sale (the device's sale UUID)
|
||||
lineIndex: number;
|
||||
syncedFromOffline: boolean;
|
||||
// What the device showed and collected per unit. The server price stays
|
||||
// authoritative; a difference (e.g. the price changed while the device
|
||||
// was offline) is kept and flagged rather than silently overwritten.
|
||||
clientUnitPrice: number | null;
|
||||
priceMismatch: boolean;
|
||||
|
||||
// TAMPER PREVENTION: this is what the device *claimed* the time was when
|
||||
// the sale happened — informational only, e.g. for offline-queue
|
||||
@@ -50,7 +57,7 @@ const transactionSchema = new Schema<ITransaction>(
|
||||
branchId: { type: Schema.Types.ObjectId, ref: "Branch", required: true },
|
||||
staffId: { type: Schema.Types.ObjectId, ref: "User", required: true },
|
||||
customerName: { type: String, default: null, trim: true },
|
||||
customerPhone: { type: String, required: true },
|
||||
customerPhone: { type: String, default: null },
|
||||
productId: { type: Schema.Types.ObjectId, ref: "Product", required: true },
|
||||
sizeLiters: { type: Number, required: true },
|
||||
quantity: { type: Number, required: true, min: 1 },
|
||||
@@ -73,7 +80,11 @@ const transactionSchema = new Schema<ITransaction>(
|
||||
},
|
||||
|
||||
clientUuid: { type: String, required: true },
|
||||
saleId: { type: String, default: null },
|
||||
lineIndex: { type: Number, default: 0 },
|
||||
syncedFromOffline: { type: Boolean, default: false },
|
||||
clientUnitPrice: { type: Number, default: null },
|
||||
priceMismatch: { type: Boolean, default: false },
|
||||
clientSubmittedAt: { type: Date, default: null },
|
||||
},
|
||||
{ timestamps: true } // createdAt/updatedAt set from the server's Date.now(), not client input
|
||||
@@ -92,6 +103,7 @@ transactionSchema.index({ clientUuid: 1 }, { unique: true });
|
||||
transactionSchema.index({ branchId: 1, createdAt: -1 });
|
||||
transactionSchema.index({ businessId: 1, createdAt: -1 });
|
||||
transactionSchema.index({ paymentStatus: 1 });
|
||||
transactionSchema.index({ businessId: 1, saleId: 1 });
|
||||
|
||||
export const Transaction =
|
||||
(models.Transaction as Model<ITransaction>) ||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// Shared between the terminal's offline queue and POST /api/transactions/cash.
|
||||
|
||||
/** Largest batch the offline queue sends in one request. */
|
||||
export const MAX_SALES_PER_REQUEST = 50;
|
||||
|
||||
/** Largest number of product lines in one sale. */
|
||||
export const MAX_LINES_PER_SALE = 20;
|
||||
|
||||
export type SaleResult =
|
||||
| { clientUuid: string; status: "saved" | "duplicate"; amountTotal: number; priceMismatch: boolean }
|
||||
| { clientUuid: string; status: "rejected"; error: string };
|
||||
Reference in New Issue
Block a user