Address the 11 October test report findings
The initial test report (run before the pilot-readiness changes) raised seven findings and a retest plan. This closes the ones still open. - F-01: a business on its free trial may run 2 active branches whatever its tier, so an owner can try transfers and per-branch stock. Only active branches count towards any limit. - F-06: owners can rename branches and deactivate/reactivate them from the Branches page. A branch can only be deactivated once it holds no stock and no active staff; its history stays in every report, and it leaves every picker. - F-04: the Products page lists deactivated products under a toggle with Reactivate. Deactivating warns about stock still on hand, which stays on the Stock page so it can be transferred or counted out. - F-05: products carry a unit (L, ml, kg, g, pcs, tray, pack) instead of everything being litres. - CAT-12: product prices must be above zero and names are unique per business, ignoring case. - F-03: a reversed report period is refused by the page and the API, and the page labels which period the cards show. Report dates are Nairobi business days. - F-07: cost of goods sold is units sold x average buying price. Stock bought in the period is reported separately, with a cash surplus line, so unsold stock no longer shows as a loss. - STA-04: staff and new branch managers can be invited with a one-time, 7-day link; the person sets their own password. Managers can issue a new link for their own cashiers. - OFF-02 / POS-02: the till shows each product's stock and deducts every sale immediately, online or offline; it warns before selling more than the recorded stock, and has a Clear sale button. - npm run backfill:stock turns purchases recorded before the stock ledger into stock, so existing tenants (and the report's ZERRO fixtures) start from what they bought. tests/retest-plan.test.ts runs the report's completion and retest plan and checks every balance and total it predicts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+156
-27
@@ -27,6 +27,12 @@ export default function BranchesPage() {
|
||||
const [mgrEmail, setMgrEmail] = useState("");
|
||||
const [mgrPhone, setMgrPhone] = useState("");
|
||||
const [mgrPassword, setMgrPassword] = useState("");
|
||||
const [inviteLink, setInviteLink] = useState<{ name: string; url: string } | null>(null);
|
||||
|
||||
// Inline rename.
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [editName, setEditName] = useState("");
|
||||
const [editCity, setEditCity] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
@@ -52,7 +58,7 @@ export default function BranchesPage() {
|
||||
}, []);
|
||||
|
||||
async function loadBranches() {
|
||||
const result = await apiFetch<{ branches: Branch[] }>("/api/branches");
|
||||
const result = await apiFetch<{ branches: Branch[] }>("/api/branches?includeInactive=1");
|
||||
setBranches(result.branches);
|
||||
}
|
||||
|
||||
@@ -71,28 +77,29 @@ export default function BranchesPage() {
|
||||
};
|
||||
|
||||
if (withManager) {
|
||||
if (!mgrName.trim() || !mgrEmail.trim() || !mgrPhone.trim() || !mgrPassword) {
|
||||
setError("Fill in the manager's name, email, phone and password — or switch off the manager login.");
|
||||
if (!mgrName.trim() || !mgrEmail.trim() || !mgrPhone.trim()) {
|
||||
setError("Fill in the manager's name, email and phone — or switch off the manager login.");
|
||||
return;
|
||||
}
|
||||
if (mgrPassword.length < 8) {
|
||||
setError("The manager password must be at least 8 characters.");
|
||||
if (mgrPassword && mgrPassword.length < 8) {
|
||||
setError("The manager password must be at least 8 characters, or leave it blank to send an invite link.");
|
||||
return;
|
||||
}
|
||||
body.manager = {
|
||||
name: mgrName.trim(),
|
||||
email: mgrEmail.trim(),
|
||||
phoneNumber: mgrPhone.trim(),
|
||||
password: mgrPassword,
|
||||
password: mgrPassword || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
await apiFetch("/api/branches", {
|
||||
const result = await apiFetch<{ inviteUrl?: string | null }>("/api/branches", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
setInviteLink(result.inviteUrl ? { name: mgrName.trim(), url: result.inviteUrl } : null);
|
||||
if (withManager) {
|
||||
show(branchName.trim() + " created with manager login for " + mgrEmail.trim(), "success");
|
||||
} else {
|
||||
@@ -113,6 +120,46 @@ export default function BranchesPage() {
|
||||
setSaving(false);
|
||||
}
|
||||
|
||||
async function saveRename(id: string) {
|
||||
if (!editName.trim() || !editCity.trim()) {
|
||||
setError("Enter both a branch name and a city.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await apiFetch("/api/branches/" + id, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ branchName: editName.trim(), locationCity: editCity.trim() }),
|
||||
});
|
||||
show("Branch updated", "success");
|
||||
setEditingId(null);
|
||||
await loadBranches();
|
||||
} catch (err) {
|
||||
show(err instanceof ApiError ? err.message : "Could not update branch", "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleBranch(b: Branch) {
|
||||
const deactivating = b.isActive !== false;
|
||||
if (
|
||||
deactivating &&
|
||||
!window.confirm(
|
||||
`Deactivate ${b.branchName}? Its sales and stock history stay in your reports, but it takes no new staff, stock or sales. You can reactivate it later.`
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await apiFetch("/api/branches/" + b._id, { method: "PATCH", body: JSON.stringify({ isActive: !deactivating }) });
|
||||
show(`${b.branchName} ${deactivating ? "deactivated" : "reactivated"}`, "success");
|
||||
await loadBranches();
|
||||
} catch (err) {
|
||||
// e.g. stock or staff still at the branch, or the plan's branch limit.
|
||||
const message = err instanceof ApiError ? err.message : "Could not update branch";
|
||||
setError(message);
|
||||
show(message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
if (!me) {
|
||||
return (
|
||||
<main className="min-h-screen bg-sand-50 pb-12">
|
||||
@@ -150,6 +197,33 @@ export default function BranchesPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{inviteLink && (
|
||||
<div className="rounded-xl2 border border-confirm-500/30 bg-confirm-500/10 p-4 text-sm text-depth-800">
|
||||
<p className="font-medium">Send this link to {inviteLink.name} so they can set their password.</p>
|
||||
<p className="mt-1 text-xs text-depth-500">It works once and expires in 7 days. You can make a new one from Staff.</p>
|
||||
<input
|
||||
readOnly
|
||||
value={inviteLink.url}
|
||||
onFocus={(e) => e.target.select()}
|
||||
aria-label="Invite link"
|
||||
className="mt-3 w-full rounded-lg border border-depth-200 bg-white px-3 py-2 font-mono text-xs"
|
||||
/>
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
<a
|
||||
href={`https://wa.me/?text=${encodeURIComponent(`Set your Vessel password here: ${inviteLink.url}`)}`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="rounded-lg border border-depth-200 bg-white px-3 py-1.5 text-xs font-semibold text-depth-700"
|
||||
>
|
||||
Share on WhatsApp
|
||||
</a>
|
||||
<button onClick={() => setInviteLink(null)} className="px-2 text-xs text-depth-500 underline">
|
||||
Done
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<SkeletonList rows={3} />
|
||||
) : (
|
||||
@@ -175,22 +249,77 @@ export default function BranchesPage() {
|
||||
/>
|
||||
) : (
|
||||
<ul className="divide-y divide-depth-100">
|
||||
{branches.map((b) => (
|
||||
<li key={b._id} className="flex items-center justify-between px-4 py-3 animate-fade-up">
|
||||
<div>
|
||||
<p className="font-medium text-depth-900">{b.branchName}</p>
|
||||
<p className="text-xs text-depth-500">{b.locationCity}</p>
|
||||
</div>
|
||||
<span
|
||||
className={
|
||||
"rounded-full px-2.5 py-1 text-xs font-medium " +
|
||||
(b.managerId ? "bg-confirm-500/15 text-confirm-600" : "bg-cash-500/15 text-cash-600")
|
||||
}
|
||||
>
|
||||
{b.managerId ? "Has manager" : "No manager yet"}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
{branches.map((b) => {
|
||||
const active = b.isActive !== false;
|
||||
return (
|
||||
<li key={b._id} className="flex flex-wrap items-center justify-between gap-3 px-4 py-3 animate-fade-up">
|
||||
{editingId === b._id ? (
|
||||
<div className="flex flex-1 flex-wrap items-center gap-2">
|
||||
<input
|
||||
autoFocus
|
||||
value={editName}
|
||||
onChange={(e) => setEditName(e.target.value)}
|
||||
aria-label="Branch name"
|
||||
className="min-w-0 flex-1 rounded-lg border border-depth-200 px-2 py-1 text-sm"
|
||||
/>
|
||||
<input
|
||||
value={editCity}
|
||||
onChange={(e) => setEditCity(e.target.value)}
|
||||
aria-label="City"
|
||||
className="min-w-0 flex-1 rounded-lg border border-depth-200 px-2 py-1 text-sm"
|
||||
/>
|
||||
<button onClick={() => saveRename(b._id)} className="rounded-lg bg-flow-500 px-3 py-1 text-sm font-semibold text-depth-950">
|
||||
Save
|
||||
</button>
|
||||
<button onClick={() => setEditingId(null)} className="text-sm text-depth-500 underline">
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className={active ? "" : "opacity-50"}>
|
||||
<p className="font-medium text-depth-900">
|
||||
{b.branchName}
|
||||
{!active && <span className="ml-2 text-xs font-normal text-alert-600">Deactivated</span>}
|
||||
</p>
|
||||
<p className="text-xs text-depth-500">{b.locationCity}</p>
|
||||
</div>
|
||||
)}
|
||||
{editingId !== b._id && (
|
||||
<div className="flex shrink-0 flex-wrap items-center gap-2">
|
||||
{active && (
|
||||
<span
|
||||
className={
|
||||
"rounded-full px-2.5 py-1 text-xs font-medium " +
|
||||
(b.managerId ? "bg-confirm-500/15 text-confirm-600" : "bg-cash-500/15 text-cash-600")
|
||||
}
|
||||
>
|
||||
{b.managerId ? "Has manager" : "No manager yet"}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingId(b._id);
|
||||
setEditName(b.branchName);
|
||||
setEditCity(b.locationCity);
|
||||
}}
|
||||
className="rounded-lg border border-depth-200 px-2.5 py-1 text-xs font-medium text-depth-700"
|
||||
>
|
||||
Rename
|
||||
</button>
|
||||
<button
|
||||
onClick={() => toggleBranch(b)}
|
||||
className={
|
||||
"rounded-lg border px-2.5 py-1 text-xs font-medium " +
|
||||
(active ? "border-alert-500/40 text-alert-600" : "border-confirm-500/40 text-confirm-600")
|
||||
}
|
||||
>
|
||||
{active ? "Deactivate" : "Reactivate"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
@@ -238,8 +367,8 @@ export default function BranchesPage() {
|
||||
Create this branch's manager login now
|
||||
</span>
|
||||
<span className="block text-xs text-depth-500">
|
||||
The manager signs in with this email & password, then adds their own delivery
|
||||
staff. You can leave this off and assign a manager later from Staff.
|
||||
Leave the password blank to get an invite link the manager uses to choose their own.
|
||||
They then add their own delivery staff. You can also assign a manager later from Staff.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
@@ -285,14 +414,14 @@ export default function BranchesPage() {
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-medium text-depth-600" htmlFor="mgr-password">
|
||||
Temporary password
|
||||
Password (optional)
|
||||
</label>
|
||||
<input
|
||||
id="mgr-password"
|
||||
type="text"
|
||||
value={mgrPassword}
|
||||
onChange={(e) => setMgrPassword(e.target.value)}
|
||||
placeholder="At least 8 characters"
|
||||
placeholder="Blank = send an invite link"
|
||||
className="tap-target w-full rounded-xl border border-depth-200 bg-white px-3"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -146,7 +146,7 @@ export default function AdminDashboardPage() {
|
||||
Stock
|
||||
</Link>
|
||||
<Link href="/admin/products" className="tap-target flex items-center rounded-xl2 bg-white/10 px-4 text-sm font-medium text-white hover:bg-white/15">
|
||||
Sizes
|
||||
Products
|
||||
</Link>
|
||||
<Link href="/admin/staff" className="tap-target flex items-center rounded-xl2 bg-white/10 px-4 text-sm font-medium text-white hover:bg-white/15">
|
||||
Staff
|
||||
|
||||
@@ -4,11 +4,11 @@ import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { apiFetch, ApiError } from "@/lib/api";
|
||||
import { AuthUser, Product } from "@/lib/types";
|
||||
import { AuthUser, Product, StockLevel } from "@/lib/types";
|
||||
import { PRODUCT_UNITS, UNIT_LABELS, formatSize, type ProductUnit } from "@/lib/units";
|
||||
import { useToast } from "@/components/ui/Toast";
|
||||
import { SkeletonList } from "@/components/ui/Skeleton";
|
||||
import EmptyState from "@/components/ui/EmptyState";
|
||||
import ConfirmButton from "@/components/ui/ConfirmButton";
|
||||
|
||||
export default function ProductsPage() {
|
||||
const router = useRouter();
|
||||
@@ -21,7 +21,9 @@ export default function ProductsPage() {
|
||||
|
||||
const [label, setLabel] = useState("");
|
||||
const [sizeLiters, setSizeLiters] = useState("");
|
||||
const [unit, setUnit] = useState<ProductUnit>("L");
|
||||
const [unitPrice, setUnitPrice] = useState("");
|
||||
const [showInactive, setShowInactive] = useState(false);
|
||||
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [editPrice, setEditPrice] = useState("");
|
||||
@@ -50,7 +52,7 @@ export default function ProductsPage() {
|
||||
}, []);
|
||||
|
||||
async function loadProducts() {
|
||||
const result = await apiFetch<{ products: Product[] }>("/api/products");
|
||||
const result = await apiFetch<{ products: Product[] }>("/api/products?includeInactive=1");
|
||||
setProducts(result.products);
|
||||
}
|
||||
|
||||
@@ -60,8 +62,8 @@ export default function ProductsPage() {
|
||||
|
||||
const size = parseFloat(sizeLiters);
|
||||
const price = parseFloat(unitPrice);
|
||||
if (!label.trim() || !Number.isFinite(size) || size <= 0 || !Number.isFinite(price) || price < 0) {
|
||||
setError("Enter a valid label, size, and price.");
|
||||
if (!label.trim() || !Number.isFinite(size) || size <= 0 || !Number.isFinite(price) || price <= 0) {
|
||||
setError("Enter a label, a size above zero and a price above zero.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -69,7 +71,7 @@ export default function ProductsPage() {
|
||||
try {
|
||||
await apiFetch("/api/products", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ label: label.trim(), sizeLiters: size, unitPrice: price, sortOrder: products.length }),
|
||||
body: JSON.stringify({ label: label.trim(), sizeLiters: size, unit, unitPrice: price, sortOrder: products.length }),
|
||||
});
|
||||
show(label.trim() + " added to the catalog", "success");
|
||||
setLabel("");
|
||||
@@ -87,8 +89,8 @@ export default function ProductsPage() {
|
||||
async function handlePriceUpdate(id: string) {
|
||||
const price = parseFloat(editPrice);
|
||||
const threshold = parseInt(editThreshold, 10);
|
||||
if (!Number.isFinite(price) || price < 0) {
|
||||
setError("Enter a valid price.");
|
||||
if (!Number.isFinite(price) || price <= 0) {
|
||||
setError("Enter a price above zero.");
|
||||
return;
|
||||
}
|
||||
if (!Number.isInteger(threshold) || threshold < 0) {
|
||||
@@ -113,6 +115,24 @@ export default function ProductsPage() {
|
||||
}
|
||||
|
||||
async function handleToggleActive(product: Product) {
|
||||
if (product.isActive) {
|
||||
// Tell the owner what happens to stock still on hand before it goes.
|
||||
let held: StockLevel[] = [];
|
||||
try {
|
||||
const res = await apiFetch<{ levels: StockLevel[] }>("/api/stock");
|
||||
held = res.levels.filter((l) => l.productId === product._id && l.quantity !== 0);
|
||||
} catch {
|
||||
// Offline or failed: still ask for confirmation below.
|
||||
}
|
||||
const stockNote =
|
||||
held.length > 0
|
||||
? `\n\nStill in stock: ${held.map((l) => `${l.branchName} ${l.quantity}`).join(", ")}. ` +
|
||||
"It stays on the Stock page, where it can be transferred or counted out, but cashiers can no longer sell it."
|
||||
: "";
|
||||
if (!window.confirm(`Deactivate ${product.label}? It disappears from the till and new purchases. Past sales and purchases are kept.${stockNote}`)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
await apiFetch("/api/products/" + product._id, {
|
||||
method: "PATCH",
|
||||
@@ -145,7 +165,7 @@ export default function ProductsPage() {
|
||||
<div className="mx-auto flex max-w-3xl items-center justify-between">
|
||||
<div>
|
||||
<p className="text-xs uppercase tracking-wide text-flow-400">Vessel</p>
|
||||
<h1 className="font-display text-xl font-bold">Jerrycan sizes & pricing</h1>
|
||||
<h1 className="font-display text-xl font-bold">Products & pricing</h1>
|
||||
</div>
|
||||
<Link href="/admin/dashboard" className="tap-target flex items-center rounded-xl2 bg-white/10 px-4 text-sm font-medium text-white hover:bg-white/15">
|
||||
← Dashboard
|
||||
@@ -166,6 +186,17 @@ export default function ProductsPage() {
|
||||
it from new sales without touching past transactions.
|
||||
{!canEdit && " Only the business owner can change products and prices."}
|
||||
</p>
|
||||
{products.some((p) => !p.isActive) && (
|
||||
<label className="mt-2 flex cursor-pointer items-center gap-2 text-xs text-depth-600">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showInactive}
|
||||
onChange={(e) => setShowInactive(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-depth-300"
|
||||
/>
|
||||
Show deactivated products ({products.filter((p) => !p.isActive).length})
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{products.length === 0 ? (
|
||||
@@ -177,11 +208,11 @@ export default function ProductsPage() {
|
||||
/>
|
||||
) : (
|
||||
<ul className="divide-y divide-depth-100">
|
||||
{products.map((p) => (
|
||||
{products.filter((p) => showInactive || p.isActive).map((p) => (
|
||||
<li key={p._id} className="flex items-center justify-between gap-3 px-4 py-3 animate-fade-up">
|
||||
<div>
|
||||
<p className="font-medium text-depth-900">
|
||||
{p.label} <span className="text-depth-500">· {p.sizeLiters}L</span>
|
||||
{p.label} <span className="text-depth-500">· {formatSize(p.sizeLiters, p.unit)}</span>
|
||||
</p>
|
||||
{!canEdit ? (
|
||||
<p className="mt-0.5 font-mono text-sm text-depth-600">
|
||||
@@ -235,13 +266,12 @@ export default function ProductsPage() {
|
||||
{p.isActive ? "Active" : "Inactive"}
|
||||
</span>
|
||||
{!canEdit ? null : p.isActive ? (
|
||||
<ConfirmButton
|
||||
label="Deactivate"
|
||||
confirmLabel="Deactivate"
|
||||
variant="danger"
|
||||
onConfirm={() => handleToggleActive(p)}
|
||||
className="rounded-lg border border-depth-200 px-3 py-1.5 text-sm font-medium text-depth-700"
|
||||
/>
|
||||
<button
|
||||
onClick={() => handleToggleActive(p)}
|
||||
className="rounded-lg border border-alert-500/40 px-3 py-1.5 text-sm font-medium text-alert-600"
|
||||
>
|
||||
Deactivate
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => handleToggleActive(p)}
|
||||
@@ -259,8 +289,8 @@ export default function ProductsPage() {
|
||||
|
||||
{canEdit && (
|
||||
<form onSubmit={handleAdd} className="rounded-xl2 bg-white p-4 shadow-soft">
|
||||
<h2 className="mb-3 font-display font-semibold text-depth-900">Add a new size</h2>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
|
||||
<h2 className="mb-3 font-display font-semibold text-depth-900">Add a product</h2>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-4">
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-medium text-depth-600" htmlFor="label">
|
||||
Label
|
||||
@@ -269,19 +299,31 @@ export default function ProductsPage() {
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-medium text-depth-600" htmlFor="size">
|
||||
Size (litres)
|
||||
Size
|
||||
</label>
|
||||
<input id="size" type="number" min="0" step="0.1" value={sizeLiters} onChange={(e) => setSizeLiters(e.target.value)} placeholder="10" className="tap-target w-full rounded-xl border border-depth-200 px-3" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-medium text-depth-600" htmlFor="unit">
|
||||
Unit
|
||||
</label>
|
||||
<select id="unit" value={unit} onChange={(e) => setUnit(e.target.value as ProductUnit)} className="tap-target w-full rounded-xl border border-depth-200 px-3">
|
||||
{PRODUCT_UNITS.map((u) => (
|
||||
<option key={u} value={u}>
|
||||
{UNIT_LABELS[u]} ({u})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-medium text-depth-600" htmlFor="price">
|
||||
Price (KES)
|
||||
</label>
|
||||
<input id="price" type="number" min="0" step="0.01" value={unitPrice} onChange={(e) => setUnitPrice(e.target.value)} placeholder="110" className="tap-target w-full rounded-xl border border-depth-200 px-3" />
|
||||
<input id="price" type="number" min="0.01" step="0.01" value={unitPrice} onChange={(e) => setUnitPrice(e.target.value)} placeholder="110" className="tap-target w-full rounded-xl border border-depth-200 px-3" />
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" disabled={saving} className="tap-target mt-4 w-full rounded-xl2 bg-flow-500 font-display font-semibold text-depth-950 disabled:opacity-60 sm:w-auto sm:px-8">
|
||||
{saving ? "Adding…" : "Add size"}
|
||||
{saving ? "Adding…" : "Add product"}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
@@ -15,16 +15,22 @@ interface ProfitReport {
|
||||
cashTotal: number;
|
||||
mpesaTotal: number;
|
||||
salesCount: number;
|
||||
costOfGoods: number;
|
||||
purchaseCount: number;
|
||||
unitsSold: number;
|
||||
costOfGoodsSold: number;
|
||||
unitsWithoutCost: number;
|
||||
grossProfit: number;
|
||||
expenses: number;
|
||||
expenseCount: number;
|
||||
netProfit: number;
|
||||
stockPurchases: number;
|
||||
purchaseCount: number;
|
||||
cashSurplus: number;
|
||||
}
|
||||
|
||||
/** YYYY-MM-DD in the device's own calendar (the owner's business day). */
|
||||
function isoDay(d: Date): string {
|
||||
return d.toISOString().slice(0, 10);
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||||
}
|
||||
|
||||
export default function ReportsPage() {
|
||||
@@ -35,6 +41,10 @@ export default function ReportsPage() {
|
||||
const [report, setReport] = useState<ProfitReport | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [fetching, setFetching] = useState(false);
|
||||
const [rangeError, setRangeError] = useState<string | null>(null);
|
||||
// The period the cards currently show, so a failed or invalid run can
|
||||
// never be mistaken for the new period.
|
||||
const [shown, setShown] = useState<{ from: string; to: string } | null>(null);
|
||||
|
||||
const monthStart = new Date();
|
||||
monthStart.setDate(1);
|
||||
@@ -75,22 +85,27 @@ export default function ReportsPage() {
|
||||
}, []);
|
||||
|
||||
async function runReport(forcedBranch?: string) {
|
||||
if (!from || !to) {
|
||||
setRangeError("Choose both a start and an end date.");
|
||||
return;
|
||||
}
|
||||
if (from > to) {
|
||||
setRangeError("The start date must be on or before the end date.");
|
||||
return;
|
||||
}
|
||||
setRangeError(null);
|
||||
setFetching(true);
|
||||
try {
|
||||
const b = forcedBranch ?? branchId;
|
||||
const params = new URLSearchParams();
|
||||
const params = new URLSearchParams({ fromDate: from, toDate: to });
|
||||
if (b && b !== "ALL") params.set("branchId", b);
|
||||
if (from) params.set("from", new Date(from).toISOString());
|
||||
// include the whole "to" day
|
||||
if (to) {
|
||||
const end = new Date(to);
|
||||
end.setHours(23, 59, 59, 999);
|
||||
params.set("to", end.toISOString());
|
||||
}
|
||||
const result = await apiFetch<ProfitReport>("/api/reports/profit?" + params.toString());
|
||||
setReport(result);
|
||||
setShown({ from, to });
|
||||
} catch (err) {
|
||||
show(err instanceof ApiError ? err.message : "Could not load report", "error");
|
||||
const message = err instanceof ApiError ? err.message : "Could not load report";
|
||||
setRangeError(message);
|
||||
show(message, "error");
|
||||
}
|
||||
setFetching(false);
|
||||
}
|
||||
@@ -99,23 +114,27 @@ export default function ReportsPage() {
|
||||
if (!report) return;
|
||||
const rows: [string, string | number][] = [
|
||||
["Metric", "Value (KES)"],
|
||||
["Range from", report.range.from.slice(0, 10)],
|
||||
["Range to", report.range.to.slice(0, 10)],
|
||||
["From", shown?.from ?? ""],
|
||||
["To", shown?.to ?? ""],
|
||||
["Revenue", report.revenue],
|
||||
[" Cash", report.cashTotal],
|
||||
[" M-Pesa", report.mpesaTotal],
|
||||
["Sales count", report.salesCount],
|
||||
["Cost of goods", report.costOfGoods],
|
||||
["Units sold", report.unitsSold],
|
||||
["Cost of goods sold (average purchase cost)", report.costOfGoodsSold],
|
||||
["Units sold with no purchase cost on record", report.unitsWithoutCost],
|
||||
["Gross profit", report.grossProfit],
|
||||
["Expenses", report.expenses],
|
||||
["Estimated net profit", report.netProfit],
|
||||
["Stock purchased in period (cash spent)", report.stockPurchases],
|
||||
["Cash surplus (sales - stock purchased - expenses)", report.cashSurplus],
|
||||
];
|
||||
const csv = rows.map((r) => r.map((c) => `"${String(c).replace(/"/g, '""')}"`).join(",")).join("\n");
|
||||
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `vessel-profit-${report.range.from.slice(0, 10)}_${report.range.to.slice(0, 10)}.csv`;
|
||||
a.download = `vessel-profit-${shown?.from}_${shown?.to}.csv`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
@@ -179,6 +198,7 @@ export default function ReportsPage() {
|
||||
<input
|
||||
type="date"
|
||||
value={from}
|
||||
max={to || undefined}
|
||||
onChange={(e) => setFrom(e.target.value)}
|
||||
className="tap-target w-full rounded-xl border border-depth-200 px-3"
|
||||
/>
|
||||
@@ -188,6 +208,7 @@ export default function ReportsPage() {
|
||||
<input
|
||||
type="date"
|
||||
value={to}
|
||||
min={from || undefined}
|
||||
onChange={(e) => setTo(e.target.value)}
|
||||
className="tap-target w-full rounded-xl border border-depth-200 px-3"
|
||||
/>
|
||||
@@ -202,8 +223,16 @@ export default function ReportsPage() {
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{rangeError && <p className="mt-3 text-sm text-alert-600">{rangeError}</p>}
|
||||
</div>
|
||||
|
||||
{report && shown && (
|
||||
<p className="text-sm text-depth-600">
|
||||
Showing {shown.from === shown.to ? shown.from : `${shown.from} to ${shown.to}`}
|
||||
{rangeError ? " (the dates above were not run)" : ""}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{report && (
|
||||
<>
|
||||
{/* Profit cards */}
|
||||
@@ -216,14 +245,17 @@ export default function ReportsPage() {
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-xl2 bg-white p-5 shadow-soft">
|
||||
<p className="text-xs uppercase tracking-wide text-depth-500">Cost of goods</p>
|
||||
<p className="mt-1 font-display text-2xl font-bold text-depth-900">{money(report.costOfGoods)}</p>
|
||||
<p className="mt-1 text-xs text-depth-500">{report.purchaseCount} purchases in range</p>
|
||||
<p className="text-xs uppercase tracking-wide text-depth-500">Cost of goods sold</p>
|
||||
<p className="mt-1 font-display text-2xl font-bold text-depth-900">{money(report.costOfGoodsSold)}</p>
|
||||
<p className="mt-1 text-xs text-depth-500">
|
||||
{report.unitsSold} units sold x average buying price
|
||||
{report.unitsWithoutCost > 0 && ` · ${report.unitsWithoutCost} units have no purchase cost on record`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-xl2 bg-white p-5 shadow-soft">
|
||||
<p className="text-xs uppercase tracking-wide text-depth-500">Gross profit</p>
|
||||
<p className="mt-1 font-display text-2xl font-bold text-flow-700">{money(report.grossProfit)}</p>
|
||||
<p className="mt-1 text-xs text-depth-500">Revenue − cost of goods</p>
|
||||
<p className="mt-1 text-xs text-depth-500">Revenue − cost of goods sold</p>
|
||||
</div>
|
||||
<div className="rounded-xl2 bg-white p-5 shadow-soft">
|
||||
<p className="text-xs uppercase tracking-wide text-depth-500">Expenses</p>
|
||||
@@ -244,6 +276,22 @@ export default function ReportsPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div className="rounded-xl2 bg-white p-5 shadow-soft">
|
||||
<p className="text-xs uppercase tracking-wide text-depth-500">Stock purchased</p>
|
||||
<p className="mt-1 font-display text-2xl font-bold text-depth-900">{money(report.stockPurchases)}</p>
|
||||
<p className="mt-1 text-xs text-depth-500">
|
||||
Cash spent on stock in this period ({report.purchaseCount} purchases). Unsold stock is not a cost
|
||||
until it is sold.
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-xl2 bg-white p-5 shadow-soft">
|
||||
<p className="text-xs uppercase tracking-wide text-depth-500">Cash surplus</p>
|
||||
<p className="mt-1 font-display text-2xl font-bold text-depth-900">{money(report.cashSurplus)}</p>
|
||||
<p className="mt-1 text-xs text-depth-500">Sales − stock purchased − expenses</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-xl2 border border-depth-200 bg-sand-100 px-4 py-3">
|
||||
<p className="text-xs text-depth-500">
|
||||
Management / profit overview — a decision aid, not full accounting software.
|
||||
|
||||
@@ -17,6 +17,7 @@ interface StaffMember {
|
||||
phoneNumber: string;
|
||||
email: string;
|
||||
isActive: boolean;
|
||||
invitePending?: boolean;
|
||||
}
|
||||
|
||||
const roleBadgeStyles: Record<UserRole, string> = {
|
||||
@@ -42,6 +43,10 @@ export default function StaffPage() {
|
||||
const [phoneNumber, setPhoneNumber] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
// Inviting is the default: the person sets their own password, so the
|
||||
// owner never has to know or pass on anyone's password.
|
||||
const [setPasswordNow, setSetPasswordNow] = useState(false);
|
||||
const [inviteLink, setInviteLink] = useState<{ name: string; url: string } | null>(null);
|
||||
|
||||
const isSuperAdmin = me?.role === "SUPER_ADMIN";
|
||||
|
||||
@@ -75,14 +80,14 @@ export default function StaffPage() {
|
||||
if (!name.trim() || !phoneNumber.trim()) return "Name and phone number are required.";
|
||||
if (role !== "SUPER_ADMIN" && isSuperAdmin && !branchId) return "Choose which branch this account belongs to.";
|
||||
if (!email.trim()) return "Email is required — every account signs in with email and password.";
|
||||
if (password.length < 8) return "Password must be at least 8 characters.";
|
||||
if (setPasswordNow && password.length < 8) return "Password must be at least 8 characters.";
|
||||
return null;
|
||||
}
|
||||
|
||||
async function submitCreate() {
|
||||
setSaving(true);
|
||||
try {
|
||||
await apiFetch("/api/users", {
|
||||
const result = await apiFetch<{ inviteUrl: string | null }>("/api/users", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
name: name.trim(),
|
||||
@@ -90,10 +95,11 @@ export default function StaffPage() {
|
||||
branchId: role !== "SUPER_ADMIN" && isSuperAdmin ? branchId : undefined,
|
||||
phoneNumber,
|
||||
email,
|
||||
password,
|
||||
password: setPasswordNow ? password : undefined,
|
||||
}),
|
||||
});
|
||||
show(name.trim() + " added as " + role.replace("_", " ").toLowerCase(), "success");
|
||||
setInviteLink(result.inviteUrl ? { name: name.trim(), url: result.inviteUrl } : null);
|
||||
setName("");
|
||||
setBranchId("");
|
||||
setPhoneNumber("");
|
||||
@@ -115,6 +121,26 @@ export default function StaffPage() {
|
||||
return s.role === "DELIVERY" && s.branchId === me.branchId;
|
||||
}
|
||||
|
||||
async function newInviteLink(s: StaffMember) {
|
||||
try {
|
||||
const result = await apiFetch<{ inviteUrl: string }>("/api/users/" + s._id + "/invite", { method: "POST" });
|
||||
setInviteLink({ name: s.name, url: result.inviteUrl });
|
||||
show("New invite link created. The old link no longer works.", "success");
|
||||
} catch (err) {
|
||||
show(err instanceof ApiError ? err.message : "Could not create an invite link", "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function copyInvite() {
|
||||
if (!inviteLink) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(inviteLink.url);
|
||||
show("Invite link copied", "success");
|
||||
} catch {
|
||||
show("Could not copy - select the link and copy it manually", "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleActive(s: StaffMember) {
|
||||
const next = !s.isActive;
|
||||
if (!next && !window.confirm(`Deactivate ${s.name}? They will be signed out of every device and cannot sign in again until reactivated.`)) {
|
||||
@@ -191,6 +217,36 @@ export default function StaffPage() {
|
||||
<div className="rounded-xl2 border border-alert-500/30 bg-alert-500/10 px-4 py-3 text-sm text-alert-600">{error}</div>
|
||||
)}
|
||||
|
||||
{inviteLink && (
|
||||
<div className="rounded-xl2 border border-confirm-500/30 bg-confirm-500/10 p-4 text-sm text-depth-800">
|
||||
<p className="font-medium">Send this link to {inviteLink.name} so they can set their password.</p>
|
||||
<p className="mt-1 text-xs text-depth-500">It works once and expires in 7 days. Anyone with the link can claim the account, so send it only to them.</p>
|
||||
<input
|
||||
readOnly
|
||||
value={inviteLink.url}
|
||||
onFocus={(e) => e.target.select()}
|
||||
aria-label="Invite link"
|
||||
className="mt-3 w-full rounded-lg border border-depth-200 bg-white px-3 py-2 font-mono text-xs"
|
||||
/>
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
<button onClick={copyInvite} className="rounded-lg bg-flow-500 px-3 py-1.5 text-xs font-semibold text-depth-950">
|
||||
Copy link
|
||||
</button>
|
||||
<a
|
||||
href={`https://wa.me/?text=${encodeURIComponent(`Set your Vessel password here: ${inviteLink.url}`)}`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="rounded-lg border border-depth-200 bg-white px-3 py-1.5 text-xs font-semibold text-depth-700"
|
||||
>
|
||||
Share on WhatsApp
|
||||
</a>
|
||||
<button onClick={() => setInviteLink(null)} className="px-2 text-xs text-depth-500 underline">
|
||||
Done
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-xl2 bg-white shadow-soft">
|
||||
<div className="border-b border-depth-100 px-4 py-3">
|
||||
<h2 className="font-display font-semibold text-depth-900">Team</h2>
|
||||
@@ -211,6 +267,9 @@ export default function StaffPage() {
|
||||
<p className="font-medium text-depth-900">
|
||||
{s.name}
|
||||
{!s.isActive && <span className="ml-2 text-xs font-normal text-alert-600">Deactivated</span>}
|
||||
{s.isActive && s.invitePending && (
|
||||
<span className="ml-2 text-xs font-normal text-cash-700">Invite pending</span>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-depth-500">
|
||||
{s.email}
|
||||
@@ -221,6 +280,14 @@ export default function StaffPage() {
|
||||
<span className={"rounded-full px-2.5 py-1 text-xs font-medium " + roleBadgeStyles[s.role]}>
|
||||
{s.role.replace("_", " ")}
|
||||
</span>
|
||||
{canManage(s) && s.isActive && s.invitePending && (
|
||||
<button
|
||||
onClick={() => newInviteLink(s)}
|
||||
className="rounded-lg border border-depth-200 px-2.5 py-1 text-xs font-medium text-depth-700"
|
||||
>
|
||||
New link
|
||||
</button>
|
||||
)}
|
||||
{canManage(s) && (
|
||||
<button
|
||||
onClick={() => toggleActive(s)}
|
||||
@@ -289,12 +356,29 @@ export default function StaffPage() {
|
||||
<label className="mb-1 block text-xs font-medium text-depth-600">Email (used to sign in)</label>
|
||||
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} className="tap-target w-full rounded-xl border border-depth-200 px-3" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-medium text-depth-600">Password (used to sign in)</label>
|
||||
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} className="tap-target w-full rounded-xl border border-depth-200 px-3" />
|
||||
</div>
|
||||
{setPasswordNow && (
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-medium text-depth-600">Password (used to sign in)</label>
|
||||
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} className="tap-target w-full rounded-xl border border-depth-200 px-3" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<label className="mt-3 flex cursor-pointer items-start gap-2 text-sm text-depth-700">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={setPasswordNow}
|
||||
onChange={(e) => setSetPasswordNow(e.target.checked)}
|
||||
className="mt-0.5 h-4 w-4 rounded border-depth-300"
|
||||
/>
|
||||
<span>
|
||||
Set their password myself instead of sending an invite link
|
||||
<span className="block text-xs text-depth-500">
|
||||
By default you get a one-time link to send them, and they choose their own password.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
{confirmSuperAdmin ? (
|
||||
<div className="mt-4 rounded-xl2 border border-alert-500/30 bg-alert-500/10 p-3">
|
||||
<p className="mb-2 text-sm text-alert-700">
|
||||
@@ -324,7 +408,7 @@ export default function StaffPage() {
|
||||
disabled={saving}
|
||||
className="tap-target mt-4 w-full rounded-xl2 bg-flow-500 font-display font-semibold text-depth-950 disabled:opacity-60 sm:w-auto sm:px-8"
|
||||
>
|
||||
{saving ? "Adding…" : "Add staff member"}
|
||||
{saving ? "Adding…" : setPasswordNow ? "Add staff member" : "Add and create invite link"}
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
|
||||
@@ -73,7 +73,9 @@ export default function StockPage() {
|
||||
}
|
||||
const [br, pr] = await Promise.all([
|
||||
apiFetch<{ branches: Branch[] }>("/api/branches"),
|
||||
apiFetch<{ products: Product[] }>("/api/products"),
|
||||
// Deactivated products too: their remaining stock can still be
|
||||
// transferred or counted out.
|
||||
apiFetch<{ products: Product[] }>("/api/products?includeInactive=1"),
|
||||
]);
|
||||
setBranches(br.branches);
|
||||
setProducts(pr.products);
|
||||
@@ -252,7 +254,10 @@ export default function StockPage() {
|
||||
<ul className="divide-y divide-depth-100">
|
||||
{group.rows.map((l) => (
|
||||
<li key={l.productId} className="flex items-center justify-between gap-3 px-4 py-2.5">
|
||||
<span className="min-w-0 truncate text-sm text-depth-800">{l.productLabel}</span>
|
||||
<span className="min-w-0 truncate text-sm text-depth-800">
|
||||
{l.productLabel}
|
||||
{!l.productActive && <span className="ml-1 text-xs text-depth-500">(deactivated)</span>}
|
||||
</span>
|
||||
<span className="flex shrink-0 items-center gap-2">
|
||||
<span className={"font-mono text-sm font-semibold " + (l.quantity < 0 ? "text-alert-600" : "text-depth-900")}>
|
||||
{l.quantity}
|
||||
@@ -347,6 +352,7 @@ export default function StockPage() {
|
||||
{products.map((p) => (
|
||||
<option key={p._id} value={p._id}>
|
||||
{p.label}
|
||||
{p.isActive ? "" : " (deactivated)"}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Business } from "@/lib/server/models/Business";
|
||||
import { getAuth } from "@/lib/server/auth";
|
||||
import { isPlatformAdminEmail } from "@/lib/server/platform";
|
||||
import { isMpesaEnabled } from "@/lib/server/env";
|
||||
import { TIERS, type TierId, type SubscriptionStatus } from "@/lib/tiers";
|
||||
import { TIERS, effectiveMaxBranches, type TierId, type SubscriptionStatus } from "@/lib/tiers";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -47,7 +47,7 @@ export async function GET(req: NextRequest) {
|
||||
status,
|
||||
trialEndsAt: business?.trialEndsAt ?? null,
|
||||
currentPeriodEnd: business?.currentPeriodEnd ?? null,
|
||||
maxBranches: tierDef.maxBranches,
|
||||
maxBranches: effectiveMaxBranches(tier, status),
|
||||
maxUsers: tierDef.maxUsers,
|
||||
},
|
||||
features: { mpesa: isMpesaEnabled() },
|
||||
|
||||
@@ -29,7 +29,7 @@ const DEFAULT_CATALOG = [
|
||||
{ label: "5L Jerrycan", sizeLiters: 5, unit: "L", category: "Water", unitPrice: 60, sortOrder: 1 },
|
||||
{ label: "10L Jerrycan", sizeLiters: 10, unit: "L", category: "Water", unitPrice: 110, sortOrder: 2 },
|
||||
{ label: "20L Jerrycan", sizeLiters: 20, unit: "L", category: "Water", unitPrice: 200, sortOrder: 3 },
|
||||
{ label: "Tray of Eggs (30)", sizeLiters: 30, unit: "pcs", category: "Eggs", unitPrice: 400, sortOrder: 4 },
|
||||
{ label: "Tray of Eggs (30)", sizeLiters: 1, unit: "tray", category: "Eggs", unitPrice: 400, sortOrder: 4 },
|
||||
{ label: "Half Tray (15)", sizeLiters: 15, unit: "pcs", category: "Eggs", unitPrice: 210, sortOrder: 5 },
|
||||
{ label: "Single Egg", sizeLiters: 1, unit: "pcs", category: "Eggs", unitPrice: 15, sortOrder: 6 },
|
||||
];
|
||||
|
||||
@@ -3,7 +3,10 @@ import { z } from "zod";
|
||||
import { isValidObjectId } from "mongoose";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { User } from "@/lib/server/models/User";
|
||||
import { authorize } from "@/lib/server/auth";
|
||||
import { branchLimitError } from "@/lib/server/subscription";
|
||||
import { getStockLevels } from "@/lib/server/stock";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
@@ -11,10 +14,21 @@ const updateSchema = z
|
||||
.object({
|
||||
branchName: z.string().trim().min(1).max(120).optional(),
|
||||
locationCity: z.string().trim().min(1).max(120).optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
})
|
||||
.refine((v) => Object.keys(v).length > 0, { message: "No fields to update" });
|
||||
|
||||
// PATCH /api/branches/:id — owner renames a branch or changes its city.
|
||||
/**
|
||||
* PATCH /api/branches/:id — owner renames a branch, or deactivates /
|
||||
* reactivates it. This is how an owner "removes" a branch: nothing is
|
||||
* deleted, so its sales, purchases and stock history stay in every report.
|
||||
*
|
||||
* A branch can only be deactivated once it is empty, so nothing is left
|
||||
* stranded in it:
|
||||
* - no stock on hand (transfer it out or count it to zero first), and
|
||||
* - no active staff (move or deactivate them first).
|
||||
* Reactivating counts against the plan's branch limit again.
|
||||
*/
|
||||
export async function PATCH(req: NextRequest, { params }: { params: { id: string } }) {
|
||||
await connectDb();
|
||||
const gate = authorize(req, ["SUPER_ADMIN"]);
|
||||
@@ -28,10 +42,36 @@ export async function PATCH(req: NextRequest, { params }: { params: { id: string
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: parsed.error.issues[0]?.message ?? "Invalid request" }, { status: 400 });
|
||||
}
|
||||
const { isActive, ...details } = parsed.data;
|
||||
|
||||
const branch = await Branch.findOneAndUpdate({ _id: params.id, businessId: auth.businessId }, parsed.data, {
|
||||
new: true,
|
||||
}).lean();
|
||||
const branch = await Branch.findOne({ _id: params.id, businessId: auth.businessId });
|
||||
if (!branch) return NextResponse.json({ error: "Branch not found" }, { status: 404 });
|
||||
const wasActive = branch.isActive !== false;
|
||||
|
||||
if (isActive === false && wasActive) {
|
||||
const stock = (await getStockLevels(auth.businessId, branch._id)).filter((l) => l.quantity !== 0);
|
||||
if (stock.length > 0) {
|
||||
const list = stock.map((l) => `${l.quantity} x ${l.productLabel}`).join(", ");
|
||||
return NextResponse.json(
|
||||
{ error: `Move or count out this branch's stock first (${list}).`, stock },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
const staff = await User.countDocuments({ businessId: auth.businessId, branchId: branch._id, isActive: true });
|
||||
if (staff > 0) {
|
||||
return NextResponse.json(
|
||||
{ error: `${staff} active staff member(s) still work at this branch. Move or deactivate them first.` },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
}
|
||||
if (isActive === true && !wasActive) {
|
||||
const limitError = await branchLimitError(auth.businessId);
|
||||
if (limitError) return NextResponse.json({ error: limitError }, { status: 403 });
|
||||
}
|
||||
|
||||
Object.assign(branch, details);
|
||||
if (isActive !== undefined) branch.isActive = isActive;
|
||||
await branch.save();
|
||||
return NextResponse.json({ branch });
|
||||
}
|
||||
|
||||
@@ -2,11 +2,12 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { ACTIVE_BRANCH, Branch } from "@/lib/server/models/Branch";
|
||||
import { User } from "@/lib/server/models/User";
|
||||
import { authorize, getAuth } from "@/lib/server/auth";
|
||||
import { normalizeKenyanPhone } from "@/lib/server/phone";
|
||||
import { branchLimitError, userLimitError, loadTier } from "@/lib/server/subscription";
|
||||
import { issueInvite, unusablePasswordHash } from "@/lib/server/invites";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -17,7 +18,11 @@ export async function GET(req: NextRequest) {
|
||||
if (!auth) return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
|
||||
|
||||
if (auth.role === "SUPER_ADMIN") {
|
||||
const branches = await Branch.find({ businessId: auth.businessId }).sort({ branchName: 1 }).lean();
|
||||
// Deactivated branches are only listed on request (the Branches page),
|
||||
// so every picker elsewhere offers active branches only.
|
||||
const includeInactive = req.nextUrl.searchParams.get("includeInactive") === "1";
|
||||
const filter = includeInactive ? { businessId: auth.businessId } : { businessId: auth.businessId, ...ACTIVE_BRANCH };
|
||||
const branches = await Branch.find(filter).sort({ branchName: 1 }).lean();
|
||||
return NextResponse.json({ branches });
|
||||
}
|
||||
if (!auth.branchId) return NextResponse.json({ branches: [] });
|
||||
@@ -33,7 +38,8 @@ const createSchema = z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
email: z.string().email(),
|
||||
phoneNumber: z.string().min(9).max(15),
|
||||
password: z.string().min(8, "Password must be at least 8 characters"),
|
||||
// Omit to invite: the response carries a one-time link for the manager.
|
||||
password: z.string().min(8, "Password must be at least 8 characters").optional(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
@@ -53,7 +59,7 @@ export async function POST(req: NextRequest) {
|
||||
const businessId = auth.businessId;
|
||||
|
||||
const tier = await loadTier(businessId);
|
||||
const branchErr = await branchLimitError(businessId, tier);
|
||||
const branchErr = await branchLimitError(businessId);
|
||||
if (branchErr) return NextResponse.json({ error: branchErr }, { status: 403 });
|
||||
|
||||
let managerPhone: string | null = null;
|
||||
@@ -80,8 +86,8 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
if (manager && managerPhone) {
|
||||
try {
|
||||
const passwordHash = await bcrypt.hash(manager.password, 12);
|
||||
const managerUser = await User.create({
|
||||
const passwordHash = manager.password ? await bcrypt.hash(manager.password, 12) : await unusablePasswordHash();
|
||||
const managerUser = new User({
|
||||
businessId,
|
||||
name: manager.name,
|
||||
role: "BRANCH_MANAGER",
|
||||
@@ -90,10 +96,12 @@ export async function POST(req: NextRequest) {
|
||||
email: manager.email.toLowerCase(),
|
||||
passwordHash,
|
||||
});
|
||||
const inviteUrl = manager.password ? null : issueInvite(managerUser, req);
|
||||
await managerUser.save();
|
||||
branch.managerId = managerUser._id;
|
||||
await branch.save();
|
||||
return NextResponse.json(
|
||||
{ branch, manager: { id: managerUser._id, name: managerUser.name, email: managerUser.email } },
|
||||
{ branch, manager: { id: managerUser._id, name: managerUser.name, email: managerUser.email }, inviteUrl },
|
||||
{ status: 201 }
|
||||
);
|
||||
} catch (err: any) {
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { User } from "@/lib/server/models/User";
|
||||
import { Business } from "@/lib/server/models/Business";
|
||||
import { hashInviteToken } from "@/lib/server/invites";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
async function findInvitee(token: string) {
|
||||
if (!token || token.length > 100) return null;
|
||||
const user = await User.findOne({ inviteTokenHash: hashInviteToken(token), isActive: true });
|
||||
if (!user || !user.inviteExpiresAt || user.inviteExpiresAt.getTime() < Date.now()) return null;
|
||||
return user;
|
||||
}
|
||||
|
||||
const INVALID = { error: "This invite link is invalid or has expired. Ask your manager for a new one." };
|
||||
|
||||
// GET /api/invites/:token — who the invite is for, so the page can greet them.
|
||||
export async function GET(_req: NextRequest, { params }: { params: { token: string } }) {
|
||||
await connectDb();
|
||||
const user = await findInvitee(params.token);
|
||||
if (!user) return NextResponse.json(INVALID, { status: 404 });
|
||||
const business = await Business.findById(user.businessId).select("name").lean();
|
||||
return NextResponse.json({ name: user.name, email: user.email, businessName: business?.name ?? null });
|
||||
}
|
||||
|
||||
const acceptSchema = z.object({ password: z.string().min(8, "Password must be at least 8 characters") });
|
||||
|
||||
// POST /api/invites/:token — set the password; the link then stops working.
|
||||
export async function POST(req: NextRequest, { params }: { params: { token: string } }) {
|
||||
await connectDb();
|
||||
const parsed = acceptSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: parsed.error.issues[0]?.message ?? "Invalid request" }, { status: 400 });
|
||||
}
|
||||
const user = await findInvitee(params.token);
|
||||
if (!user) return NextResponse.json(INVALID, { status: 404 });
|
||||
|
||||
user.passwordHash = await bcrypt.hash(parsed.data.password, 12);
|
||||
user.inviteTokenHash = null;
|
||||
user.inviteExpiresAt = null;
|
||||
user.failedLoginAttempts = 0;
|
||||
user.lockedUntil = null;
|
||||
await user.save();
|
||||
return NextResponse.json({ ok: true, email: user.email });
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { Business } from "@/lib/server/models/Business";
|
||||
import { User } from "@/lib/server/models/User";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { requirePlatformAdmin } from "@/lib/server/platform";
|
||||
import { TIERS, type TierId } from "@/lib/tiers";
|
||||
import { TIERS, effectiveMaxBranches, type TierId, type SubscriptionStatus } from "@/lib/tiers";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -28,6 +28,7 @@ export async function GET(req: NextRequest) {
|
||||
{ $group: { _id: "$businessId", count: { $sum: 1 } } },
|
||||
]),
|
||||
Branch.aggregate<{ _id: unknown; count: number }>([
|
||||
{ $match: { isActive: { $ne: false } } },
|
||||
{ $group: { _id: "$businessId", count: { $sum: 1 } } },
|
||||
]),
|
||||
]);
|
||||
@@ -58,7 +59,7 @@ export async function GET(req: NextRequest) {
|
||||
userCount: userMap.get(String(b._id)) ?? 0,
|
||||
branchCount: branchMap.get(String(b._id)) ?? 0,
|
||||
maxUsers: TIERS[tier].maxUsers,
|
||||
maxBranches: TIERS[tier].maxBranches,
|
||||
maxBranches: effectiveMaxBranches(tier, (b.subscriptionStatus as SubscriptionStatus) ?? "TRIALING"),
|
||||
owner: owner
|
||||
? { name: owner.name, email: owner.email, phoneNumber: owner.phoneNumber }
|
||||
: null,
|
||||
|
||||
@@ -4,13 +4,16 @@ import { connectDb } from "@/lib/server/db";
|
||||
import { Product } from "@/lib/server/models/Product";
|
||||
import { authorize } from "@/lib/server/auth";
|
||||
import { isValidObjectId } from "mongoose";
|
||||
import { PRODUCT_UNITS } from "@/lib/units";
|
||||
import { labelTakenError } from "@/lib/server/products";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
const updateSchema = z.object({
|
||||
label: z.string().trim().min(1).max(60).optional(),
|
||||
sizeLiters: z.number().positive().max(1000).optional(),
|
||||
unitPrice: z.number().nonnegative().optional(),
|
||||
unit: z.enum(PRODUCT_UNITS).optional(),
|
||||
unitPrice: z.number().positive("Price must be more than zero").optional(),
|
||||
sortOrder: z.number().int().optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
lowStockThreshold: z.number().int().min(0).max(1_000_000).optional(),
|
||||
@@ -33,6 +36,11 @@ export async function PATCH(req: NextRequest, { params }: { params: { id: string
|
||||
return NextResponse.json({ error: "No fields to update" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (parsed.data.label) {
|
||||
const taken = await labelTakenError(auth.businessId, parsed.data.label, params.id);
|
||||
if (taken) return NextResponse.json({ error: taken }, { status: 409 });
|
||||
}
|
||||
|
||||
const product = await Product.findOneAndUpdate(
|
||||
{ _id: params.id, businessId: auth.businessId },
|
||||
parsed.data,
|
||||
|
||||
@@ -2,12 +2,15 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { Product, BranchPricing } from "@/lib/server/models/Product";
|
||||
import { authorize } from "@/lib/server/auth";
|
||||
import { authorize, MANAGERS } from "@/lib/server/auth";
|
||||
import { PRODUCT_UNITS } from "@/lib/units";
|
||||
import { labelTakenError } from "@/lib/server/products";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// GET /api/products — the tenant's active catalogue. For branch-scoped
|
||||
// GET /api/products — the tenant's active catalogue (?includeInactive=1
|
||||
// adds deactivated products, for managers and owners). For branch-scoped
|
||||
// staff the price returned is the price THEIR branch charges (the branch
|
||||
// override when one exists), so the terminal shows exactly what the
|
||||
// server will record.
|
||||
@@ -17,7 +20,10 @@ export async function GET(req: NextRequest) {
|
||||
if (!gate.ok) return gate.response;
|
||||
const auth = gate.auth;
|
||||
|
||||
const products = await Product.find({ businessId: auth.businessId, isActive: true }).sort({ sortOrder: 1 }).lean();
|
||||
const includeInactive =
|
||||
req.nextUrl.searchParams.get("includeInactive") === "1" && MANAGERS.includes(auth.role);
|
||||
const filter = includeInactive ? { businessId: auth.businessId } : { businessId: auth.businessId, isActive: true };
|
||||
const products = await Product.find(filter).sort({ sortOrder: 1 }).lean();
|
||||
if (auth.branchId) {
|
||||
const overrides = await BranchPricing.find({ businessId: auth.businessId, branchId: auth.branchId }).lean();
|
||||
const priceByProduct = new Map(overrides.map((o) => [o.productId.toString(), o.unitPrice]));
|
||||
@@ -31,9 +37,9 @@ export async function GET(req: NextRequest) {
|
||||
const createSchema = z.object({
|
||||
label: z.string().trim().min(1).max(60),
|
||||
sizeLiters: z.number().positive().max(1000),
|
||||
unit: z.string().trim().min(1).max(12).optional(),
|
||||
unit: z.enum(PRODUCT_UNITS).optional(),
|
||||
category: z.string().trim().min(1).max(40).optional(),
|
||||
unitPrice: z.number().nonnegative(),
|
||||
unitPrice: z.number().positive("Price must be more than zero"),
|
||||
sortOrder: z.number().int().optional(),
|
||||
lowStockThreshold: z.number().int().min(0).max(1_000_000).optional(),
|
||||
});
|
||||
@@ -51,6 +57,8 @@ export async function POST(req: NextRequest) {
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: parsed.error.issues[0]?.message ?? "Invalid request" }, { status: 400 });
|
||||
}
|
||||
const taken = await labelTakenError(auth.businessId, parsed.data.label);
|
||||
if (taken) return NextResponse.json({ error: taken }, { status: 409 });
|
||||
const product = await Product.create({ ...parsed.data, businessId: auth.businessId });
|
||||
return NextResponse.json({ product }, { status: 201 });
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { Purchase } from "@/lib/server/models/Purchase";
|
||||
import { Product } from "@/lib/server/models/Product";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { ACTIVE_BRANCH, 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";
|
||||
@@ -91,7 +91,7 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
// The target branch MUST belong to this tenant.
|
||||
const branchDoc = await Branch.findOne({ _id: branchId, businessId: auth.businessId }).lean();
|
||||
const branchDoc = await Branch.findOne({ _id: branchId, businessId: auth.businessId, ...ACTIVE_BRANCH }).lean();
|
||||
if (!branchDoc) {
|
||||
return NextResponse.json({ error: "Branch not found in your business" }, { status: 404 });
|
||||
}
|
||||
|
||||
@@ -1,21 +1,32 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import mongoose from "mongoose";
|
||||
import mongoose, { Types } from "mongoose";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { Transaction } from "@/lib/server/models/Transaction";
|
||||
import { Purchase } from "@/lib/server/models/Purchase";
|
||||
import { Expense } from "@/lib/server/models/Expense";
|
||||
import { authorize, badRequest, branchParam, MANAGERS } from "@/lib/server/auth";
|
||||
import { startOfMonthNairobi } from "@/lib/server/businessDay";
|
||||
import { dayRangeNairobi, isBusinessDate, startOfMonthNairobi } from "@/lib/server/businessDay";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Management / profit overview — NOT full accounting.
|
||||
// Revenue = sum of SUCCESS sales in range
|
||||
// Cost of Goods= sum of purchase cost in range (stock bought in)
|
||||
// Gross Profit = Revenue - Cost of Goods
|
||||
// Expenses = sum of operating expenses in range
|
||||
// Net Profit = Gross Profit - Expenses
|
||||
/**
|
||||
* GET /api/reports/profit?branchId=&fromDate=YYYY-MM-DD&toDate=YYYY-MM-DD
|
||||
*
|
||||
* Management overview, NOT accounting (full accounting is out of the PRD's scope).
|
||||
* Revenue SUCCESS sales in the period
|
||||
* Cost of goods sold units sold x that product's average purchase cost
|
||||
* (all purchases up to the end of the period)
|
||||
* Gross profit revenue - cost of goods sold
|
||||
* Expenses operating expenses in the period
|
||||
* Net profit gross profit - expenses
|
||||
* Shown separately, because buying stock is not the same as using it:
|
||||
* Stock purchased cash spent on stock in the period
|
||||
* Cash surplus revenue - stock purchased - expenses
|
||||
*
|
||||
* Dates are Nairobi business days, inclusive. `from`/`to` (ISO instants)
|
||||
* are still accepted for older clients.
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
await connectDb();
|
||||
// Revenue, costs and profit are owner/manager information, never a cashier's.
|
||||
@@ -28,63 +39,111 @@ export async function GET(req: NextRequest) {
|
||||
if (!scope.ok) return scope.response;
|
||||
const branchId = scope.branchId;
|
||||
|
||||
// Default range: start of the current business month (EAT) -> now.
|
||||
const now = new Date();
|
||||
const from = url.searchParams.get("from") ? new Date(url.searchParams.get("from")!) : startOfMonthNairobi(now);
|
||||
const to = url.searchParams.get("to") ? new Date(url.searchParams.get("to")!) : now;
|
||||
if (Number.isNaN(from.getTime()) || Number.isNaN(to.getTime())) return badRequest("Invalid from/to date");
|
||||
const range = parseRange(url.searchParams);
|
||||
if ("error" in range) return badRequest(range.error);
|
||||
const { from, to } = range;
|
||||
|
||||
const branchObjId = branchId ? new mongoose.Types.ObjectId(branchId) : null;
|
||||
const businessObjId = new mongoose.Types.ObjectId(auth.businessId);
|
||||
const dateMatch = { createdAt: { $gte: from, $lte: to } };
|
||||
const branchObjId = branchId ? new mongoose.Types.ObjectId(branchId) : null;
|
||||
const inPeriod = { businessId: businessObjId, createdAt: { $gte: from, $lt: to }, ...(branchObjId ? { branchId: branchObjId } : {}) };
|
||||
|
||||
const salesMatch: Record<string, unknown> = { ...dateMatch, businessId: businessObjId, paymentStatus: "SUCCESS" };
|
||||
if (branchObjId) salesMatch.branchId = branchObjId;
|
||||
|
||||
const costMatch: Record<string, unknown> = { ...dateMatch, businessId: businessObjId };
|
||||
if (branchObjId) costMatch.branchId = branchObjId;
|
||||
|
||||
const [salesAgg, purchaseAgg, expenseAgg] = await Promise.all([
|
||||
Transaction.aggregate([
|
||||
{ $match: salesMatch },
|
||||
const [salesByProduct, avgCosts, purchaseAgg, expenseAgg] = await Promise.all([
|
||||
Transaction.aggregate<{
|
||||
_id: Types.ObjectId;
|
||||
revenue: number;
|
||||
cashTotal: number;
|
||||
mpesaTotal: number;
|
||||
units: number;
|
||||
lines: number;
|
||||
}>([
|
||||
{ $match: { ...inPeriod, paymentStatus: "SUCCESS" } },
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
_id: "$productId",
|
||||
revenue: { $sum: "$amountTotal" },
|
||||
cashTotal: { $sum: { $cond: [{ $eq: ["$paymentMethod", "CASH"] }, "$amountTotal", 0] } },
|
||||
mpesaTotal: { $sum: { $cond: [{ $eq: ["$paymentMethod", "MPESA"] }, "$amountTotal", 0] } },
|
||||
salesCount: { $sum: 1 },
|
||||
units: { $sum: "$quantity" },
|
||||
lines: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
]),
|
||||
Purchase.aggregate([
|
||||
{ $match: costMatch },
|
||||
{ $group: { _id: null, costOfGoods: { $sum: "$totalCost" }, purchaseCount: { $sum: 1 } } },
|
||||
// Average buying price per product across the business (suppliers
|
||||
// charge every branch alike), using everything bought up to period end.
|
||||
Purchase.aggregate<{ _id: Types.ObjectId; cost: number; qty: number }>([
|
||||
{ $match: { businessId: businessObjId, productId: { $ne: null }, createdAt: { $lt: to } } },
|
||||
{ $group: { _id: "$productId", cost: { $sum: "$totalCost" }, qty: { $sum: "$quantity" } } },
|
||||
]),
|
||||
Expense.aggregate([
|
||||
{ $match: costMatch },
|
||||
{ $group: { _id: null, expenses: { $sum: "$amount" }, expenseCount: { $sum: 1 } } },
|
||||
Purchase.aggregate<{ total: number; count: number }>([
|
||||
{ $match: inPeriod },
|
||||
{ $group: { _id: null, total: { $sum: "$totalCost" }, count: { $sum: 1 } } },
|
||||
]),
|
||||
Expense.aggregate<{ total: number; count: number }>([
|
||||
{ $match: inPeriod },
|
||||
{ $group: { _id: null, total: { $sum: "$amount" }, count: { $sum: 1 } } },
|
||||
]),
|
||||
]);
|
||||
|
||||
const revenue = salesAgg[0]?.revenue ?? 0;
|
||||
const costOfGoods = purchaseAgg[0]?.costOfGoods ?? 0;
|
||||
const expenses = expenseAgg[0]?.expenses ?? 0;
|
||||
const grossProfit = revenue - costOfGoods;
|
||||
const netProfit = grossProfit - expenses;
|
||||
const avgCost = new Map(avgCosts.filter((c) => c.qty > 0).map((c) => [c._id.toString(), c.cost / c.qty]));
|
||||
let revenue = 0, cashTotal = 0, mpesaTotal = 0, salesCount = 0, unitsSold = 0, unitsWithoutCost = 0, costOfGoodsSold = 0;
|
||||
for (const s of salesByProduct) {
|
||||
revenue += s.revenue;
|
||||
cashTotal += s.cashTotal;
|
||||
mpesaTotal += s.mpesaTotal;
|
||||
salesCount += s.lines;
|
||||
unitsSold += s.units;
|
||||
const unitCost = avgCost.get(s._id.toString());
|
||||
if (unitCost === undefined) unitsWithoutCost += s.units;
|
||||
else costOfGoodsSold += s.units * unitCost;
|
||||
}
|
||||
costOfGoodsSold = Math.round(costOfGoodsSold * 100) / 100;
|
||||
|
||||
const stockPurchases = purchaseAgg[0]?.total ?? 0;
|
||||
const expenses = expenseAgg[0]?.total ?? 0;
|
||||
const grossProfit = Math.round((revenue - costOfGoodsSold) * 100) / 100;
|
||||
|
||||
return NextResponse.json({
|
||||
scope: branchId ? "branch" : "global",
|
||||
range: { from: from.toISOString(), to: to.toISOString() },
|
||||
revenue,
|
||||
cashTotal: salesAgg[0]?.cashTotal ?? 0,
|
||||
mpesaTotal: salesAgg[0]?.mpesaTotal ?? 0,
|
||||
salesCount: salesAgg[0]?.salesCount ?? 0,
|
||||
costOfGoods,
|
||||
purchaseCount: purchaseAgg[0]?.purchaseCount ?? 0,
|
||||
cashTotal,
|
||||
mpesaTotal,
|
||||
salesCount,
|
||||
unitsSold,
|
||||
costOfGoodsSold,
|
||||
// Units sold of products never bought through Purchases: their cost
|
||||
// is unknown, so gross profit overstates by their cost.
|
||||
unitsWithoutCost,
|
||||
grossProfit,
|
||||
expenses,
|
||||
expenseCount: expenseAgg[0]?.expenseCount ?? 0,
|
||||
netProfit,
|
||||
expenseCount: expenseAgg[0]?.count ?? 0,
|
||||
netProfit: Math.round((grossProfit - expenses) * 100) / 100,
|
||||
stockPurchases,
|
||||
purchaseCount: purchaseAgg[0]?.count ?? 0,
|
||||
cashSurplus: Math.round((revenue - stockPurchases - expenses) * 100) / 100,
|
||||
});
|
||||
}
|
||||
|
||||
/** The half-open UTC range [from, to) for the request, or a validation error. */
|
||||
function parseRange(params: URLSearchParams): { from: Date; to: Date } | { error: string } {
|
||||
const fromDate = params.get("fromDate");
|
||||
const toDate = params.get("toDate");
|
||||
let from: Date;
|
||||
let to: Date;
|
||||
|
||||
if (fromDate || toDate) {
|
||||
if ((fromDate && !isBusinessDate(fromDate)) || (toDate && !isBusinessDate(toDate))) {
|
||||
return { error: "Dates must be YYYY-MM-DD" };
|
||||
}
|
||||
from = fromDate ? dayRangeNairobi(fromDate).start : startOfMonthNairobi();
|
||||
to = toDate ? dayRangeNairobi(toDate).end : new Date();
|
||||
} else {
|
||||
from = params.get("from") ? new Date(params.get("from")!) : startOfMonthNairobi();
|
||||
to = params.get("to") ? new Date(params.get("to")!) : new Date();
|
||||
if (Number.isNaN(from.getTime()) || Number.isNaN(to.getTime())) return { error: "Invalid from/to date" };
|
||||
}
|
||||
|
||||
// A reversed period must not look like a period with no activity.
|
||||
if (from >= to) return { error: "The start date must be on or before the end date." };
|
||||
return { from, to };
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { ACTIVE_BRANCH, 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";
|
||||
@@ -97,7 +97,7 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
const [branchCount, product] = await Promise.all([
|
||||
Branch.countDocuments({ _id: { $in: [fromBranchId, data.toBranchId] }, businessId: auth.businessId }),
|
||||
Branch.countDocuments({ _id: { $in: [fromBranchId, data.toBranchId] }, businessId: auth.businessId, ...ACTIVE_BRANCH }),
|
||||
Product.exists({ _id: data.productId, businessId: auth.businessId }),
|
||||
]);
|
||||
if (branchCount !== 2) return NextResponse.json({ error: "Branch not found in your business" }, { status: 404 });
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { isValidObjectId } from "mongoose";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { User } from "@/lib/server/models/User";
|
||||
import { authorize, MANAGERS } from "@/lib/server/auth";
|
||||
import { issueInvite } from "@/lib/server/invites";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
/**
|
||||
* POST /api/users/:id/invite — a new invite link for someone who has not
|
||||
* accepted theirs yet (lost or expired). The previous link stops working.
|
||||
* Owners: anyone in the business. Managers: their own branch's cashiers.
|
||||
*/
|
||||
export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
|
||||
await connectDb();
|
||||
const gate = authorize(req, MANAGERS);
|
||||
if (!gate.ok) return gate.response;
|
||||
const auth = gate.auth;
|
||||
|
||||
if (!isValidObjectId(params.id)) return NextResponse.json({ error: "User not found" }, { status: 404 });
|
||||
const user = await User.findOne({ _id: params.id, businessId: auth.businessId });
|
||||
if (!user) return NextResponse.json({ error: "User not found" }, { status: 404 });
|
||||
|
||||
if (auth.role === "BRANCH_MANAGER" && !(user.role === "DELIVERY" && user.branchId?.toString() === auth.branchId)) {
|
||||
return NextResponse.json({ error: "Branch managers may only invite delivery staff in their own branch" }, { status: 403 });
|
||||
}
|
||||
if (!user.inviteExpiresAt) {
|
||||
return NextResponse.json({ error: "This person has already set their password" }, { status: 409 });
|
||||
}
|
||||
|
||||
const inviteUrl = issueInvite(user, req);
|
||||
await user.save();
|
||||
return NextResponse.json({ inviteUrl, expiresAt: user.inviteExpiresAt });
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import { isValidObjectId } from "mongoose";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { User } from "@/lib/server/models/User";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { ACTIVE_BRANCH, Branch } from "@/lib/server/models/Branch";
|
||||
import { Business } from "@/lib/server/models/Business";
|
||||
import { UserSession } from "@/lib/server/models/UserSession";
|
||||
import { authorize, MANAGERS } from "@/lib/server/auth";
|
||||
@@ -67,7 +67,7 @@ export async function PATCH(req: NextRequest, { params }: { params: { id: string
|
||||
if (target.role === "SUPER_ADMIN") {
|
||||
return NextResponse.json({ error: "Owner accounts are not tied to a branch" }, { status: 400 });
|
||||
}
|
||||
const branch = await Branch.findOne({ _id: branchId, businessId: auth.businessId }).lean();
|
||||
const branch = await Branch.findOne({ _id: branchId, businessId: auth.businessId, ...ACTIVE_BRANCH }).lean();
|
||||
if (!branch) return NextResponse.json({ error: "Branch not found in your business" }, { status: 404 });
|
||||
target.branchId = branch._id;
|
||||
}
|
||||
@@ -82,5 +82,6 @@ export async function PATCH(req: NextRequest, { params }: { params: { id: string
|
||||
|
||||
const obj = target.toObject() as unknown as Record<string, unknown>;
|
||||
delete obj.passwordHash;
|
||||
delete obj.inviteTokenHash;
|
||||
return NextResponse.json({ user: obj });
|
||||
}
|
||||
|
||||
@@ -3,11 +3,12 @@ import bcrypt from "bcryptjs";
|
||||
import { z } from "zod";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { User } from "@/lib/server/models/User";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { ACTIVE_BRANCH, Branch } from "@/lib/server/models/Branch";
|
||||
import { authorize, branchParam, MANAGERS } from "@/lib/server/auth";
|
||||
import { objectId } from "@/lib/server/validation";
|
||||
import { normalizeKenyanPhone } from "@/lib/server/phone";
|
||||
import { userLimitError, loadTier } from "@/lib/server/subscription";
|
||||
import { issueInvite, unusablePasswordHash } from "@/lib/server/invites";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -22,8 +23,11 @@ export async function GET(req: NextRequest) {
|
||||
if (!scope.ok) return scope.response;
|
||||
const filter: Record<string, unknown> = { businessId: auth.businessId };
|
||||
if (scope.branchId) filter.branchId = scope.branchId;
|
||||
const users = await User.find(filter).select("-passwordHash").sort({ name: 1 }).lean();
|
||||
return NextResponse.json({ users });
|
||||
const users = await User.find(filter).select("-passwordHash -inviteTokenHash").sort({ name: 1 }).lean();
|
||||
// invitePending: the person has not set their password yet.
|
||||
return NextResponse.json({
|
||||
users: users.map((u) => ({ ...u, invitePending: !!u.inviteExpiresAt })),
|
||||
});
|
||||
}
|
||||
|
||||
const createSchema = z.object({
|
||||
@@ -32,7 +36,9 @@ const createSchema = z.object({
|
||||
branchId: objectId.optional(),
|
||||
phoneNumber: z.string().min(9).max(15),
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8),
|
||||
// Omit the password to invite instead: the response carries a one-time
|
||||
// link the person uses to set their own password.
|
||||
password: z.string().min(8).optional(),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
@@ -63,7 +69,7 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
if (branchId) {
|
||||
const branch = await Branch.findOne({ _id: branchId, businessId: auth.businessId }).lean();
|
||||
const branch = await Branch.findOne({ _id: branchId, businessId: auth.businessId, ...ACTIVE_BRANCH }).lean();
|
||||
if (!branch) {
|
||||
return NextResponse.json({ error: "Branch not found in your business" }, { status: 404 });
|
||||
}
|
||||
@@ -81,10 +87,10 @@ export async function POST(req: NextRequest) {
|
||||
const userErr = await userLimitError(auth.businessId, tier);
|
||||
if (userErr) return NextResponse.json({ error: userErr }, { status: 403 });
|
||||
|
||||
const passwordHash = await bcrypt.hash(data.password, 12);
|
||||
const passwordHash = data.password ? await bcrypt.hash(data.password, 12) : await unusablePasswordHash();
|
||||
|
||||
try {
|
||||
const user = await User.create({
|
||||
const user = new User({
|
||||
businessId: auth.businessId,
|
||||
name: data.name,
|
||||
role: data.role,
|
||||
@@ -93,6 +99,8 @@ export async function POST(req: NextRequest) {
|
||||
email: data.email.toLowerCase(),
|
||||
passwordHash,
|
||||
});
|
||||
const inviteUrl = data.password ? null : issueInvite(user, req);
|
||||
await user.save();
|
||||
|
||||
if (data.role === "BRANCH_MANAGER" && branchId) {
|
||||
await Branch.findOneAndUpdate(
|
||||
@@ -103,7 +111,8 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
const obj: any = user.toObject();
|
||||
delete obj.passwordHash;
|
||||
return NextResponse.json({ user: obj }, { status: 201 });
|
||||
delete obj.inviteTokenHash;
|
||||
return NextResponse.json({ user: obj, inviteUrl }, { status: 201 });
|
||||
} catch (err: any) {
|
||||
if (err?.code === 11000) {
|
||||
return NextResponse.json({ error: "A user with this phone number or email already exists" }, { status: 409 });
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { apiFetch, ApiError } from "@/lib/api";
|
||||
|
||||
interface Invite {
|
||||
name: string;
|
||||
email: string;
|
||||
businessName: string | null;
|
||||
}
|
||||
|
||||
const inputClass =
|
||||
"tap-target w-full rounded-xl2 border border-depth-200 bg-white px-4 text-depth-900 shadow-sm transition focus:border-flow-500 focus:outline-none focus:ring-2 focus:ring-flow-500/25";
|
||||
|
||||
/** Where an invited staff member sets their own password. */
|
||||
export default function InvitePage() {
|
||||
const { token } = useParams<{ token: string }>();
|
||||
const router = useRouter();
|
||||
const [invite, setInvite] = useState<Invite | null>(null);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirm, setConfirm] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
apiFetch<Invite>("/api/invites/" + encodeURIComponent(token))
|
||||
.then(setInvite)
|
||||
.catch((err) => setLoadError(err instanceof ApiError ? err.message : "Could not load this invite."));
|
||||
}, [token]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
if (password.length < 8) return setError("Use at least 8 characters.");
|
||||
if (password !== confirm) return setError("The two passwords do not match.");
|
||||
setSaving(true);
|
||||
try {
|
||||
await apiFetch("/api/invites/" + encodeURIComponent(token), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
router.replace("/login?invited=1");
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : "Could not save your password.");
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-sand-50 px-5 py-10">
|
||||
<div className="w-full max-w-md rounded-3xl bg-white p-6 shadow-soft">
|
||||
{loadError ? (
|
||||
<p role="alert" className="text-sm text-alert-600">
|
||||
{loadError}
|
||||
</p>
|
||||
) : !invite ? (
|
||||
<div className="h-32 animate-pulse rounded-xl2 bg-sand-100" />
|
||||
) : (
|
||||
<>
|
||||
<p className="text-xs uppercase tracking-wide text-flow-600">{invite.businessName ?? "Vessel"}</p>
|
||||
<h1 className="mt-1 font-display text-2xl font-bold text-depth-900">Welcome, {invite.name}</h1>
|
||||
<p className="mt-2 text-sm text-depth-600">
|
||||
Choose a password. You will sign in with <strong>{invite.email}</strong> and this password.
|
||||
</p>
|
||||
<form onSubmit={handleSubmit} className="mt-6 space-y-4">
|
||||
<div>
|
||||
<label htmlFor="new-password" className="mb-1.5 block text-sm font-medium text-depth-700">
|
||||
New password
|
||||
</label>
|
||||
<input
|
||||
id="new-password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="confirm-password" className="mb-1.5 block text-sm font-medium text-depth-700">
|
||||
Confirm password
|
||||
</label>
|
||||
<input
|
||||
id="confirm-password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={confirm}
|
||||
onChange={(e) => setConfirm(e.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p role="alert" className="rounded-lg bg-alert-500/10 px-3 py-2 text-sm text-alert-600">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
className="tap-target w-full rounded-full bg-gradient-to-r from-flow-500 to-flow-700 font-display font-semibold text-white disabled:opacity-60"
|
||||
>
|
||||
{saving ? "Saving…" : "Set password"}
|
||||
</button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+11
-1
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { apiFetch, ApiError } from "@/lib/api";
|
||||
import { getDeviceId, getDeviceLabel } from "@/lib/deviceId";
|
||||
@@ -21,6 +21,11 @@ export default function LoginPage() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deviceConflict, setDeviceConflict] = useState<ActiveDevice[] | null>(null);
|
||||
const [invited, setInvited] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setInvited(new URLSearchParams(window.location.search).get("invited") === "1");
|
||||
}, []);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
@@ -174,6 +179,11 @@ export default function LoginPage() {
|
||||
<span className="font-medium text-flow-600">Forgot password?</span>
|
||||
</div>
|
||||
|
||||
{invited && !error && (
|
||||
<p className="rounded-lg bg-confirm-500/10 px-3 py-2 text-sm text-confirm-600">
|
||||
Your password is set. Sign in with your email and new password.
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="rounded-lg bg-alert-500/10 px-3 py-2 text-sm text-alert-600">
|
||||
{error}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { apiFetch, ApiError } from "@/lib/api";
|
||||
import { isValidKenyanPhone } from "@/lib/phone";
|
||||
import { AuthUser, PaymentMethod, Product } from "@/lib/types";
|
||||
import { AuthUser, PaymentMethod, Product, StockLevel } from "@/lib/types";
|
||||
import {
|
||||
dismissRejected,
|
||||
flushQueue,
|
||||
@@ -13,10 +13,11 @@ import {
|
||||
queueSale,
|
||||
registerOfflineSync,
|
||||
salesFor,
|
||||
unsyncedQuantities,
|
||||
type QueuedSale,
|
||||
type QueueOwner,
|
||||
} from "@/lib/offlineQueue";
|
||||
import { clearSession, loadSession, saveSession } from "@/lib/sessionCache";
|
||||
import { clearSession, loadSession, saveSession, type StockSnapshot } from "@/lib/sessionCache";
|
||||
import { MAX_LINES_PER_SALE } from "@/lib/syncProtocol";
|
||||
import { useToast } from "@/components/ui/Toast";
|
||||
import ProductGrid from "@/components/terminal/ProductGrid";
|
||||
@@ -51,6 +52,11 @@ export default function TerminalPage() {
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
const [productsLoading, setProductsLoading] = useState(true);
|
||||
const [cart, setCart] = useState<CartLine[]>([]);
|
||||
// Branch stock from the server, minus this phone's sales the server has
|
||||
// not counted yet — so the till deducts stock the moment a sale is
|
||||
// recorded, even offline (PRD 5.3).
|
||||
const [stockSnapshot, setStockSnapshot] = useState<StockSnapshot | null>(null);
|
||||
const [unsynced, setUnsynced] = useState<Record<string, number>>({});
|
||||
|
||||
const [showCustomer, setShowCustomer] = useState(false);
|
||||
const [customerName, setCustomerName] = useState("");
|
||||
@@ -72,8 +78,37 @@ export default function TerminalPage() {
|
||||
|
||||
const refreshCounts = useCallback(async (userId: string) => {
|
||||
setCounts(await queueCounts(userId));
|
||||
const snapshotAt = loadSession()?.stock?.fetchedAt ?? null;
|
||||
setUnsynced(unsyncedQuantities(await salesFor(userId), snapshotAt));
|
||||
}, []);
|
||||
|
||||
const refreshStock = useCallback(
|
||||
async (user: AuthUser) => {
|
||||
const fetchedAt = new Date().toISOString();
|
||||
try {
|
||||
const res = await apiFetch<{ levels: StockLevel[] }>("/api/stock");
|
||||
const snapshot: StockSnapshot = {
|
||||
byProduct: Object.fromEntries(res.levels.map((l) => [l.productId, l.quantity])),
|
||||
fetchedAt,
|
||||
};
|
||||
saveSession({ user, stock: snapshot });
|
||||
setStockSnapshot(snapshot);
|
||||
} catch {
|
||||
// Offline: keep showing the last snapshot minus local sales.
|
||||
const saved = loadSession();
|
||||
if (saved?.user.id === user.id && saved.stock) setStockSnapshot(saved.stock);
|
||||
}
|
||||
await refreshCounts(user.id);
|
||||
},
|
||||
[refreshCounts]
|
||||
);
|
||||
|
||||
const stockByProduct: Record<string, number> | null = stockSnapshot
|
||||
? Object.fromEntries(
|
||||
products.map((p) => [p._id, (stockSnapshot.byProduct[p._id] ?? 0) - (unsynced[p._id] ?? 0)])
|
||||
)
|
||||
: null;
|
||||
|
||||
// Boot: confirm the session online, or fall back to the last confirmed
|
||||
// session on this device so a cashier can keep selling with no network.
|
||||
useEffect(() => {
|
||||
@@ -106,7 +141,7 @@ export default function TerminalPage() {
|
||||
show("Offline - using this phone's saved session. Sales will sync when you're back online.", "info");
|
||||
}
|
||||
setMe(user);
|
||||
await refreshCounts(user.id);
|
||||
await refreshStock(user);
|
||||
|
||||
try {
|
||||
const productsResult = await apiFetch<{ products: Product[] }>("/api/products");
|
||||
@@ -142,7 +177,10 @@ export default function TerminalPage() {
|
||||
const unregister = registerOfflineSync({ id: me.id, businessId: me.businessId, branchId: me.branchId }, (r) => {
|
||||
setCounts((c) => ({ ...c, pending: r.pending }));
|
||||
setServerReachable(!r.offline);
|
||||
if (r.synced > 0) show(r.synced + " saved sale(s) synced", "success");
|
||||
if (r.synced > 0) {
|
||||
show(r.synced + " saved sale(s) synced", "success");
|
||||
refreshStock(me);
|
||||
}
|
||||
if (r.rejected > 0) {
|
||||
show(r.rejected + " sale(s) could not be synced - tap the banner to see why", "error");
|
||||
refreshCounts(me.id);
|
||||
@@ -210,6 +248,19 @@ export default function TerminalPage() {
|
||||
setFormError("Your account is not assigned to a branch.");
|
||||
return;
|
||||
}
|
||||
// Warn, never block: the jerrycans may be physically there even if the
|
||||
// system was not told (no opening count, an unrecorded delivery), and a
|
||||
// sale that really happened must be recorded. Negative stock then shows
|
||||
// up on the manager's Stock page to be corrected with a count.
|
||||
if (stockByProduct) {
|
||||
const short = lines.filter((l) => l.quantity > (stockByProduct[l.productId] ?? 0));
|
||||
if (short.length > 0) {
|
||||
const detail = short
|
||||
.map((l) => `${l.product.label}: ${Math.max(stockByProduct[l.productId] ?? 0, 0)} in stock, selling ${l.quantity}`)
|
||||
.join("\n");
|
||||
if (!window.confirm(`Not enough stock recorded at this branch:\n${detail}\n\nRecord the sale anyway?`)) return;
|
||||
}
|
||||
}
|
||||
setSubmitting(true);
|
||||
|
||||
// The IndexedDB write is the only step that must finish before we show
|
||||
@@ -233,7 +284,7 @@ export default function TerminalPage() {
|
||||
setSubmitting(false);
|
||||
setScreen({ kind: "receipt", sale });
|
||||
setCart([]);
|
||||
await refreshCounts(me.id);
|
||||
await refreshCounts(me.id); // deducts this sale from the stock shown
|
||||
|
||||
// Sync in the background; a failure leaves the sale queued for the
|
||||
// next automatic retry.
|
||||
@@ -241,6 +292,7 @@ export default function TerminalPage() {
|
||||
flushQueue(owner).then(async (r) => {
|
||||
setCounts((c) => ({ ...c, pending: r.pending }));
|
||||
setServerReachable(!r.offline);
|
||||
if (r.synced > 0) refreshStock(me);
|
||||
const rows = await salesFor(me.id);
|
||||
const updated = rows.find((row) => row.clientUuid === sale.clientUuid);
|
||||
if (updated) setScreen((s) => (s.kind === "receipt" && s.sale.clientUuid === sale.clientUuid ? { ...s, sale: updated } : s));
|
||||
@@ -450,7 +502,7 @@ export default function TerminalPage() {
|
||||
{productsLoading ? (
|
||||
<div className="h-24 animate-pulse rounded-xl2 bg-white shadow-soft" />
|
||||
) : (
|
||||
<ProductGrid products={products} quantities={quantities} onAdd={addProduct} />
|
||||
<ProductGrid products={products} quantities={quantities} stock={stockByProduct} onAdd={addProduct} />
|
||||
)}
|
||||
|
||||
{lines.length > 0 && (
|
||||
@@ -491,6 +543,13 @@ export default function TerminalPage() {
|
||||
<span>Total</span>
|
||||
<span>KES {total.toLocaleString()}</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCart([])}
|
||||
className="mt-2 text-sm font-medium text-alert-600 underline underline-offset-2"
|
||||
>
|
||||
Clear sale
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user