Compare commits
18 Commits
cb962466b3
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 34ea64c4d4 | |||
| d15273e2a6 | |||
| 5b7a2b847f | |||
| 6f8a5fe969 | |||
| 418ad36b02 | |||
| ff75cf2fa7 | |||
| db9387c01a | |||
| dc500972e0 | |||
| 83ec5ecd36 | |||
| bae21ee62c | |||
| 5e0e44c647 | |||
| 21d530cd6d | |||
| 9e3e59a804 | |||
| ee5bb5beb8 | |||
| 1fe2421cc4 | |||
| 0f609d57bb | |||
| 38facd3d9d | |||
| f865837b27 |
+9
-2
@@ -13,10 +13,17 @@ JWT_REFRESH_TTL=30d
|
||||
DELIVERY_MAX_DEVICES=2
|
||||
|
||||
# ---- Platform operator ----
|
||||
# Comma-separated emails with cross-tenant access to /platform. Create these
|
||||
# accounts with `npm run seed`; public signup refuses these addresses.
|
||||
# Comma-separated emails with cross-tenant access to /platform. The account
|
||||
# must also carry the platformAdmin flag, set only by `npm run seed` or
|
||||
# `npm run migrate:identity`. Removing an email here revokes access.
|
||||
# Public signup refuses these addresses.
|
||||
PLATFORM_ADMIN_EMAILS=
|
||||
|
||||
# ---- Invite links ----
|
||||
# Public base URL used in staff invite links. Optional: defaults to the
|
||||
# address the request came in on.
|
||||
APP_URL=
|
||||
|
||||
# ---- M-Pesa (optional, off for the pilot) ----
|
||||
# M-Pesa STK Push is out of scope for the pilot. While this is false every
|
||||
# /api/mpesa route returns 404 and the Daraja variables below are ignored.
|
||||
|
||||
+122
-17
@@ -62,7 +62,7 @@ the decisions taken along the way, and what is still open.
|
||||
| Decision | Why |
|
||||
|---|---|
|
||||
| Offline sales are always accepted, even if they take stock below zero. | The sale already happened. Refusing it would lose real cash. Negative stock is shown on the Stock page and fixed with a physical count. |
|
||||
| Transfers are refused when the sending branch lacks the stock. | Transfers are made online by a manager, so they can be checked. |
|
||||
| Transfers are refused when the sending branch lacks the stock. | Transfers are made online by a manager, so they can be checked. The check and the move run under a short per-branch, per-product lock (`withStockLock` in `src/lib/server/stock.ts`), so simultaneous transfers cannot together overdraw a branch; physical counts take the same lock. |
|
||||
| The server price is authoritative; a different price shown on the device is kept (`clientUnitPrice`) and flagged (`priceMismatch`). | Trusting the device's price would let a cashier under-charge. Overwriting it silently would hide a cash discrepancy. |
|
||||
| A queued sale stays with the branch where it was recorded, even if the cashier has since moved. | That is where the stock left and the cash was taken. |
|
||||
| A product deactivated while a phone was offline is still recorded at its price. | Same reason as the first row: the sale happened. |
|
||||
@@ -76,7 +76,7 @@ the decisions taken along the way, and what is still open.
|
||||
sales from the old version are sent on the next sync.
|
||||
|
||||
## Testing
|
||||
- `npm test` runs 37 API tests against an in-memory MongoDB, covering role
|
||||
- `npm test` runs 62 API tests against an in-memory MongoDB, covering role
|
||||
enforcement, tenant isolation for sales, stock and transfers, suspension,
|
||||
the sync protocol (including a 120-sale backlog replayed twice), and the
|
||||
business day.
|
||||
@@ -84,21 +84,126 @@ the decisions taken along the way, and what is still open.
|
||||
in, stop the server, reload the terminal, record two sales, restart the
|
||||
server, confirm they sync once and deduct stock.
|
||||
|
||||
## Follow-ups from the 11 October 2026 test report
|
||||
|
||||
The initial test report (run on the build before these changes) raised
|
||||
seven findings and a retest plan. All of them are addressed on
|
||||
`fix/test-report-followups`:
|
||||
|
||||
| Finding | What changed |
|
||||
|---|---|
|
||||
| F-01 Trial allows one branch | A business on its free trial may run **2 active branches** whatever its tier (`TRIAL_MAX_BRANCHES` in `src/lib/tiers.ts`). After the trial the tier's limit applies to adding branches. |
|
||||
| F-02 No current stock | Done in the previous change (stock ledger). Purchases recorded before the ledger existed are added by `npm run backfill:stock`. |
|
||||
| F-03 Reversed report dates | Refused in the page and by the API (400). The page labels which period the cards show. Report dates are Nairobi business days. |
|
||||
| F-04 No way back for deactivated products | Products page lists deactivated products under a toggle, with Reactivate. Deactivating warns about stock still on hand; that stock stays on the Stock page and can be transferred or counted out. |
|
||||
| F-05 Eggs shown as litres | Products carry a unit (L, ml, kg, g, pcs, tray, pack), chosen when the product is created and shown everywhere. |
|
||||
| F-06 No branch or staff removal | Staff: deactivate/reactivate (previous change). Branches: rename and deactivate/reactivate on the Branches page. A branch can only be deactivated once it has no stock and no active staff; its history stays in reports. |
|
||||
| F-07 Purchases shown as cost of goods | Cost of goods sold covers only units sold (now first-in-first-out per branch; see "Cost of goods sold" below). Purchases in the period are shown separately as "Stock purchased", with a "Cash surplus" line. |
|
||||
| STA-04 No invites | Staff and new branch managers can be invited: the owner or manager gets a one-time link (7 days) to send, and the person sets their own password. A new link can be made from Staff. |
|
||||
| CAT-12 Zero price, duplicates | Prices must be above zero; product names are unique per business, ignoring case. |
|
||||
| OFF-02 Local stock deduction | The till shows each product's stock and deducts every sale immediately, online or offline. |
|
||||
| POS-02 / INV-05 Oversell, cancel | The till warns before selling more than the recorded stock and asks to confirm (it does not block, because the sale may already have happened). A "Clear sale" button empties the cart. |
|
||||
|
||||
`tests/retest-plan.test.ts` runs the report's completion and retest plan
|
||||
(online sale, transfer, two offline sales replayed twice, a Branch B sale)
|
||||
and checks every balance and total it predicts.
|
||||
|
||||
### Before re-running the test report's plan on ZERRO
|
||||
1. Deploy, then run `npm run backfill:stock` once so the existing test
|
||||
purchases count as stock. Run it **before** anyone records an opening
|
||||
count, or those units would be counted twice.
|
||||
2. ZERRO is trialling, so it can now add Branch B without a plan change.
|
||||
3. Create the manager and cashier logins with invite links from Staff.
|
||||
|
||||
## Branch prices
|
||||
|
||||
Owners set a different price per branch on **Products -> Branch prices**
|
||||
(`/admin/prices`, API `/api/branch-prices`). Setting a price back to the
|
||||
default removes the override. Branch managers see their own branch's
|
||||
prices read-only.
|
||||
|
||||
- It is a Growth/Enterprise feature (as the plan list already advertised),
|
||||
also available during the free trial. After a trial on Starter, existing
|
||||
branch prices keep applying and can be reset, but not changed.
|
||||
- The till, cash sales and M-Pesa all read the branch price. A phone picks
|
||||
up a change the next time it loads products; a sale it records offline in
|
||||
the meantime is kept at the server's price and flagged as a price
|
||||
mismatch.
|
||||
- The Products page always shows default prices.
|
||||
|
||||
## People in more than one business
|
||||
|
||||
Email and phone are unique **within a business**, not across the platform,
|
||||
so one person can work for two businesses. Each account has its own
|
||||
password and role.
|
||||
|
||||
- Login looks the email up in every business. If the password matches one
|
||||
account, it signs straight in; if it matches several, the login page asks
|
||||
which business. Someone with a wrong password learns nothing about which
|
||||
businesses an email belongs to, and a wrong guess never resets the
|
||||
failed-login count of another business's account.
|
||||
- Signup and staff creation only check for duplicates inside the business,
|
||||
so they no longer reveal whether an email or phone is registered
|
||||
elsewhere.
|
||||
- Platform-operator access now needs the `platformAdmin` flag on the
|
||||
account as well as the email in `PLATFORM_ADMIN_EMAILS`. Without the
|
||||
flag, any owner could create a staff account with the operator's email
|
||||
in their own business. The flag is only set by `npm run seed` and
|
||||
`npm run migrate:identity`, never through the app.
|
||||
|
||||
**Deploying this change:** run `npm run migrate:identity` straight after
|
||||
the deploy. It flags the existing operator accounts and swaps the old
|
||||
platform-wide unique indexes for per-business ones. Until it runs,
|
||||
operators cannot open the Platform console and a second business cannot
|
||||
reuse an email. It is safe to re-run.
|
||||
|
||||
## Tenant isolation is enforced
|
||||
|
||||
Every model that holds one business's data carries a guard
|
||||
(`src/lib/server/tenantGuard.ts`). A query that does not name exactly one
|
||||
business (`businessId: <id>`) throws `TenantScopeError` before it reaches
|
||||
the database, so a route that forgets the business filter fails loudly in
|
||||
development and in the tests instead of reading or changing another
|
||||
business's data.
|
||||
|
||||
- Guarded: User, Branch, Product, BranchPricing, Transaction,
|
||||
DailyInventory, Expense, Purchase, StockMovement, StockTransfer. A test
|
||||
fails if a new model with a `businessId` field is added without the guard.
|
||||
- Queries that genuinely span businesses must be wrapped in
|
||||
`crossTenant("reason", ...)`: login's email lookup, refresh-session and
|
||||
invite-token lookups, the M-Pesa callback, the platform console, and the
|
||||
maintenance scripts. `git grep crossTenant` lists every one.
|
||||
- Related records are loaded with `scopedPopulate`, so a populated branch,
|
||||
product or staff name is also restricted to the business.
|
||||
- `tests/isolation.test.ts` sweeps every read route with another business's
|
||||
ids (nothing of theirs comes back) and every write route (all refused,
|
||||
their data unchanged).
|
||||
- Not guarded, by design: Business (the tenant itself, always looked up by
|
||||
the session's id), UserSession, MpesaCallbackLog and StockLock.
|
||||
|
||||
## Cost of goods sold
|
||||
|
||||
The profit report costs sales first-in-first-out, per branch
|
||||
(`src/lib/server/costing.ts`). It replays the stock ledger in order. Each
|
||||
branch keeps queues of stock at the price it was bought at, and a sale
|
||||
takes the oldest first.
|
||||
|
||||
- **Transfers carry their cost.** Stock moved between branches arrives at
|
||||
what the sending branch paid.
|
||||
- **Opening stock and upward counts** are valued at the product's purchase
|
||||
price at the time (or its first purchase price, if they came first).
|
||||
- **A sale recorded before its stock** (e.g. an offline sale before the
|
||||
purchase was entered) is costed by the next stock to arrive at that
|
||||
branch. Until then it counts as "units with no purchase cost on record".
|
||||
- **Stock written off** by counts or adjustments is shown as "Stock losses"
|
||||
and deducted in net profit. It is not part of cost of goods sold.
|
||||
- Each report replays the business's whole stock history. That is fast at
|
||||
pilot volumes; a business with years of history would want stored cost
|
||||
layers instead.
|
||||
|
||||
## Still open
|
||||
- **Removing a branch.** Branches can be renamed but not removed. Someone
|
||||
needs to decide what happens to a removed branch's stock and history.
|
||||
- **Setting branch prices.** Branch price overrides are applied everywhere,
|
||||
but there is no screen or API to set them yet.
|
||||
- **Global email and phone uniqueness.** One person cannot work for two
|
||||
businesses, and signup reveals whether an address is already registered.
|
||||
- **Isolation by convention.** Tenant filters are still written per route.
|
||||
The tests cover the sales, stock, transfer and access paths, not every
|
||||
route.
|
||||
- **Concurrent transfers.** Two transfers submitted at the same moment
|
||||
could together send more than the branch holds.
|
||||
- **Cash-basis profit.** The profit report counts all purchases in the
|
||||
period as cost of goods.
|
||||
- **M-Pesa, if turned on.** Only one product per payment. A prompt that
|
||||
times out still needs a manual check before taking cash.
|
||||
- **Not modelled yet:** invites and email verification, empty-bottle and
|
||||
deposit tracking, home-screen icons for the PWA.
|
||||
- **Not modelled yet:** email verification at signup, sending invites by
|
||||
email (links are shared by hand, e.g. WhatsApp), empty-bottle and deposit
|
||||
tracking, home-screen icons for the PWA.
|
||||
|
||||
+3
-1
@@ -10,7 +10,9 @@
|
||||
"seed": "tsx scripts/seed.ts",
|
||||
"migrate:multitenant": "tsx scripts/migrate-multitenant.ts",
|
||||
"test": "vitest run",
|
||||
"typecheck": "tsc --noEmit"
|
||||
"typecheck": "tsc --noEmit",
|
||||
"backfill:stock": "tsx scripts/backfill-stock-from-purchases.ts",
|
||||
"migrate:identity": "tsx scripts/migrate-per-business-identity.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.7.7",
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import dotenv from "dotenv";
|
||||
import path from "path";
|
||||
dotenv.config({ path: path.resolve(__dirname, "../.env.local") });
|
||||
|
||||
import mongoose from "mongoose";
|
||||
import { connectDb } from "../src/lib/server/db";
|
||||
import { backfillPurchaseMovements } from "../src/lib/server/stock";
|
||||
|
||||
/**
|
||||
* One-off (safe to re-run): purchases recorded before the stock ledger
|
||||
* existed did not add stock. This adds the missing PURCHASE movements so
|
||||
* each branch's stock starts from what it actually bought.
|
||||
*
|
||||
* npm run backfill:stock
|
||||
*
|
||||
* Run it once after deploying the stock ledger, BEFORE branches record
|
||||
* opening counts — a count recorded first already includes those units,
|
||||
* and backfilling afterwards would add them a second time.
|
||||
*/
|
||||
async function main() {
|
||||
await connectDb();
|
||||
const added = await backfillPurchaseMovements();
|
||||
console.log(`Added ${added} purchase stock movement(s).`);
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("backfill failed:", err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import { Expense } from "../src/lib/server/models/Expense";
|
||||
import { Purchase } from "../src/lib/server/models/Purchase";
|
||||
import { Business } from "../src/lib/server/models/Business";
|
||||
import { DEFAULT_TIER, TRIAL_DAYS } from "../src/lib/tiers";
|
||||
import { crossTenant } from "../src/lib/server/tenantGuard";
|
||||
|
||||
async function migrate() {
|
||||
await connectDb();
|
||||
@@ -75,7 +76,7 @@ async function migrate() {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
migrate().catch((err) => {
|
||||
crossTenant("one-off migration of data from before businesses existed", migrate).catch((err) => {
|
||||
console.error("migration failed:", err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import dotenv from "dotenv";
|
||||
import path from "path";
|
||||
dotenv.config({ path: path.resolve(__dirname, "../.env.local") });
|
||||
|
||||
import mongoose from "mongoose";
|
||||
import { connectDb } from "../src/lib/server/db";
|
||||
import { User } from "../src/lib/server/models/User";
|
||||
import { platformAdminEmails } from "../src/lib/server/platform";
|
||||
import { crossTenant } from "../src/lib/server/tenantGuard";
|
||||
|
||||
/**
|
||||
* One-off, safe to re-run. Moves user identity from platform-wide to
|
||||
* per-business uniqueness:
|
||||
*
|
||||
* 1. Marks today's platform operators. Until now an operator was anyone
|
||||
* whose email was in PLATFORM_ADMIN_EMAILS; emails were unique, so
|
||||
* that was one account each. From now on emails are only unique per
|
||||
* business, so access also needs the platformAdmin flag on the account.
|
||||
* Run this BEFORE dropping the old index, while each listed email
|
||||
* still matches exactly one account.
|
||||
* 2. Syncs the User indexes: drops the old unique `email_1` and
|
||||
* `phoneNumber_1`, creates unique (businessId, email) and
|
||||
* (businessId, phoneNumber), and a plain email lookup index.
|
||||
*
|
||||
* npm run migrate:identity
|
||||
*/
|
||||
async function main() {
|
||||
await connectDb();
|
||||
|
||||
for (const email of platformAdminEmails()) {
|
||||
const accounts = await User.find({ email }).select("_id").lean();
|
||||
if (accounts.length === 1) {
|
||||
await User.updateOne({ _id: accounts[0]._id }, { $set: { platformAdmin: true } });
|
||||
console.log(`Platform operator: ${email}`);
|
||||
} else if (accounts.length === 0) {
|
||||
console.warn(`No account for ${email} - create it with npm run seed.`);
|
||||
} else {
|
||||
console.warn(`${email} has ${accounts.length} accounts - set platformAdmin on the right one by hand.`);
|
||||
}
|
||||
}
|
||||
|
||||
const dropped = await User.syncIndexes();
|
||||
console.log(`User indexes synced. Dropped: ${dropped.length ? dropped.join(", ") : "none"}.`);
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
|
||||
crossTenant("identity migration spans every business", main).catch((err) => {
|
||||
console.error("migration failed:", err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
+18
-2
@@ -13,6 +13,8 @@ import { connectDb } from "../src/lib/server/db";
|
||||
import { User } from "../src/lib/server/models/User";
|
||||
import { Product } from "../src/lib/server/models/Product";
|
||||
import { Business } from "../src/lib/server/models/Business";
|
||||
import { isPlatformAdminEmail } from "../src/lib/server/platform";
|
||||
import { crossTenant } from "../src/lib/server/tenantGuard";
|
||||
|
||||
/**
|
||||
* Run once against a fresh database: `npm run seed`.
|
||||
@@ -39,10 +41,23 @@ async function seed() {
|
||||
}
|
||||
|
||||
let business = await Business.findOne({ name: demoBusinessName });
|
||||
const existing = await User.findOne({ email });
|
||||
// Emails are unique per business, so look in the seeded business (or, for
|
||||
// a legacy single-tenant database, for its one super admin).
|
||||
const existing = business
|
||||
? await User.findOne({ email, businessId: business._id })
|
||||
: await User.findOne({ email, role: "SUPER_ADMIN" });
|
||||
// The seed is the only way (besides the identity migration) to make an
|
||||
// operator: the flag is honoured only while the email is also listed in
|
||||
// PLATFORM_ADMIN_EMAILS.
|
||||
const platformAdmin = isPlatformAdminEmail(email);
|
||||
|
||||
if (existing) {
|
||||
console.log(`Super admin (${email}) already exists, skipping`);
|
||||
if (platformAdmin && !existing.platformAdmin) {
|
||||
existing.platformAdmin = true;
|
||||
await existing.save();
|
||||
console.log(`Marked ${email} as a platform operator`);
|
||||
}
|
||||
if (!business) {
|
||||
// Backfill a business for a legacy single-tenant admin if needed.
|
||||
business = await Business.create({ name: demoBusinessName, ownerId: existing._id });
|
||||
@@ -61,6 +76,7 @@ async function seed() {
|
||||
phoneNumber: "254700000000",
|
||||
email,
|
||||
passwordHash,
|
||||
platformAdmin,
|
||||
businessId: new mongoose.Types.ObjectId(), // temporary, overwritten below
|
||||
});
|
||||
business = await Business.create({ name: demoBusinessName, ownerId: owner._id });
|
||||
@@ -92,7 +108,7 @@ async function seed() {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
seed().catch((err) => {
|
||||
crossTenant("seeding may find a legacy admin outside any business", seed).catch((err) => {
|
||||
console.error("seed failed:", err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { apiFetch, ApiError } from "@/lib/api";
|
||||
import { AuthUser } from "@/lib/types";
|
||||
|
||||
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";
|
||||
|
||||
/** The signed-in user changes their own password. */
|
||||
export default function ChangePasswordPage() {
|
||||
const router = useRouter();
|
||||
const [me, setMe] = useState<AuthUser | null>(null);
|
||||
const [current, setCurrent] = useState("");
|
||||
const [next, setNext] = useState("");
|
||||
const [confirm, setConfirm] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [done, setDone] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
apiFetch<{ user: AuthUser }>("/api/auth/me")
|
||||
.then((r) => setMe(r.user))
|
||||
.catch(() => router.replace("/login"));
|
||||
}, [router]);
|
||||
|
||||
const home = me?.role === "DELIVERY" ? "/terminal" : "/admin/dashboard";
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
if (next.length < 8) return setError("The new password must be at least 8 characters.");
|
||||
if (next !== confirm) return setError("The two new passwords do not match.");
|
||||
setSaving(true);
|
||||
try {
|
||||
await apiFetch("/api/auth/password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ currentPassword: current, newPassword: next }),
|
||||
});
|
||||
setDone(true);
|
||||
setCurrent("");
|
||||
setNext("");
|
||||
setConfirm("");
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : "Could not change 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">
|
||||
<h1 className="font-display text-2xl font-bold text-depth-900">Change password</h1>
|
||||
{me && <p className="mt-1 text-sm text-depth-600">{me.email}</p>}
|
||||
|
||||
{done ? (
|
||||
<div className="mt-6">
|
||||
<p className="rounded-lg bg-confirm-500/10 px-3 py-2 text-sm text-confirm-600">
|
||||
Your password is changed. Any other phone or computer signed in to your account has been signed out.
|
||||
</p>
|
||||
<button
|
||||
onClick={() => router.replace(home)}
|
||||
className="tap-target mt-4 w-full rounded-full bg-gradient-to-r from-flow-500 to-flow-700 font-display font-semibold text-white"
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<form onSubmit={handleSubmit} className="mt-6 space-y-4">
|
||||
<div>
|
||||
<label htmlFor="current-password" className="mb-1.5 block text-sm font-medium text-depth-700">
|
||||
Current password
|
||||
</label>
|
||||
<input id="current-password" type="password" autoComplete="current-password" value={current} onChange={(e) => setCurrent(e.target.value)} className={inputClass} />
|
||||
</div>
|
||||
<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={next} onChange={(e) => setNext(e.target.value)} className={inputClass} />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="confirm-password" className="mb-1.5 block text-sm font-medium text-depth-700">
|
||||
Confirm new 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…" : "Change password"}
|
||||
</button>
|
||||
<button type="button" onClick={() => router.replace(home)} className="w-full text-sm text-depth-500 underline">
|
||||
Cancel
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+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>
|
||||
|
||||
@@ -17,6 +17,7 @@ import BranchRankingList from "@/components/admin/BranchRankingList";
|
||||
import ActivityFeedMatrix from "@/components/admin/ActivityFeedMatrix";
|
||||
import ReconciliationGrid from "@/components/admin/ReconciliationGrid";
|
||||
import StockSummaryCard from "@/components/admin/StockSummaryCard";
|
||||
import AccountLinks from "@/components/AccountLinks";
|
||||
|
||||
export default function AdminDashboardPage() {
|
||||
const router = useRouter();
|
||||
@@ -112,7 +113,8 @@ export default function AdminDashboardPage() {
|
||||
}
|
||||
|
||||
const scope: "global" | "branch" = selectedBranchId === "ALL" ? "global" : "branch";
|
||||
const showNoBranchesNudge = me.role === "SUPER_ADMIN" && branchesLoaded && branches.length === 0;
|
||||
// The operator's own business is a placeholder; don't nudge it to set up branches.
|
||||
const showNoBranchesNudge = me.role === "SUPER_ADMIN" && !me.isPlatformAdmin && branchesLoaded && branches.length === 0;
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-sand-50 pb-12">
|
||||
@@ -129,6 +131,13 @@ export default function AdminDashboardPage() {
|
||||
? `${me.branchName} Dashboard`
|
||||
: "Branch Dashboard"}
|
||||
</h1>
|
||||
<p className="mt-1 text-xs text-sand-200/60">
|
||||
{me.name}
|
||||
{me.isPlatformAdmin && " · Platform operator"}
|
||||
</p>
|
||||
<div className="mt-2">
|
||||
<AccountLinks />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<GlobalSwitcher
|
||||
@@ -137,7 +146,7 @@ export default function AdminDashboardPage() {
|
||||
onChange={setSelectedBranchId}
|
||||
isSuperAdmin={me.role === "SUPER_ADMIN"}
|
||||
/>
|
||||
{me.isPlatformAdmin && (
|
||||
{me.isPlatformAdmin && (
|
||||
<Link href="/platform" className="tap-target flex items-center rounded-xl2 bg-gradient-to-r from-flow-500 to-flow-700 px-4 text-sm font-semibold text-depth-950 hover:opacity-90">
|
||||
Platform
|
||||
</Link>
|
||||
@@ -145,8 +154,13 @@ export default function AdminDashboardPage() {
|
||||
<Link href="/admin/stock" className="tap-target flex items-center rounded-xl2 bg-white/10 px-4 text-sm font-medium text-white hover:bg-white/15">
|
||||
Stock
|
||||
</Link>
|
||||
{me.role === "SUPER_ADMIN" && (
|
||||
<Link href="/admin/branches" className="tap-target flex items-center rounded-xl2 bg-white/10 px-4 text-sm font-medium text-white hover:bg-white/15">
|
||||
Branches
|
||||
</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
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { apiFetch, ApiError } from "@/lib/api";
|
||||
import { AuthUser, Branch } from "@/lib/types";
|
||||
import { formatSize } from "@/lib/units";
|
||||
import { useToast } from "@/components/ui/Toast";
|
||||
import { SkeletonList } from "@/components/ui/Skeleton";
|
||||
import EmptyState from "@/components/ui/EmptyState";
|
||||
|
||||
interface PriceRow {
|
||||
productId: string;
|
||||
label: string;
|
||||
unit: string;
|
||||
sizeLiters: number;
|
||||
isActive: boolean;
|
||||
defaultPrice: number;
|
||||
branchPrice: number | null;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
interface PricesResponse {
|
||||
branchId: string;
|
||||
branchName: string;
|
||||
allowed: boolean;
|
||||
prices: PriceRow[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Branch prices: what each branch charges for each product. Owners edit;
|
||||
* branch managers see their own branch's prices.
|
||||
*/
|
||||
export default function BranchPricesPage() {
|
||||
const router = useRouter();
|
||||
const { show } = useToast();
|
||||
const [me, setMe] = useState<AuthUser | null>(null);
|
||||
const [branches, setBranches] = useState<Branch[]>([]);
|
||||
const [branchId, setBranchId] = useState("");
|
||||
const [data, setData] = useState<PricesResponse | null>(null);
|
||||
const [drafts, setDrafts] = useState<Record<string, string>>({});
|
||||
const [savingId, setSavingId] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const isOwner = me?.role === "SUPER_ADMIN";
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
try {
|
||||
const result = await apiFetch<{ user: AuthUser }>("/api/auth/me");
|
||||
if (result.user.role === "DELIVERY") {
|
||||
router.replace("/terminal");
|
||||
return;
|
||||
}
|
||||
setMe(result.user);
|
||||
const br = await apiFetch<{ branches: Branch[] }>("/api/branches");
|
||||
setBranches(br.branches);
|
||||
const first = result.user.role === "SUPER_ADMIN" ? br.branches[0]?._id : result.user.branchId;
|
||||
if (first) setBranchId(first);
|
||||
} catch {
|
||||
router.replace("/login");
|
||||
return;
|
||||
}
|
||||
setLoading(false);
|
||||
})();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!branchId) return;
|
||||
loadPrices(branchId);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [branchId]);
|
||||
|
||||
async function loadPrices(id: string) {
|
||||
try {
|
||||
const res = await apiFetch<PricesResponse>("/api/branch-prices?branchId=" + id);
|
||||
setData(res);
|
||||
setDrafts(Object.fromEntries(res.prices.map((p) => [p.productId, String(p.branchPrice ?? p.defaultPrice)])));
|
||||
} catch (err) {
|
||||
show(err instanceof ApiError ? err.message : "Could not load prices", "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function save(row: PriceRow) {
|
||||
const price = parseFloat(drafts[row.productId]);
|
||||
if (!Number.isFinite(price) || price <= 0) {
|
||||
show("Enter a price above zero", "error");
|
||||
return;
|
||||
}
|
||||
setSavingId(row.productId);
|
||||
try {
|
||||
await apiFetch("/api/branch-prices", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ branchId, productId: row.productId, unitPrice: price }),
|
||||
});
|
||||
show(
|
||||
price === row.defaultPrice
|
||||
? `${row.label} back to the default price`
|
||||
: `${row.label} now KES ${price.toLocaleString()} at ${data?.branchName}`,
|
||||
"success"
|
||||
);
|
||||
await loadPrices(branchId);
|
||||
} catch (err) {
|
||||
show(err instanceof ApiError ? err.message : "Could not save the price", "error");
|
||||
}
|
||||
setSavingId(null);
|
||||
}
|
||||
|
||||
async function reset(row: PriceRow) {
|
||||
setSavingId(row.productId);
|
||||
try {
|
||||
await apiFetch(`/api/branch-prices?branchId=${branchId}&productId=${row.productId}`, { method: "DELETE" });
|
||||
show(`${row.label} back to the default price`, "success");
|
||||
await loadPrices(branchId);
|
||||
} catch (err) {
|
||||
show(err instanceof ApiError ? err.message : "Could not reset the price", "error");
|
||||
}
|
||||
setSavingId(null);
|
||||
}
|
||||
|
||||
if (loading || !me) {
|
||||
return (
|
||||
<main className="min-h-screen bg-sand-50 pb-12">
|
||||
<header className="bg-depth-900 px-5 pb-8 pt-8">
|
||||
<div className="mx-auto h-14 max-w-3xl" />
|
||||
</header>
|
||||
<div className="mx-auto -mt-4 max-w-3xl px-5">
|
||||
<SkeletonList rows={4} />
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
const canEdit = isOwner && !!data?.allowed;
|
||||
const overrides = data?.prices.filter((p) => p.branchPrice !== null).length ?? 0;
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-sand-50 pb-12">
|
||||
<header className="bg-depth-900 px-5 pb-8 pt-8 text-white">
|
||||
<div className="mx-auto flex max-w-3xl flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<p className="text-xs uppercase tracking-wide text-flow-400">{me.businessName ?? "Vessel"}</p>
|
||||
<h1 className="font-display text-xl font-bold">Branch prices</h1>
|
||||
</div>
|
||||
<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"
|
||||
>
|
||||
← Products
|
||||
</Link>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="mx-auto -mt-4 max-w-3xl space-y-5 px-5">
|
||||
{branches.length === 0 ? (
|
||||
<div className="rounded-xl2 bg-white shadow-soft">
|
||||
<EmptyState icon="🏢" title="No branches yet" description="Create a branch first, then set its prices here." />
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-xl2 bg-white shadow-soft">
|
||||
<div className="space-y-3 border-b border-depth-100 px-4 py-3">
|
||||
{isOwner ? (
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-medium text-depth-600" htmlFor="price-branch">
|
||||
Branch
|
||||
</label>
|
||||
<select
|
||||
id="price-branch"
|
||||
value={branchId}
|
||||
onChange={(e) => setBranchId(e.target.value)}
|
||||
className="tap-target w-full rounded-xl border border-depth-200 bg-white px-3 sm:w-72"
|
||||
>
|
||||
{branches.map((b) => (
|
||||
<option key={b._id} value={b._id}>
|
||||
{b.branchName} — {b.locationCity}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
) : (
|
||||
<h2 className="font-display font-semibold text-depth-900">{data?.branchName ?? "Your branch"}</h2>
|
||||
)}
|
||||
<p className="text-xs text-depth-500">
|
||||
Each product sells at its default price unless this branch has its own price. Cashiers at the branch
|
||||
see the new price the next time their till loads products.
|
||||
{!isOwner && " Only the business owner can change prices."}
|
||||
</p>
|
||||
{isOwner && data && !data.allowed && (
|
||||
<p className="rounded-lg bg-cash-500/10 px-3 py-2 text-sm text-cash-700">
|
||||
Branch prices are part of the Growth plan. Existing branch prices still apply and can be reset to
|
||||
the default.
|
||||
</p>
|
||||
)}
|
||||
{data && <p className="text-xs font-medium text-depth-600">{overrides} product(s) priced differently here</p>}
|
||||
</div>
|
||||
|
||||
{!data ? (
|
||||
<SkeletonList rows={3} />
|
||||
) : data.prices.length === 0 ? (
|
||||
<EmptyState icon="🧴" title="No products yet" description="Add products first on the Products page." />
|
||||
) : (
|
||||
<ul className="divide-y divide-depth-100">
|
||||
{data.prices.map((row) => {
|
||||
const custom = row.branchPrice !== null;
|
||||
const draft = drafts[row.productId] ?? "";
|
||||
const changed = parseFloat(draft) !== (row.branchPrice ?? row.defaultPrice);
|
||||
return (
|
||||
<li key={row.productId} className="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
|
||||
<div className="min-w-0">
|
||||
<p className="font-medium text-depth-900">
|
||||
{row.label}{" "}
|
||||
<span className="text-depth-500">· {formatSize(row.sizeLiters, row.unit)}</span>
|
||||
{!row.isActive && <span className="ml-2 text-xs text-depth-500">(deactivated)</span>}
|
||||
</p>
|
||||
<p className="text-xs text-depth-500">
|
||||
Default KES {row.defaultPrice.toLocaleString()}
|
||||
{custom && (
|
||||
<span className="ml-2 rounded-full bg-flow-500/15 px-2 py-0.5 font-medium text-flow-700">
|
||||
This branch: KES {row.branchPrice!.toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
{canEdit ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-depth-500">KES</span>
|
||||
<input
|
||||
type="number"
|
||||
min="0.01"
|
||||
step="0.01"
|
||||
inputMode="decimal"
|
||||
value={draft}
|
||||
onChange={(e) => setDrafts((d) => ({ ...d, [row.productId]: e.target.value }))}
|
||||
aria-label={`Price of ${row.label} at this branch`}
|
||||
className="w-24 rounded-lg border border-depth-200 px-2 py-1.5 text-sm"
|
||||
/>
|
||||
<button
|
||||
onClick={() => save(row)}
|
||||
disabled={!changed || savingId === row.productId}
|
||||
className="rounded-lg bg-flow-500 px-3 py-1.5 text-sm font-semibold text-depth-950 disabled:opacity-40"
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
{custom && (
|
||||
<button
|
||||
onClick={() => reset(row)}
|
||||
disabled={savingId === row.productId}
|
||||
className="text-xs text-depth-500 underline"
|
||||
>
|
||||
Use default
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-sm font-semibold text-depth-900">
|
||||
KES {(row.branchPrice ?? row.defaultPrice).toLocaleString()}
|
||||
</span>
|
||||
{isOwner && custom && (
|
||||
<button onClick={() => reset(row)} className="text-xs text-depth-500 underline">
|
||||
Use default
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -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,11 +165,16 @@ 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>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Link href="/admin/prices" className="tap-target flex items-center rounded-xl2 bg-white/10 px-4 text-sm font-medium text-white hover:bg-white/15">
|
||||
Branch prices
|
||||
</Link>
|
||||
<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
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -164,8 +189,24 @@ export default function ProductsPage() {
|
||||
<p className="text-xs text-depth-500">
|
||||
Sizes shown here appear as options on every branch's terminal. Deactivating a size hides
|
||||
it from new sales without touching past transactions.
|
||||
{!canEdit && " Only the business owner can change products and prices."}
|
||||
{!canEdit && " Only the business owner can change products and prices."} Prices here are the
|
||||
defaults; a branch can charge its own price under{" "}
|
||||
<Link href="/admin/prices" className="underline underline-offset-2">
|
||||
Branch prices
|
||||
</Link>
|
||||
.
|
||||
</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 +218,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 +276,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 +299,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 +309,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,23 @@ interface ProfitReport {
|
||||
cashTotal: number;
|
||||
mpesaTotal: number;
|
||||
salesCount: number;
|
||||
costOfGoods: number;
|
||||
purchaseCount: number;
|
||||
unitsSold: number;
|
||||
costOfGoodsSold: number;
|
||||
unitsWithoutCost: number;
|
||||
stockLosses: 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 +42,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 +86,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 +115,28 @@ 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 (FIFO per branch)", report.costOfGoodsSold],
|
||||
["Units sold with no purchase cost on record", report.unitsWithoutCost],
|
||||
["Stock losses (counts and write-offs)", report.stockLosses],
|
||||
["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 +200,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 +210,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 +225,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 +247,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, each at what its branch paid for its oldest stock (first in, first out)
|
||||
{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>
|
||||
@@ -240,7 +274,32 @@ export default function ReportsPage() {
|
||||
>
|
||||
{money(report.netProfit)}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-depth-500">Gross profit − expenses</p>
|
||||
<p className="mt-1 text-xs text-depth-500">Gross profit − expenses − stock losses</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<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 className="rounded-xl2 bg-white p-5 shadow-soft">
|
||||
<p className="text-xs uppercase tracking-wide text-depth-500">Stock losses</p>
|
||||
<p className={"mt-1 font-display text-2xl font-bold " + (report.stockLosses > 0 ? "text-alert-600" : "text-depth-900")}>
|
||||
{money(report.stockLosses)}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-depth-500">
|
||||
Cost of stock written off by counts, breakage or adjustments. Deducted in net profit.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+140
-10
@@ -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; purpose: "invite" | "reset" } | 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, purpose: "invite" } : null);
|
||||
setName("");
|
||||
setBranchId("");
|
||||
setPhoneNumber("");
|
||||
@@ -115,6 +121,48 @@ export default function StaffPage() {
|
||||
return s.role === "DELIVERY" && s.branchId === me.branchId;
|
||||
}
|
||||
|
||||
// A new invite link while the person has no password yet; a password
|
||||
// reset link once they have one.
|
||||
async function newPasswordLink(s: StaffMember) {
|
||||
if (!s.invitePending && !window.confirm(`Create a password reset link for ${s.name}? Their current password keeps working until they use it.`)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await apiFetch<{ inviteUrl: string; purpose: "invite" | "reset" }>("/api/users/" + s._id + "/invite", {
|
||||
method: "POST",
|
||||
});
|
||||
setInviteLink({ name: s.name, url: result.inviteUrl, purpose: result.purpose });
|
||||
show(result.purpose === "reset" ? "Reset link created" : "New invite link created. The old link no longer works.", "success");
|
||||
} catch (err) {
|
||||
show(err instanceof ApiError ? err.message : "Could not create a link", "error");
|
||||
}
|
||||
}
|
||||
|
||||
// Owner only: move a manager or cashier to another branch. They are signed
|
||||
// out and sign in again; sales already recorded stay with the old branch.
|
||||
async function moveToBranch(s: StaffMember, branchId: string) {
|
||||
const to = branches.find((b) => b._id === branchId);
|
||||
if (!to || branchId === s.branchId) return;
|
||||
if (!window.confirm(`Move ${s.name} to ${to.branchName}? They will be signed out and must sign in again.`)) return;
|
||||
try {
|
||||
await apiFetch("/api/users/" + s._id, { method: "PATCH", body: JSON.stringify({ branchId }) });
|
||||
show(`${s.name} moved to ${to.branchName}`, "success");
|
||||
await loadStaff();
|
||||
} catch (err) {
|
||||
show(err instanceof ApiError ? err.message : "Could not move this person", "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 +239,43 @@ 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">
|
||||
{inviteLink.purpose === "reset"
|
||||
? `Send this password reset link to ${inviteLink.name}.`
|
||||
: `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 {inviteLink.purpose === "reset" ? "24 hours" : "7 days"}. Anyone with the link can
|
||||
take over 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(`${inviteLink.purpose === "reset" ? "Reset" : "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>
|
||||
@@ -206,21 +291,49 @@ export default function StaffPage() {
|
||||
{staff.map((s) => {
|
||||
const branchName = branches.find((b) => b._id === s.branchId)?.branchName;
|
||||
return (
|
||||
<li key={s._id} className="flex items-center justify-between gap-3 px-4 py-3 animate-fade-up">
|
||||
<li key={s._id} className="flex flex-wrap items-center justify-between gap-3 px-4 py-3 animate-fade-up">
|
||||
<div className={s.isActive ? "" : "opacity-50"}>
|
||||
<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}
|
||||
{branchName ? " · " + branchName : ""}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className={"rounded-full px-2.5 py-1 text-xs font-medium " + roleBadgeStyles[s.role]}>
|
||||
{s.role.replace("_", " ")}
|
||||
</span>
|
||||
{isSuperAdmin && canManage(s) && s.isActive && s.role !== "SUPER_ADMIN" && branches.length > 1 && (
|
||||
<select
|
||||
value=""
|
||||
onChange={(e) => moveToBranch(s, e.target.value)}
|
||||
aria-label={`Move ${s.name} to another branch`}
|
||||
className="rounded-lg border border-depth-200 bg-white px-2 py-1 text-xs text-depth-700"
|
||||
>
|
||||
<option value="">Move to…</option>
|
||||
{branches
|
||||
.filter((b) => b._id !== s.branchId)
|
||||
.map((b) => (
|
||||
<option key={b._id} value={b._id}>
|
||||
{b.branchName}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{canManage(s) && s.isActive && (
|
||||
<button
|
||||
onClick={() => newPasswordLink(s)}
|
||||
className="rounded-lg border border-depth-200 px-2.5 py-1 text-xs font-medium text-depth-700"
|
||||
>
|
||||
{s.invitePending ? "New link" : "Reset password"}
|
||||
</button>
|
||||
)}
|
||||
{canManage(s) && (
|
||||
<button
|
||||
onClick={() => toggleActive(s)}
|
||||
@@ -289,12 +402,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 +454,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>
|
||||
|
||||
@@ -7,7 +7,9 @@ import { Branch } from "@/lib/server/models/Branch";
|
||||
import { Business } from "@/lib/server/models/Business";
|
||||
import { signAccessToken, generateRefreshToken, hashRefreshToken, refreshTtlMs } from "@/lib/server/jwt";
|
||||
import { ACCESS_COOKIE, REFRESH_COOKIE, accessCookieOptions, refreshCookieOptions } from "@/lib/server/auth";
|
||||
import { isPlatformAdminEmail } from "@/lib/server/platform";
|
||||
import { isPlatformAdmin } from "@/lib/server/platform";
|
||||
import { objectId } from "@/lib/server/validation";
|
||||
import { crossTenant } from "@/lib/server/tenantGuard";
|
||||
import { getEnv } from "@/lib/server/env";
|
||||
import { tenantAccessError } from "@/lib/server/subscription";
|
||||
|
||||
@@ -21,6 +23,9 @@ const loginSchema = z.object({
|
||||
password: z.string().min(1),
|
||||
deviceId: z.string().uuid(),
|
||||
deviceLabel: z.string().max(120).optional(),
|
||||
// Which business to sign in to, when the same email and password match
|
||||
// accounts in more than one (the first attempt returns the choices).
|
||||
businessId: objectId.optional(),
|
||||
});
|
||||
|
||||
async function enforceDeviceBinding(userId: string, deviceId: string) {
|
||||
@@ -44,32 +49,72 @@ export async function POST(req: NextRequest) {
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: parsed.error.issues[0]?.message ?? "Invalid request" }, { status: 400 });
|
||||
}
|
||||
const { email, password, deviceId, deviceLabel } = parsed.data;
|
||||
const { email, password, deviceId, deviceLabel, businessId } = parsed.data;
|
||||
|
||||
const user = await User.findOne({ email: email.toLowerCase() }).select("+passwordHash");
|
||||
if (!user || !user.isActive) {
|
||||
// An email is unique within a business, so it can belong to accounts in
|
||||
// several businesses, each with its own password.
|
||||
const filter: Record<string, unknown> = { email: email.toLowerCase(), isActive: true };
|
||||
if (businessId) filter.businessId = businessId;
|
||||
const candidates = await crossTenant("login looks an email up in every business", () =>
|
||||
User.find(filter).select("+passwordHash").exec()
|
||||
);
|
||||
if (candidates.length === 0) {
|
||||
return NextResponse.json({ error: "Incorrect email or password" }, { status: 401 });
|
||||
}
|
||||
|
||||
if (user.lockedUntil && user.lockedUntil.getTime() > Date.now()) {
|
||||
const minutesLeft = Math.ceil((user.lockedUntil.getTime() - Date.now()) / 60000);
|
||||
const now = Date.now();
|
||||
const unlocked = candidates.filter((u) => !u.lockedUntil || u.lockedUntil.getTime() <= now);
|
||||
if (unlocked.length === 0) {
|
||||
const soonest = Math.min(...candidates.map((u) => u.lockedUntil!.getTime()));
|
||||
const minutesLeft = Math.ceil((soonest - now) / 60000);
|
||||
return NextResponse.json({ error: `Account locked. Try again in ${minutesLeft} minute(s).` }, { status: 423 });
|
||||
}
|
||||
|
||||
const validPassword = await user.comparePassword(password);
|
||||
if (!validPassword) {
|
||||
user.failedLoginAttempts += 1;
|
||||
if (user.failedLoginAttempts >= MAX_FAILED_ATTEMPTS) {
|
||||
user.lockedUntil = new Date(Date.now() + LOCKOUT_MS);
|
||||
user.failedLoginAttempts = 0;
|
||||
const matched = [];
|
||||
for (const u of unlocked) {
|
||||
if (await u.comparePassword(password)) matched.push(u);
|
||||
}
|
||||
|
||||
if (matched.length === 0) {
|
||||
// Count the failure against every account this email could have meant.
|
||||
for (const u of unlocked) {
|
||||
u.failedLoginAttempts += 1;
|
||||
if (u.failedLoginAttempts >= MAX_FAILED_ATTEMPTS) {
|
||||
u.lockedUntil = new Date(now + LOCKOUT_MS);
|
||||
u.failedLoginAttempts = 0;
|
||||
}
|
||||
await u.save();
|
||||
}
|
||||
await user.save();
|
||||
return NextResponse.json({ error: "Incorrect email or password" }, { status: 401 });
|
||||
}
|
||||
|
||||
user.failedLoginAttempts = 0;
|
||||
user.lockedUntil = null;
|
||||
await user.save();
|
||||
// A correct password unlocks only the accounts it belongs to; a person
|
||||
// with a different password in another business is not affected.
|
||||
for (const u of matched) {
|
||||
u.failedLoginAttempts = 0;
|
||||
u.lockedUntil = null;
|
||||
await u.save();
|
||||
}
|
||||
|
||||
if (matched.length > 1) {
|
||||
// Only someone who knows the password learns which businesses it opens.
|
||||
const businesses = await Business.find({ _id: { $in: matched.map((u) => u.businessId) } })
|
||||
.select("name")
|
||||
.lean();
|
||||
const nameById = new Map(businesses.map((b) => [b._id.toString(), b.name]));
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "This email signs in to more than one business. Choose one.",
|
||||
chooseBusiness: matched.map((u) => ({
|
||||
businessId: u.businessId.toString(),
|
||||
businessName: nameById.get(u.businessId.toString()) ?? "Business",
|
||||
role: u.role,
|
||||
})),
|
||||
},
|
||||
{ status: 300 }
|
||||
);
|
||||
}
|
||||
const user = matched[0];
|
||||
|
||||
const tenantError = await tenantAccessError(user.businessId);
|
||||
if (tenantError) {
|
||||
@@ -107,7 +152,7 @@ export async function POST(req: NextRequest) {
|
||||
deviceId,
|
||||
});
|
||||
|
||||
const branch = user.branchId ? await Branch.findById(user.branchId).lean() : null;
|
||||
const branch = user.branchId ? await Branch.findOne({ _id: user.branchId, businessId: user.businessId }).lean() : null;
|
||||
const business = await Business.findById(user.businessId).lean();
|
||||
|
||||
const res = NextResponse.json({
|
||||
@@ -122,8 +167,10 @@ export async function POST(req: NextRequest) {
|
||||
phoneNumber: user.phoneNumber,
|
||||
email: user.email,
|
||||
},
|
||||
redirectTo: user.role === "DELIVERY" ? "/terminal" : "/admin/dashboard",
|
||||
isPlatformAdmin: isPlatformAdminEmail(user.email),
|
||||
// Platform operators start on the console for every business, not on
|
||||
// their own (placeholder) business's dashboard.
|
||||
redirectTo: isPlatformAdmin(user) ? "/platform" : user.role === "DELIVERY" ? "/terminal" : "/admin/dashboard",
|
||||
isPlatformAdmin: isPlatformAdmin(user),
|
||||
});
|
||||
|
||||
res.cookies.set(ACCESS_COOKIE, accessToken, accessCookieOptions());
|
||||
|
||||
@@ -4,9 +4,9 @@ import { User } from "@/lib/server/models/User";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { Business } from "@/lib/server/models/Business";
|
||||
import { getAuth } from "@/lib/server/auth";
|
||||
import { isPlatformAdminEmail } from "@/lib/server/platform";
|
||||
import { isPlatformAdmin } 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";
|
||||
@@ -16,11 +16,11 @@ export async function GET(req: NextRequest) {
|
||||
const auth = getAuth(req);
|
||||
if (!auth) return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
|
||||
|
||||
const user = await User.findById(auth.sub).lean();
|
||||
const user = await User.findOne({ _id: auth.sub, businessId: auth.businessId }).lean();
|
||||
if (!user || !user.isActive) {
|
||||
return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
|
||||
}
|
||||
const branch = user.branchId ? await Branch.findById(user.branchId).lean() : null;
|
||||
const branch = user.branchId ? await Branch.findOne({ _id: user.branchId, businessId: user.businessId }).lean() : null;
|
||||
const business = await Business.findById(user.businessId).lean();
|
||||
|
||||
const tier = (business?.tier as TierId) ?? "STARTER";
|
||||
@@ -38,7 +38,7 @@ export async function GET(req: NextRequest) {
|
||||
branchName: branch?.branchName ?? null,
|
||||
phoneNumber: user.phoneNumber,
|
||||
email: user.email,
|
||||
isPlatformAdmin: isPlatformAdminEmail(user.email),
|
||||
isPlatformAdmin: isPlatformAdmin(user),
|
||||
},
|
||||
subscription: {
|
||||
tier,
|
||||
@@ -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() },
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
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 { UserSession } from "@/lib/server/models/UserSession";
|
||||
import { authorize } from "@/lib/server/auth";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
const changeSchema = z.object({
|
||||
currentPassword: z.string().min(1, "Enter your current password"),
|
||||
newPassword: z.string().min(8, "The new password must be at least 8 characters"),
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/auth/password — the signed-in user changes their own password.
|
||||
* Every other device is signed out; this one stays signed in.
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
await connectDb();
|
||||
const gate = authorize(req);
|
||||
if (!gate.ok) return gate.response;
|
||||
const auth = gate.auth;
|
||||
|
||||
const parsed = changeSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: parsed.error.issues[0]?.message ?? "Invalid request" }, { status: 400 });
|
||||
}
|
||||
const { currentPassword, newPassword } = parsed.data;
|
||||
if (currentPassword === newPassword) {
|
||||
return NextResponse.json({ error: "Choose a password different from the current one" }, { status: 400 });
|
||||
}
|
||||
|
||||
const user = await User.findOne({ _id: auth.sub, businessId: auth.businessId }).select("+passwordHash");
|
||||
if (!user || !user.isActive) return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
|
||||
if (!(await user.comparePassword(currentPassword))) {
|
||||
return NextResponse.json({ error: "Your current password is not correct" }, { status: 400 });
|
||||
}
|
||||
|
||||
user.passwordHash = await bcrypt.hash(newPassword, 12);
|
||||
await user.save();
|
||||
await UserSession.deleteMany({ userId: user._id, deviceId: { $ne: auth.deviceId } });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { User } from "@/lib/server/models/User";
|
||||
import { UserSession } from "@/lib/server/models/UserSession";
|
||||
import { signAccessToken, generateRefreshToken, hashRefreshToken, refreshTtlMs } from "@/lib/server/jwt";
|
||||
import { tenantAccessError } from "@/lib/server/subscription";
|
||||
import { crossTenant } from "@/lib/server/tenantGuard";
|
||||
import { ACCESS_COOKIE, REFRESH_COOKIE, accessCookieOptions, refreshCookieOptions } from "@/lib/server/auth";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
@@ -24,7 +25,9 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: "Session expired. Please log in again." }, { status: 401 });
|
||||
}
|
||||
|
||||
const user = await User.findById(session.userId);
|
||||
const user = await crossTenant("a refresh session identifies its user before the business is known", () =>
|
||||
User.findById(session.userId).exec()
|
||||
);
|
||||
if (!user || !user.isActive) {
|
||||
await UserSession.deleteOne({ _id: session._id });
|
||||
return NextResponse.json({ error: "Account no longer active" }, { status: 401 });
|
||||
|
||||
@@ -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 },
|
||||
];
|
||||
@@ -53,22 +53,16 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
const lowerEmail = email.toLowerCase();
|
||||
|
||||
// Platform-operator rights are granted by email (PLATFORM_ADMIN_EMAILS)
|
||||
// and signup does not verify email ownership, so an operator address
|
||||
// must never be claimable through public signup. Operator accounts are
|
||||
// created with `npm run seed` instead.
|
||||
// Operator addresses are reserved, so nobody can open a business that
|
||||
// looks like the operator's. (Access itself also needs the platformAdmin
|
||||
// flag, which signup never sets.)
|
||||
if (isPlatformAdminEmail(lowerEmail)) {
|
||||
return NextResponse.json({ error: "This email cannot be used to sign up." }, { status: 403 });
|
||||
}
|
||||
|
||||
const emailTaken = await User.findOne({ email: lowerEmail }).lean();
|
||||
if (emailTaken) {
|
||||
return NextResponse.json({ error: "An account with this email already exists." }, { status: 409 });
|
||||
}
|
||||
const phoneTaken = await User.findOne({ phoneNumber: normalizedPhone }).lean();
|
||||
if (phoneTaken) {
|
||||
return NextResponse.json({ error: "An account with this phone number already exists." }, { status: 409 });
|
||||
}
|
||||
// No platform-wide duplicate check: a new business has no users yet, and
|
||||
// the same person may already work for another business. (Checking would
|
||||
// also tell anyone whether an email or phone is registered elsewhere.)
|
||||
|
||||
const passwordHash = await bcrypt.hash(password, 12);
|
||||
|
||||
@@ -100,7 +94,7 @@ export async function POST(req: NextRequest) {
|
||||
await owner.save();
|
||||
} catch (e) {
|
||||
await Business.deleteOne({ _id: businessId }).catch(() => {});
|
||||
await User.deleteOne({ _id: ownerId }).catch(() => {});
|
||||
await User.deleteOne({ _id: ownerId, businessId }).catch(() => {});
|
||||
const msg = (e as Error).message || "";
|
||||
if (msg.includes("duplicate key")) {
|
||||
return NextResponse.json({ error: "An account with this email or phone already exists." }, { status: 409 });
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { ACTIVE_BRANCH, Branch } from "@/lib/server/models/Branch";
|
||||
import { Business } from "@/lib/server/models/Business";
|
||||
import { Product, BranchPricing } from "@/lib/server/models/Product";
|
||||
import { authorize, badRequest, MANAGERS } from "@/lib/server/auth";
|
||||
import { objectId } from "@/lib/server/validation";
|
||||
import { canUseBranchPricing, type SubscriptionStatus, type TierId } from "@/lib/tiers";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Branch-specific prices. A branch charges its own price for a product when
|
||||
* one is set here, otherwise the product's default price. The till, the
|
||||
* cash-sale route and M-Pesa all read prices the same way, so a change here
|
||||
* applies to the next sale at that branch (a phone that is offline picks it
|
||||
* up when it next loads products; a sale it records meanwhile is kept at the
|
||||
* server's price and flagged as a price mismatch).
|
||||
*/
|
||||
|
||||
async function pricingAllowed(businessId: string): Promise<boolean> {
|
||||
const biz = await Business.findById(businessId).select("tier subscriptionStatus").lean();
|
||||
return canUseBranchPricing((biz?.tier as TierId) ?? "STARTER", (biz?.subscriptionStatus as SubscriptionStatus) ?? "TRIALING");
|
||||
}
|
||||
|
||||
// GET /api/branch-prices?branchId= — every product with its default and
|
||||
// branch price. Owners pick any branch; managers see their own.
|
||||
export async function GET(req: NextRequest) {
|
||||
await connectDb();
|
||||
const gate = authorize(req, MANAGERS);
|
||||
if (!gate.ok) return gate.response;
|
||||
const auth = gate.auth;
|
||||
|
||||
const requested = req.nextUrl.searchParams.get("branchId");
|
||||
const branchId = auth.role === "SUPER_ADMIN" ? requested : auth.branchId;
|
||||
if (!branchId) return badRequest("branchId is required");
|
||||
if (!objectId.safeParse(branchId).success) return badRequest("Invalid branchId");
|
||||
|
||||
const branch = await Branch.findOne({ _id: branchId, businessId: auth.businessId }).lean();
|
||||
if (!branch) return NextResponse.json({ error: "Branch not found in your business" }, { status: 404 });
|
||||
|
||||
const [products, overrides, allowed] = await Promise.all([
|
||||
Product.find({ businessId: auth.businessId }).sort({ sortOrder: 1 }).lean(),
|
||||
BranchPricing.find({ businessId: auth.businessId, branchId }).lean(),
|
||||
pricingAllowed(auth.businessId),
|
||||
]);
|
||||
const byProduct = new Map(overrides.map((o) => [o.productId.toString(), o]));
|
||||
|
||||
const prices = products
|
||||
// Deactivated products only matter here if they still carry a branch price.
|
||||
.filter((p) => p.isActive || byProduct.has(p._id.toString()))
|
||||
.map((p) => {
|
||||
const o = byProduct.get(p._id.toString());
|
||||
return {
|
||||
productId: p._id.toString(),
|
||||
label: p.label,
|
||||
unit: p.unit,
|
||||
sizeLiters: p.sizeLiters,
|
||||
isActive: p.isActive,
|
||||
defaultPrice: p.unitPrice,
|
||||
branchPrice: o?.unitPrice ?? null,
|
||||
updatedAt: o?.updatedAt ?? null,
|
||||
};
|
||||
});
|
||||
|
||||
return NextResponse.json({ branchId, branchName: branch.branchName, allowed, prices });
|
||||
}
|
||||
|
||||
const setSchema = z.object({
|
||||
branchId: objectId,
|
||||
productId: objectId,
|
||||
unitPrice: z.number().positive("Price must be more than zero").max(10_000_000),
|
||||
});
|
||||
|
||||
// PUT /api/branch-prices — owner sets one product's price at one branch.
|
||||
// Setting it to the default price removes the override.
|
||||
export async function PUT(req: NextRequest) {
|
||||
await connectDb();
|
||||
const gate = authorize(req, ["SUPER_ADMIN"]);
|
||||
if (!gate.ok) return gate.response;
|
||||
const auth = gate.auth;
|
||||
|
||||
const parsed = setSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) return badRequest(parsed.error.issues[0]?.message ?? "Invalid request");
|
||||
const { branchId, productId, unitPrice } = parsed.data;
|
||||
|
||||
if (!(await pricingAllowed(auth.businessId))) {
|
||||
return NextResponse.json(
|
||||
{ error: "Branch prices are part of the Growth plan. Upgrade to set a different price per branch." },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
const [branch, product] = await Promise.all([
|
||||
Branch.exists({ _id: branchId, businessId: auth.businessId, ...ACTIVE_BRANCH }),
|
||||
Product.findOne({ _id: productId, businessId: auth.businessId }).select("unitPrice").lean(),
|
||||
]);
|
||||
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 });
|
||||
|
||||
if (unitPrice === product.unitPrice) {
|
||||
await BranchPricing.deleteOne({ businessId: auth.businessId, branchId, productId });
|
||||
return NextResponse.json({ branchId, productId, branchPrice: null, defaultPrice: product.unitPrice });
|
||||
}
|
||||
|
||||
const row = await BranchPricing.findOneAndUpdate(
|
||||
{ businessId: auth.businessId, branchId, productId },
|
||||
{ businessId: auth.businessId, unitPrice, updatedBy: auth.sub },
|
||||
{ upsert: true, new: true, setDefaultsOnInsert: true }
|
||||
).lean();
|
||||
return NextResponse.json({ branchId, productId, branchPrice: row!.unitPrice, defaultPrice: product.unitPrice });
|
||||
}
|
||||
|
||||
// DELETE /api/branch-prices?branchId=&productId= — back to the default price.
|
||||
// Always allowed, even after the plan no longer includes branch prices.
|
||||
export async function DELETE(req: NextRequest) {
|
||||
await connectDb();
|
||||
const gate = authorize(req, ["SUPER_ADMIN"]);
|
||||
if (!gate.ok) return gate.response;
|
||||
const auth = gate.auth;
|
||||
|
||||
const branchId = req.nextUrl.searchParams.get("branchId");
|
||||
const productId = req.nextUrl.searchParams.get("productId");
|
||||
if (!objectId.safeParse(branchId).success || !objectId.safeParse(productId).success) {
|
||||
return badRequest("branchId and productId are required");
|
||||
}
|
||||
await BranchPricing.deleteOne({ businessId: auth.businessId, branchId, productId });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -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;
|
||||
@@ -65,14 +71,15 @@ export async function POST(req: NextRequest) {
|
||||
} catch (e) {
|
||||
return NextResponse.json({ error: (e as Error).message }, { status: 400 });
|
||||
}
|
||||
// Unique within this business only (see the User model).
|
||||
const lowerEmail = manager.email.toLowerCase();
|
||||
const emailTaken = await User.findOne({ email: lowerEmail }).lean();
|
||||
const emailTaken = await User.exists({ businessId, email: lowerEmail });
|
||||
if (emailTaken) {
|
||||
return NextResponse.json({ error: "An account with this email already exists." }, { status: 409 });
|
||||
return NextResponse.json({ error: "Someone in your business already uses this email." }, { status: 409 });
|
||||
}
|
||||
const phoneTaken = await User.findOne({ phoneNumber: managerPhone }).lean();
|
||||
const phoneTaken = await User.exists({ businessId, phoneNumber: managerPhone });
|
||||
if (phoneTaken) {
|
||||
return NextResponse.json({ error: "An account with this phone number already exists." }, { status: 409 });
|
||||
return NextResponse.json({ error: "Someone in your business already uses this phone number." }, { status: 409 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,8 +87,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,16 +97,18 @@ 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) {
|
||||
await Branch.deleteOne({ _id: branch._id }).catch(() => {});
|
||||
await Branch.deleteOne({ _id: branch._id, businessId }).catch(() => {});
|
||||
if (err?.code === 11000) {
|
||||
return NextResponse.json({ error: "A user with this phone number or email already exists." }, { status: 409 });
|
||||
return NextResponse.json({ error: "Someone in your business already uses this phone number or email." }, { status: 409 });
|
||||
}
|
||||
return NextResponse.json({ error: "Could not create the branch manager. Please try again." }, { status: 500 });
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Expense, EXPENSE_CATEGORIES } from "@/lib/server/models/Expense";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { objectId } from "@/lib/server/validation";
|
||||
import { authorize, branchParam, MANAGERS } from "@/lib/server/auth";
|
||||
import { scopedPopulate } from "@/lib/server/tenantGuard";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -36,8 +37,8 @@ export async function GET(req: NextRequest) {
|
||||
}
|
||||
|
||||
const expenses = await Expense.find(filter)
|
||||
.populate("branchId", "branchName")
|
||||
.populate("recordedBy", "name")
|
||||
.populate(scopedPopulate("branchId", "branchName", auth.businessId))
|
||||
.populate(scopedPopulate("recordedBy", "name", auth.businessId))
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(500)
|
||||
.lean();
|
||||
|
||||
@@ -43,7 +43,7 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
const date = parsed.data.date ?? todayNairobi();
|
||||
const row = await DailyInventory.findOneAndUpdate(
|
||||
{ branchId, productId: parsed.data.productId, date },
|
||||
{ businessId: auth.businessId, branchId, productId: parsed.data.productId, date },
|
||||
{ morningDispatched: parsed.data.morningDispatched, recordedBy: auth.sub, businessId: auth.businessId },
|
||||
{ upsert: true, new: true, setDefaultsOnInsert: true }
|
||||
);
|
||||
|
||||
@@ -42,7 +42,7 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
const date = parsed.data.date ?? todayNairobi();
|
||||
const row = await DailyInventory.findOneAndUpdate(
|
||||
{ branchId, productId: parsed.data.productId, date },
|
||||
{ businessId: auth.businessId, branchId, productId: parsed.data.productId, date },
|
||||
{ eveningPhysicalCount: parsed.data.eveningPhysicalCount, recordedBy: auth.sub, businessId: auth.businessId },
|
||||
{ upsert: true, new: true, setDefaultsOnInsert: true }
|
||||
);
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
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 { UserSession } from "@/lib/server/models/UserSession";
|
||||
import { hashInviteToken } from "@/lib/server/invites";
|
||||
import { crossTenant } from "@/lib/server/tenantGuard";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
async function findInvitee(token: string) {
|
||||
if (!token || token.length > 100) return null;
|
||||
const user = await crossTenant("an invite token identifies its account before sign-in", () =>
|
||||
User.findOne({ inviteTokenHash: hashInviteToken(token), isActive: true }).exec()
|
||||
);
|
||||
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,
|
||||
purpose: user.invitePurpose === "reset" ? "reset" : "invite",
|
||||
});
|
||||
}
|
||||
|
||||
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.invitePurpose = null;
|
||||
user.failedLoginAttempts = 0;
|
||||
user.lockedUntil = null;
|
||||
await user.save();
|
||||
// A new password ends every existing session, so whoever had the old one
|
||||
// (a lost phone, a former colleague) is signed out.
|
||||
await UserSession.deleteMany({ userId: user._id });
|
||||
return NextResponse.json({ ok: true, email: user.email });
|
||||
}
|
||||
@@ -3,6 +3,7 @@ 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 { crossTenant } from "@/lib/server/tenantGuard";
|
||||
import { MpesaCallbackLog } from "@/lib/server/models/MpesaCallbackLog";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
@@ -69,7 +70,9 @@ export async function POST(req: NextRequest) {
|
||||
mpesaReceiptNumber = receiptItem ? String(receiptItem.Value) : null;
|
||||
}
|
||||
|
||||
const txn = await Transaction.findOne({ "mpesaDetails.checkoutRequestId": checkoutRequestId });
|
||||
const txn = await crossTenant("the payment provider's callback is matched by checkout id", () =>
|
||||
Transaction.findOne({ "mpesaDetails.checkoutRequestId": checkoutRequestId }).exec()
|
||||
);
|
||||
|
||||
if (!txn) {
|
||||
await MpesaCallbackLog.create({
|
||||
|
||||
@@ -26,7 +26,7 @@ export async function GET(req: NextRequest, { params }: { params: { transactionI
|
||||
const result = await queryStkStatus(txn.mpesaDetails.checkoutRequestId);
|
||||
const code = Number(result.ResultCode);
|
||||
if (!Number.isNaN(code) && code !== 1032) {
|
||||
const fresh = await Transaction.findOne({ _id: txn._id, paymentStatus: "PENDING" });
|
||||
const fresh = await Transaction.findOne({ _id: txn._id, businessId: auth.businessId, paymentStatus: "PENDING" });
|
||||
if (fresh) {
|
||||
fresh.paymentStatus = code === 0 ? "SUCCESS" : "FAILED";
|
||||
fresh.mpesaDetails.resultCode = code;
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { isValidObjectId } from "mongoose";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { Business } from "@/lib/server/models/Business";
|
||||
import { User } from "@/lib/server/models/User";
|
||||
import { requirePlatformAdmin } from "@/lib/server/platform";
|
||||
import { invitePending, issueInvite } from "@/lib/server/invites";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
/**
|
||||
* POST /api/platform/businesses/:id/owner-reset — operator only. A one-time
|
||||
* password link for a business's owner of record: the way back in for an
|
||||
* owner who has forgotten their password (nobody inside the business can
|
||||
* reset the owner). Send the link to the owner yourself, by a channel you
|
||||
* know is theirs. Their current password keeps working until it is used.
|
||||
*/
|
||||
export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
|
||||
await connectDb();
|
||||
const admin = await requirePlatformAdmin(req);
|
||||
if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
if (!isValidObjectId(params.id)) return NextResponse.json({ error: "Business not found" }, { status: 404 });
|
||||
|
||||
const business = await Business.findById(params.id).select("ownerId").lean();
|
||||
if (!business) return NextResponse.json({ error: "Business not found" }, { status: 404 });
|
||||
const owner = await User.findOne({ _id: business.ownerId, businessId: business._id });
|
||||
if (!owner) return NextResponse.json({ error: "This business has no owner account" }, { status: 404 });
|
||||
if (owner._id.toString() === admin.userId) {
|
||||
return NextResponse.json({ error: "Change your own password from Change password instead" }, { status: 409 });
|
||||
}
|
||||
if (!owner.isActive) return NextResponse.json({ error: "The owner's account is deactivated" }, { status: 409 });
|
||||
|
||||
const purpose = invitePending(owner) ? "invite" : "reset";
|
||||
const inviteUrl = issueInvite(owner, req, purpose);
|
||||
await owner.save();
|
||||
return NextResponse.json({ inviteUrl, purpose, email: owner.email, name: owner.name, expiresAt: owner.inviteExpiresAt });
|
||||
}
|
||||
@@ -4,7 +4,8 @@ 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 { crossTenant } from "@/lib/server/tenantGuard";
|
||||
import { TIERS, effectiveMaxBranches, type TierId, type SubscriptionStatus } from "@/lib/tiers";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -23,22 +24,26 @@ export async function GET(req: NextRequest) {
|
||||
const businesses = await Business.find({}).sort({ createdAt: -1 }).lean();
|
||||
|
||||
// Usage counts per business in two grouped queries instead of N+1.
|
||||
const [userCounts, branchCounts] = await Promise.all([
|
||||
User.aggregate<{ _id: unknown; count: number }>([
|
||||
{ $group: { _id: "$businessId", count: { $sum: 1 } } },
|
||||
]),
|
||||
Branch.aggregate<{ _id: unknown; count: number }>([
|
||||
{ $group: { _id: "$businessId", count: { $sum: 1 } } },
|
||||
]),
|
||||
]);
|
||||
const [userCounts, branchCounts] = await crossTenant("the platform console counts every business", () =>
|
||||
Promise.all([
|
||||
User.aggregate<{ _id: unknown; count: number }>([{ $group: { _id: "$businessId", count: { $sum: 1 } } }]).exec(),
|
||||
Branch.aggregate<{ _id: unknown; count: number }>([
|
||||
{ $match: { isActive: { $ne: false } } },
|
||||
{ $group: { _id: "$businessId", count: { $sum: 1 } } },
|
||||
]).exec(),
|
||||
])
|
||||
);
|
||||
const userMap = new Map(userCounts.map((u) => [String(u._id), u.count]));
|
||||
const branchMap = new Map(branchCounts.map((b) => [String(b._id), b.count]));
|
||||
|
||||
// Owner contact lookup.
|
||||
const ownerIds = businesses.map((b) => b.ownerId);
|
||||
const owners = await User.find({ _id: { $in: ownerIds } })
|
||||
.select("name email phoneNumber")
|
||||
.lean();
|
||||
const owners = await crossTenant("the platform console lists every business's owner", () =>
|
||||
User.find({ _id: { $in: ownerIds } })
|
||||
.select("name email phoneNumber")
|
||||
.lean()
|
||||
.exec()
|
||||
);
|
||||
const ownerMap = new Map(owners.map((o) => [String(o._id), o]));
|
||||
|
||||
const rows = businesses.map((b) => {
|
||||
@@ -58,7 +63,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,8 +20,13 @@ 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();
|
||||
if (auth.branchId) {
|
||||
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();
|
||||
// The catalogue view (includeInactive) shows default prices; the till's
|
||||
// view shows what this branch actually charges.
|
||||
if (auth.branchId && !includeInactive) {
|
||||
const overrides = await BranchPricing.find({ businessId: auth.businessId, branchId: auth.branchId }).lean();
|
||||
const priceByProduct = new Map(overrides.map((o) => [o.productId.toString(), o.unitPrice]));
|
||||
for (const p of products) {
|
||||
@@ -31,9 +39,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 +59,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,10 +3,11 @@ 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";
|
||||
import { scopedPopulate } from "@/lib/server/tenantGuard";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -36,8 +37,8 @@ export async function GET(req: NextRequest) {
|
||||
}
|
||||
|
||||
const purchases = await Purchase.find(filter)
|
||||
.populate("branchId", "branchName")
|
||||
.populate("recordedBy", "name")
|
||||
.populate(scopedPopulate("branchId", "branchName", auth.businessId))
|
||||
.populate(scopedPopulate("recordedBy", "name", auth.businessId))
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(500)
|
||||
.lean();
|
||||
@@ -91,7 +92,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,35 @@
|
||||
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";
|
||||
import { costOfGoodsSold as fifoCost } from "@/lib/server/costing";
|
||||
|
||||
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 first-in-first-out per branch: each unit sold costs
|
||||
* what that branch paid for its oldest stock on hand
|
||||
* (see src/lib/server/costing.ts)
|
||||
* Gross profit revenue - cost of goods sold
|
||||
* Expenses operating expenses in the period
|
||||
* Stock losses cost of stock written off by counts and adjustments
|
||||
* Net profit gross profit - expenses - stock losses
|
||||
* 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 +42,107 @@ 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, cost, 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 } } },
|
||||
fifoCost(auth.businessId, { from, to, branchId }),
|
||||
Purchase.aggregate<{ total: number; count: number }>([
|
||||
{ $match: inPeriod },
|
||||
{ $group: { _id: null, total: { $sum: "$totalCost" }, count: { $sum: 1 } } },
|
||||
]),
|
||||
Expense.aggregate([
|
||||
{ $match: costMatch },
|
||||
{ $group: { _id: null, expenses: { $sum: "$amount" }, expenseCount: { $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;
|
||||
let revenue = 0, cashTotal = 0, mpesaTotal = 0, salesCount = 0, unitsSold = 0;
|
||||
for (const s of salesByProduct) {
|
||||
revenue += s.revenue;
|
||||
cashTotal += s.cashTotal;
|
||||
mpesaTotal += s.mpesaTotal;
|
||||
salesCount += s.lines;
|
||||
unitsSold += s.units;
|
||||
}
|
||||
const costOfGoodsSold = cost.costOfGoodsSold;
|
||||
// Sales recorded before the stock ledger existed have no stock movement,
|
||||
// so FIFO cannot cost them: count them as uncosted too.
|
||||
const unitsWithoutCost = Math.max(cost.unitsWithoutCost, unitsSold - cost.unitsCosted);
|
||||
|
||||
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,
|
||||
costMethod: "FIFO per branch",
|
||||
// Units sold whose cost is unknown (no purchase price for that stock on
|
||||
// record): gross profit overstates by their cost.
|
||||
unitsWithoutCost,
|
||||
stockLosses: cost.stockLosses,
|
||||
grossProfit,
|
||||
expenses,
|
||||
expenseCount: expenseAgg[0]?.expenseCount ?? 0,
|
||||
netProfit,
|
||||
expenseCount: expenseAgg[0]?.count ?? 0,
|
||||
netProfit: Math.round((grossProfit - expenses - cost.stockLosses) * 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 };
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ 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";
|
||||
import { clientRefId, recordMovement, stockOf, StockBusyError, withStockLock } from "@/lib/server/stock";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
@@ -57,27 +57,36 @@ export async function POST(req: NextRequest) {
|
||||
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.
|
||||
// A retried submit with the same clientUuid is a no-op. A count reads the
|
||||
// balance to work out its correction, so it runs under the stock lock:
|
||||
// a transfer cannot slip in between the read and the write.
|
||||
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 lockedBranch = branchId;
|
||||
try {
|
||||
const quantity = await withStockLock(auth.businessId, lockedBranch, data.productId, async () => {
|
||||
const already = await StockMovement.exists({ type: "ADJUSTMENT", refId, businessId: auth.businessId });
|
||||
if (!already) {
|
||||
const before = await stockOf(auth.businessId, lockedBranch, 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: lockedBranch,
|
||||
productId: data.productId,
|
||||
type: "ADJUSTMENT",
|
||||
quantity: delta,
|
||||
refId,
|
||||
note: data.note ? `${label}. ${data.note}` : label,
|
||||
recordedBy: auth.sub,
|
||||
});
|
||||
}
|
||||
}
|
||||
return stockOf(auth.businessId, lockedBranch, data.productId);
|
||||
});
|
||||
return NextResponse.json({ branchId, productId: data.productId, quantity }, { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof StockBusyError) return NextResponse.json({ error: err.message }, { status: 409 });
|
||||
throw err;
|
||||
}
|
||||
|
||||
const quantity = await stockOf(auth.businessId, branchId, data.productId);
|
||||
return NextResponse.json({ branchId, productId: data.productId, quantity }, { status: 201 });
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ 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";
|
||||
import { scopedPopulate } from "@/lib/server/tenantGuard";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -23,9 +24,9 @@ export async function GET(req: NextRequest) {
|
||||
const movements = await StockMovement.find(filter)
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(limit)
|
||||
.populate("branchId", "branchName")
|
||||
.populate("productId", "label unit")
|
||||
.populate("recordedBy", "name")
|
||||
.populate(scopedPopulate("branchId", "branchName", auth.businessId))
|
||||
.populate(scopedPopulate("productId", "label unit", auth.businessId))
|
||||
.populate(scopedPopulate("recordedBy", "name", auth.businessId))
|
||||
.lean();
|
||||
return NextResponse.json({ movements });
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
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";
|
||||
import { scopedPopulate } from "@/lib/server/tenantGuard";
|
||||
import { objectId } from "@/lib/server/validation";
|
||||
import { recordMovement, stockOf } from "@/lib/server/stock";
|
||||
import { recordMovement, stockOf, StockBusyError, withStockLock } from "@/lib/server/stock";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -27,10 +28,10 @@ export async function GET(req: NextRequest) {
|
||||
const transfers = await StockTransfer.find(filter)
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(100)
|
||||
.populate("fromBranchId", "branchName")
|
||||
.populate("toBranchId", "branchName")
|
||||
.populate("productId", "label unit")
|
||||
.populate("recordedBy", "name")
|
||||
.populate(scopedPopulate("fromBranchId", "branchName", auth.businessId))
|
||||
.populate(scopedPopulate("toBranchId", "branchName", auth.businessId))
|
||||
.populate(scopedPopulate("productId", "label unit", auth.businessId))
|
||||
.populate(scopedPopulate("recordedBy", "name", auth.businessId))
|
||||
.lean();
|
||||
return NextResponse.json({ transfers });
|
||||
}
|
||||
@@ -97,40 +98,56 @@ 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 });
|
||||
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;
|
||||
// can be refused when the sending branch does not have the stock. The
|
||||
// balance check and the movements run under the sending branch's stock
|
||||
// lock, so two simultaneous transfers cannot both spend the same units.
|
||||
const sendingBranch = fromBranchId;
|
||||
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 await withStockLock(auth.businessId, sendingBranch, data.productId, async () => {
|
||||
// An identical submit may have completed while we waited for the lock.
|
||||
const done = await StockTransfer.findOne({ businessId: auth.businessId, clientUuid: data.clientUuid });
|
||||
if (done) {
|
||||
await applyTransfer(done);
|
||||
return NextResponse.json({ transfer: done }, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ transfer }, { status: 201 });
|
||||
const available = await stockOf(auth.businessId, sendingBranch, 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: sendingBranch,
|
||||
toBranchId: data.toBranchId,
|
||||
productId: data.productId,
|
||||
quantity: data.quantity,
|
||||
clientUuid: data.clientUuid,
|
||||
note: data.note ?? null,
|
||||
recordedBy: auth.sub,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
// Defensive: the unique clientUuid index still guards double submits.
|
||||
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 });
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof StockBusyError) return NextResponse.json({ error: err.message }, { status: 409 });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,10 +167,8 @@ export async function POST(req: NextRequest) {
|
||||
} 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.");
|
||||
}
|
||||
const existing = await Transaction.findOne({ clientUuid: `${sale.clientUuid}:${index}`, businessId: auth.businessId });
|
||||
if (!existing) return reject("This sale id is already in use.");
|
||||
txn = existing;
|
||||
}
|
||||
// Idempotent, and also repairs a line whose stock movement was not
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { connectDb } from "@/lib/server/db";
|
||||
import { Transaction } from "@/lib/server/models/Transaction";
|
||||
import { authorize, branchParam } from "@/lib/server/auth";
|
||||
import { scopedPopulate } from "@/lib/server/tenantGuard";
|
||||
import { startOfTodayNairobi } from "@/lib/server/businessDay";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
@@ -26,7 +27,7 @@ export async function GET(req: NextRequest) {
|
||||
const transactions = await Transaction.find(filter)
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(limit)
|
||||
.populate("branchId", "branchName")
|
||||
.populate(scopedPopulate("branchId", "branchName", auth.businessId))
|
||||
.lean();
|
||||
|
||||
return NextResponse.json({ transactions });
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
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 { invitePending, issueInvite } from "@/lib/server/invites";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
/**
|
||||
* POST /api/users/:id/invite — a one-time password link for a staff member:
|
||||
* - an INVITE link while they have not set a password yet (lost or expired invite);
|
||||
* - a RESET link once they have (forgotten password). Their current password
|
||||
* keeps working until the link is used; using it signs them out everywhere.
|
||||
* The previous link stops working either way.
|
||||
* Owners: anyone in the business but themselves. 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 do this for delivery staff in their own branch" }, { status: 403 });
|
||||
}
|
||||
if (user._id.toString() === auth.sub) {
|
||||
return NextResponse.json({ error: "Change your own password from Change password instead" }, { status: 409 });
|
||||
}
|
||||
if (!user.isActive) {
|
||||
return NextResponse.json({ error: "Reactivate this account first" }, { status: 409 });
|
||||
}
|
||||
|
||||
const purpose = invitePending(user) ? "invite" : "reset";
|
||||
const inviteUrl = issueInvite(user, req, purpose);
|
||||
await user.save();
|
||||
return NextResponse.json({ inviteUrl, purpose, 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,9 +67,16 @@ 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 });
|
||||
const fromBranch = target.branchId;
|
||||
target.branchId = branch._id;
|
||||
// A moved manager stops being the old branch's manager, and becomes the
|
||||
// new branch's manager if it has none.
|
||||
if (target.role === "BRANCH_MANAGER" && fromBranch?.toString() !== branch._id.toString()) {
|
||||
await Branch.updateOne({ _id: fromBranch, businessId: auth.businessId, managerId: target._id }, { managerId: null });
|
||||
await Branch.updateOne({ _id: branch._id, businessId: auth.businessId, managerId: null }, { managerId: target._id });
|
||||
}
|
||||
}
|
||||
if (isActive !== undefined) target.isActive = isActive;
|
||||
await target.save();
|
||||
@@ -82,5 +89,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 { invitePending, 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: invitePending(u) })),
|
||||
});
|
||||
}
|
||||
|
||||
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,10 +111,11 @@ 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 });
|
||||
return NextResponse.json({ error: "Someone in your business already uses this phone number or email" }, { status: 409 });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"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;
|
||||
purpose: "invite" | "reset";
|
||||
}
|
||||
|
||||
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">
|
||||
{invite.purpose === "reset" ? `Reset your password, ${invite.name}` : `Welcome, ${invite.name}`}
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-depth-600">
|
||||
{invite.purpose === "reset" ? "Choose a new password. Every device signed in to your account will be signed out." : "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>
|
||||
);
|
||||
}
|
||||
+73
-4
@@ -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";
|
||||
@@ -12,6 +12,18 @@ interface ActiveDevice {
|
||||
lastUsedAt: string;
|
||||
}
|
||||
|
||||
interface BusinessChoice {
|
||||
businessId: string;
|
||||
businessName: string;
|
||||
role: string;
|
||||
}
|
||||
|
||||
const ROLE_LABELS: Record<string, string> = {
|
||||
SUPER_ADMIN: "Owner",
|
||||
BRANCH_MANAGER: "Branch manager",
|
||||
DELIVERY: "Cashier",
|
||||
};
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const [email, setEmail] = useState("");
|
||||
@@ -21,9 +33,21 @@ export default function LoginPage() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deviceConflict, setDeviceConflict] = useState<ActiveDevice[] | null>(null);
|
||||
// Set when this email and password open accounts in more than one business.
|
||||
const [choices, setChoices] = useState<BusinessChoice[] | null>(null);
|
||||
const [invited, setInvited] = useState(false);
|
||||
const [showForgot, setShowForgot] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setInvited(new URLSearchParams(window.location.search).get("invited") === "1");
|
||||
}, []);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
await signIn();
|
||||
}
|
||||
|
||||
async function signIn(businessId?: string) {
|
||||
setError(null);
|
||||
setDeviceConflict(null);
|
||||
setLoading(true);
|
||||
@@ -36,11 +60,15 @@ export default function LoginPage() {
|
||||
password,
|
||||
deviceId: getDeviceId(),
|
||||
deviceLabel: getDeviceLabel(),
|
||||
businessId,
|
||||
}),
|
||||
});
|
||||
router.replace(result.redirectTo);
|
||||
return;
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 409) {
|
||||
if (err instanceof ApiError && err.status === 300) {
|
||||
setChoices((err.body?.chooseBusiness as BusinessChoice[]) ?? []);
|
||||
} else if (err instanceof ApiError && err.status === 409) {
|
||||
setDeviceConflict((err.body?.activeDevices as ActiveDevice[]) ?? []);
|
||||
setError(err.message);
|
||||
} else if (err instanceof ApiError) {
|
||||
@@ -70,7 +98,35 @@ export default function LoginPage() {
|
||||
Run every branch with confidence — sales, stock, M-Pesa and cash.
|
||||
</p>
|
||||
|
||||
{deviceConflict ? (
|
||||
{choices && !deviceConflict ? (
|
||||
<div className="mt-8">
|
||||
<p className="text-sm font-medium text-depth-800">Which business do you want to sign in to?</p>
|
||||
{error && choices.length === 0 && <p className="mt-2 text-sm text-alert-600">{error}</p>}
|
||||
<ul className="mt-3 space-y-2">
|
||||
{choices.map((c) => (
|
||||
<li key={c.businessId}>
|
||||
<button
|
||||
onClick={() => signIn(c.businessId)}
|
||||
disabled={loading}
|
||||
className="tap-target flex w-full items-center justify-between rounded-xl2 border border-depth-200 bg-white px-4 text-left transition hover:border-flow-500 disabled:opacity-60"
|
||||
>
|
||||
<span className="font-medium text-depth-900">{c.businessName}</span>
|
||||
<span className="text-xs text-depth-500">{ROLE_LABELS[c.role] ?? c.role}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<button
|
||||
onClick={() => {
|
||||
setChoices(null);
|
||||
setError(null);
|
||||
}}
|
||||
className="mt-4 text-sm text-depth-500 underline underline-offset-2"
|
||||
>
|
||||
Use a different email
|
||||
</button>
|
||||
</div>
|
||||
) : deviceConflict ? (
|
||||
<div className="mt-8 rounded-xl2 border border-alert-500/30 bg-alert-500/10 p-4">
|
||||
<p className="text-sm font-medium text-alert-600">{error}</p>
|
||||
<ul className="mt-3 space-y-2">
|
||||
@@ -171,9 +227,22 @@ export default function LoginPage() {
|
||||
/>
|
||||
Remember me
|
||||
</label>
|
||||
<span className="font-medium text-flow-600">Forgot password?</span>
|
||||
<button type="button" onClick={() => setShowForgot((v) => !v)} className="font-medium text-flow-600">
|
||||
Forgot password?
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showForgot && (
|
||||
<p className="rounded-lg bg-sand-100 px-3 py-2 text-sm text-depth-700">
|
||||
Ask your branch manager or business owner for a password reset link (Staff page, Reset password). If
|
||||
you are the owner, contact Digital Chances support for one.
|
||||
</p>
|
||||
)}
|
||||
{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}
|
||||
|
||||
+3
-1
@@ -12,7 +12,9 @@ export default function RootPage() {
|
||||
(async () => {
|
||||
try {
|
||||
const result = await apiFetch<{ user: AuthUser }>("/api/auth/me");
|
||||
if (result.user.role === "DELIVERY") {
|
||||
if (result.user.isPlatformAdmin) {
|
||||
router.replace("/platform");
|
||||
} else if (result.user.role === "DELIVERY") {
|
||||
router.replace("/terminal");
|
||||
} else {
|
||||
router.replace("/admin/dashboard");
|
||||
|
||||
@@ -6,6 +6,7 @@ import { apiFetch, ApiError } from "@/lib/api";
|
||||
import { AuthUser } from "@/lib/types";
|
||||
import { useToast } from "@/components/ui/Toast";
|
||||
import { SkeletonList } from "@/components/ui/Skeleton";
|
||||
import AccountLinks from "@/components/AccountLinks";
|
||||
|
||||
type TierId = "STARTER" | "GROWTH" | "ENTERPRISE";
|
||||
type SubStatus = "TRIALING" | "ACTIVE" | "PAST_DUE" | "SUSPENDED";
|
||||
@@ -63,6 +64,7 @@ export default function PlatformPage() {
|
||||
const [stats, setStats] = useState<Stats | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [savingId, setSavingId] = useState<string | null>(null);
|
||||
const [ownerLink, setOwnerLink] = useState<{ business: string; name: string; email: string; url: string } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
@@ -107,6 +109,23 @@ export default function PlatformPage() {
|
||||
setSavingId(null);
|
||||
}
|
||||
|
||||
// A one-time password link for a business's owner (an owner who forgot
|
||||
// their password has nobody inside the business who can reset it).
|
||||
async function ownerReset(b: BizRow) {
|
||||
if (!window.confirm(`Create a password link for the owner of ${b.name}? Send it only to the owner, by a channel you know is theirs.`)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const r = await apiFetch<{ inviteUrl: string; email: string; name: string }>(
|
||||
"/api/platform/businesses/" + b.id + "/owner-reset",
|
||||
{ method: "POST" }
|
||||
);
|
||||
setOwnerLink({ business: b.name, name: r.name, email: r.email, url: r.inviteUrl });
|
||||
} catch (err) {
|
||||
show(err instanceof ApiError ? err.message : "Could not create the link", "error");
|
||||
}
|
||||
}
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<main className="min-h-screen bg-depth-950 pb-12">
|
||||
@@ -130,6 +149,12 @@ export default function PlatformPage() {
|
||||
Every business on your platform, across all tenants. Change plans, extend billing periods,
|
||||
and suspend accounts here.
|
||||
</p>
|
||||
<div className="mt-3 flex items-center gap-4">
|
||||
<a href="/admin/dashboard" className="text-sm text-sand-200/70 underline underline-offset-2 hover:text-white">
|
||||
Your business dashboard
|
||||
</a>
|
||||
<AccountLinks />
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -144,6 +169,28 @@ export default function PlatformPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{ownerLink && (
|
||||
<div className="rounded-xl2 border border-confirm-500/30 bg-confirm-500/10 p-4 text-sm">
|
||||
<p className="font-medium text-white">
|
||||
Password link for {ownerLink.name} ({ownerLink.email}), owner of {ownerLink.business}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-white/60">
|
||||
It works once and expires within 24 hours (7 days if they never set a password). Whoever opens it can take
|
||||
over the account: send it only to the owner, by a channel you know is theirs.
|
||||
</p>
|
||||
<input
|
||||
readOnly
|
||||
value={ownerLink.url}
|
||||
onFocus={(e) => e.target.select()}
|
||||
aria-label="Owner password link"
|
||||
className="mt-3 w-full rounded-lg border border-white/20 bg-depth-900 px-3 py-2 font-mono text-xs text-white"
|
||||
/>
|
||||
<button onClick={() => setOwnerLink(null)} className="mt-2 text-xs text-white/60 underline">
|
||||
Done
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<SkeletonList rows={4} />
|
||||
) : rows.length === 0 ? (
|
||||
@@ -158,6 +205,7 @@ export default function PlatformPage() {
|
||||
b={b}
|
||||
saving={savingId === b.id}
|
||||
onPatch={patch}
|
||||
onOwnerReset={ownerReset}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -180,10 +228,12 @@ function BusinessCard({
|
||||
b,
|
||||
saving,
|
||||
onPatch,
|
||||
onOwnerReset,
|
||||
}: {
|
||||
b: BizRow;
|
||||
saving: boolean;
|
||||
onPatch: (id: string, update: Record<string, unknown>, label: string) => void;
|
||||
onOwnerReset: (b: BizRow) => void;
|
||||
}) {
|
||||
const overBranches = b.maxBranches !== null && b.branchCount > b.maxBranches;
|
||||
const overUsers = b.maxUsers !== null && b.userCount > b.maxUsers;
|
||||
@@ -287,6 +337,15 @@ function BusinessCard({
|
||||
Reactivate
|
||||
</button>
|
||||
)}
|
||||
{b.owner && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOwnerReset(b)}
|
||||
className="tap-target rounded-xl2 border border-white/20 px-4 text-sm font-medium text-white/80"
|
||||
>
|
||||
Owner password link
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
+75
-15
@@ -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,12 @@ import {
|
||||
queueSale,
|
||||
registerOfflineSync,
|
||||
salesFor,
|
||||
unsyncedQuantities,
|
||||
type QueuedSale,
|
||||
type QueueOwner,
|
||||
} from "@/lib/offlineQueue";
|
||||
import { clearSession, loadSession, saveSession } from "@/lib/sessionCache";
|
||||
import { loadSession, saveSession, type StockSnapshot } from "@/lib/sessionCache";
|
||||
import { signOut } from "@/lib/signOut";
|
||||
import { MAX_LINES_PER_SALE } from "@/lib/syncProtocol";
|
||||
import { useToast } from "@/components/ui/Toast";
|
||||
import ProductGrid from "@/components/terminal/ProductGrid";
|
||||
@@ -51,6 +53,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 +79,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 +142,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 +178,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 +249,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 +285,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 +293,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));
|
||||
@@ -340,12 +393,7 @@ export default function TerminalPage() {
|
||||
);
|
||||
if (!ok) return;
|
||||
}
|
||||
try {
|
||||
await apiFetch("/api/auth/logout", { method: "POST" });
|
||||
} catch {
|
||||
// Offline: the cookies expire on their own; still clear this device.
|
||||
}
|
||||
clearSession();
|
||||
await signOut();
|
||||
router.replace("/login");
|
||||
}
|
||||
|
||||
@@ -399,9 +447,14 @@ export default function TerminalPage() {
|
||||
>
|
||||
{connected ? "● Online" : "● Offline"}
|
||||
</span>
|
||||
<button onClick={handleSignOut} className="text-xs text-sand-200/60 underline underline-offset-2">
|
||||
Sign out
|
||||
</button>
|
||||
<div className="flex gap-3">
|
||||
<button onClick={() => router.push("/account/password")} className="text-xs text-sand-200/60 underline underline-offset-2">
|
||||
Password
|
||||
</button>
|
||||
<button onClick={handleSignOut} className="text-xs text-sand-200/60 underline underline-offset-2">
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
@@ -450,7 +503,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 +544,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>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { signOut } from "@/lib/signOut";
|
||||
|
||||
/** Change password + Sign out, for the dark page headers. */
|
||||
export default function AccountLinks() {
|
||||
const router = useRouter();
|
||||
return (
|
||||
<div className="flex items-center gap-3 whitespace-nowrap text-sm">
|
||||
<Link href="/account/password" className="text-sand-200/70 underline underline-offset-2 hover:text-white">
|
||||
Change password
|
||||
</Link>
|
||||
<button
|
||||
onClick={async () => {
|
||||
await signOut();
|
||||
router.replace("/login");
|
||||
}}
|
||||
className="text-sand-200/70 underline underline-offset-2 hover:text-white"
|
||||
>
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,11 +5,13 @@ import { Product } from "@/lib/types";
|
||||
interface Props {
|
||||
products: Product[];
|
||||
quantities: Record<string, number>;
|
||||
/** Stock left at this branch after this phone's own sales; null if unknown. */
|
||||
stock: Record<string, number> | null;
|
||||
onAdd: (productId: string) => void;
|
||||
}
|
||||
|
||||
/** One tap adds one unit of a product to the current sale. */
|
||||
export default function ProductGrid({ products, quantities, onAdd }: Props) {
|
||||
export default function ProductGrid({ products, quantities, stock, onAdd }: Props) {
|
||||
if (products.length === 0) {
|
||||
return (
|
||||
<div className="rounded-xl2 border border-dashed border-depth-200 bg-white p-4 text-center text-sm text-depth-500">
|
||||
@@ -37,6 +39,16 @@ export default function ProductGrid({ products, quantities, onAdd }: Props) {
|
||||
>
|
||||
<span className="font-display text-sm font-bold leading-tight text-depth-900">{p.label}</span>
|
||||
<span className="font-mono text-xs text-depth-500">KES {p.unitPrice.toLocaleString()}</span>
|
||||
{stock && (
|
||||
<span
|
||||
className={
|
||||
"text-xs font-medium " +
|
||||
((stock[p._id] ?? 0) - inCart <= 0 ? "text-alert-600" : "text-depth-500")
|
||||
}
|
||||
>
|
||||
{Math.max((stock[p._id] ?? 0) - inCart, 0)} in stock
|
||||
</span>
|
||||
)}
|
||||
{inCart > 0 && (
|
||||
<span className="absolute right-2 top-2 flex h-6 min-w-6 items-center justify-center rounded-full bg-flow-500 px-1.5 font-mono text-xs font-bold text-white">
|
||||
{inCart}
|
||||
|
||||
@@ -108,6 +108,23 @@ export async function queueCounts(userId: string): Promise<{ pending: number; re
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Units this cashier has sold that the given server stock snapshot does
|
||||
* not include yet: sales still pending, plus sales that synced after the
|
||||
* snapshot was taken. Subtracting these from the snapshot gives the stock
|
||||
* the till should show right now, online or offline.
|
||||
*/
|
||||
export function unsyncedQuantities(rows: QueuedSale[], snapshotAt: string | null): Record<string, number> {
|
||||
const out: Record<string, number> = {};
|
||||
for (const row of rows) {
|
||||
const notInSnapshot =
|
||||
row.state === "pending" || (row.state === "synced" && (!snapshotAt || (row.syncedAt ?? "") > snapshotAt));
|
||||
if (!notInSnapshot) continue;
|
||||
for (const l of row.lines) out[l.productId] = (out[l.productId] ?? 0) + l.quantity;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The cashier has acknowledged a rejected sale (e.g. reported it to the manager). */
|
||||
export async function dismissRejected(clientUuid: string): Promise<void> {
|
||||
const db = await getDb();
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import mongoose, { Types } from "mongoose";
|
||||
import { StockMovement, type MovementType } from "@/lib/server/models/StockMovement";
|
||||
import { Purchase } from "@/lib/server/models/Purchase";
|
||||
|
||||
/**
|
||||
* Cost of goods sold, first-in-first-out, per branch.
|
||||
*
|
||||
* The stock ledger is replayed in order. Each branch keeps, per product, a
|
||||
* queue of cost layers (quantity at a unit cost). Stock coming in adds a
|
||||
* layer; stock going out takes from the oldest layers first:
|
||||
*
|
||||
* PURCHASE in, at the purchase's unit cost
|
||||
* TRANSFER_IN in, at the cost of the layers the sending branch gave up
|
||||
* ADJUSTMENT + in (opening stock, a count that found more), at an
|
||||
* estimated cost: the latest purchase price for the product
|
||||
* at that time, or the first one after it if none yet
|
||||
* SALE out: its cost is cost of goods sold
|
||||
* TRANSFER_OUT out: its cost travels with the stock to the other branch
|
||||
* ADJUSTMENT - out (breakage, a count that found less): its cost is a
|
||||
* stock loss, reported separately from cost of goods
|
||||
*
|
||||
* Stock can go negative (an offline sale recorded before the stock it came
|
||||
* from). The units sold short wait as a deficit and are costed by the next
|
||||
* stock that arrives at that branch, which is where they must have come
|
||||
* from. Units still uncosted at the end are reported as unitsWithoutCost.
|
||||
*
|
||||
* The replay reads the whole history, in order, so a sale is costed against
|
||||
* what was actually on hand when it happened, whatever period is being
|
||||
* reported; only events inside the period (and branch) are added up. A sale
|
||||
* made short in the period is costed by stock that arrived later, even
|
||||
* after the period ended.
|
||||
*/
|
||||
|
||||
type Id = Types.ObjectId | string;
|
||||
|
||||
interface Layer {
|
||||
qty: number;
|
||||
unitCost: number | null; // null: cost unknown
|
||||
}
|
||||
|
||||
interface Deficit {
|
||||
qty: number;
|
||||
kind: "sale" | "loss" | "transfer";
|
||||
counts: boolean; // inside the reported period and branch
|
||||
}
|
||||
|
||||
interface Position {
|
||||
layers: Layer[];
|
||||
deficits: Deficit[];
|
||||
}
|
||||
|
||||
export interface CostOfGoods {
|
||||
costOfGoodsSold: number;
|
||||
unitsCosted: number; // units sold in the period that have a cost
|
||||
unitsWithoutCost: number; // units sold in the period whose cost is unknown
|
||||
stockLosses: number; // cost of stock written off by counts or adjustments in the period
|
||||
}
|
||||
|
||||
// Process transfers' outgoing side before the incoming side, so the cost is known.
|
||||
const TYPE_ORDER: Record<MovementType, number> = {
|
||||
PURCHASE: 0,
|
||||
ADJUSTMENT: 1,
|
||||
TRANSFER_OUT: 2,
|
||||
TRANSFER_IN: 3,
|
||||
SALE: 4,
|
||||
};
|
||||
|
||||
const round2 = (n: number) => Math.round(n * 100) / 100;
|
||||
|
||||
/** Take `qty` units from the front of `layers`; returns what was taken and the shortfall. */
|
||||
function take(layers: Layer[], qty: number): { taken: Layer[]; short: number } {
|
||||
const taken: Layer[] = [];
|
||||
let need = qty;
|
||||
while (need > 0 && layers.length > 0) {
|
||||
const head = layers[0];
|
||||
const n = Math.min(head.qty, need);
|
||||
taken.push({ qty: n, unitCost: head.unitCost });
|
||||
head.qty -= n;
|
||||
need -= n;
|
||||
if (head.qty === 0) layers.shift();
|
||||
}
|
||||
return { taken, short: need };
|
||||
}
|
||||
|
||||
export async function costOfGoodsSold(
|
||||
businessId: Id,
|
||||
period: { from: Date; to: Date; branchId?: Id | null }
|
||||
): Promise<CostOfGoods> {
|
||||
const biz = new mongoose.Types.ObjectId(businessId.toString());
|
||||
const branchFilter = period.branchId ? period.branchId.toString() : null;
|
||||
|
||||
const [movements, purchases] = await Promise.all([
|
||||
StockMovement.find({ businessId: biz })
|
||||
.select("branchId productId type quantity refId createdAt")
|
||||
.sort({ createdAt: 1, _id: 1 })
|
||||
.lean(),
|
||||
Purchase.find({ businessId: biz, productId: { $ne: null } })
|
||||
.select("productId unitCost createdAt")
|
||||
.sort({ createdAt: 1 })
|
||||
.lean(),
|
||||
]);
|
||||
movements.sort(
|
||||
(a, b) => a.createdAt.getTime() - b.createdAt.getTime() || TYPE_ORDER[a.type] - TYPE_ORDER[b.type]
|
||||
);
|
||||
|
||||
const purchaseCost = new Map(purchases.map((p) => [p._id.toString(), p.unitCost]));
|
||||
const priceHistory = new Map<string, { at: number; unitCost: number }[]>();
|
||||
for (const p of purchases) {
|
||||
const key = p.productId!.toString();
|
||||
if (!priceHistory.has(key)) priceHistory.set(key, []);
|
||||
priceHistory.get(key)!.push({ at: p.createdAt.getTime(), unitCost: p.unitCost });
|
||||
}
|
||||
const estimateCost = (productId: string, at: number): number | null => {
|
||||
const history = priceHistory.get(productId);
|
||||
if (!history || history.length === 0) return null;
|
||||
let latest: number | null = null;
|
||||
for (const h of history) {
|
||||
if (h.at <= at) latest = h.unitCost;
|
||||
else break;
|
||||
}
|
||||
return latest ?? history[0].unitCost;
|
||||
};
|
||||
|
||||
const positions = new Map<string, Position>();
|
||||
const position = (branch: string, product: string) => {
|
||||
const key = `${branch}:${product}`;
|
||||
if (!positions.has(key)) positions.set(key, { layers: [], deficits: [] });
|
||||
return positions.get(key)!;
|
||||
};
|
||||
const inTransit = new Map<string, Layer[]>(); // transfer refId -> layers given up by the sender
|
||||
|
||||
const result = { costOfGoodsSold: 0, unitsCosted: 0, unitsWithoutCost: 0, stockLosses: 0 };
|
||||
const charge = (kind: Deficit["kind"], layers: Layer[]) => {
|
||||
for (const l of layers) {
|
||||
if (kind === "sale") {
|
||||
if (l.unitCost === null) result.unitsWithoutCost += l.qty;
|
||||
else {
|
||||
result.costOfGoodsSold += l.qty * l.unitCost;
|
||||
result.unitsCosted += l.qty;
|
||||
}
|
||||
} else if (kind === "loss" && l.unitCost !== null) {
|
||||
result.stockLosses += l.qty * l.unitCost;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
for (const m of movements) {
|
||||
const branch = m.branchId.toString();
|
||||
const product = m.productId.toString();
|
||||
const pos = position(branch, product);
|
||||
const at = m.createdAt.getTime();
|
||||
const counts =
|
||||
at >= period.from.getTime() && at < period.to.getTime() && (!branchFilter || branch === branchFilter);
|
||||
|
||||
if (m.quantity > 0) {
|
||||
let incoming: Layer[];
|
||||
if (m.type === "PURCHASE") incoming = [{ qty: m.quantity, unitCost: purchaseCost.get(m.refId) ?? null }];
|
||||
else if (m.type === "TRANSFER_IN") incoming = (inTransit.get(m.refId) ?? [{ qty: m.quantity, unitCost: null }]).map((l) => ({ ...l }));
|
||||
else incoming = [{ qty: m.quantity, unitCost: estimateCost(product, at) }];
|
||||
|
||||
// Stock that was already sold short is covered first, at this stock's cost.
|
||||
while (pos.deficits.length > 0 && incoming.length > 0) {
|
||||
const d = pos.deficits[0];
|
||||
const { taken, short } = take(incoming, d.qty);
|
||||
if (d.counts) charge(d.kind, taken);
|
||||
d.qty = short;
|
||||
if (d.qty === 0) pos.deficits.shift();
|
||||
}
|
||||
pos.layers.push(...incoming);
|
||||
} else if (m.quantity < 0) {
|
||||
const kind: Deficit["kind"] = m.type === "SALE" ? "sale" : m.type === "TRANSFER_OUT" ? "transfer" : "loss";
|
||||
const { taken, short } = take(pos.layers, -m.quantity);
|
||||
if (kind === "transfer") {
|
||||
// The receiving branch inherits this cost; any shortfall arrives with no known cost.
|
||||
inTransit.set(m.refId, short > 0 ? [...taken, { qty: short, unitCost: null }] : taken);
|
||||
} else if (counts) {
|
||||
charge(kind, taken);
|
||||
}
|
||||
if (short > 0) pos.deficits.push({ qty: short, kind, counts: counts && kind !== "transfer" });
|
||||
}
|
||||
}
|
||||
|
||||
// Short sales in the period that no later stock has covered yet.
|
||||
for (const pos of positions.values()) {
|
||||
for (const d of pos.deficits) if (d.counts && d.kind === "sale") result.unitsWithoutCost += d.qty;
|
||||
}
|
||||
|
||||
return {
|
||||
costOfGoodsSold: round2(result.costOfGoodsSold),
|
||||
unitsCosted: result.unitsCosted,
|
||||
unitsWithoutCost: result.unitsWithoutCost,
|
||||
stockLosses: round2(result.stockLosses),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import crypto from "crypto";
|
||||
import bcrypt from "bcryptjs";
|
||||
import type { NextRequest } from "next/server";
|
||||
import type { IUser } from "@/lib/server/models/User";
|
||||
|
||||
export const INVITE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
/** Reset links are shorter-lived: they can take over an account that is already in use. */
|
||||
export const RESET_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
export type LinkPurpose = "invite" | "reset";
|
||||
|
||||
export function hashInviteToken(token: string): string {
|
||||
return crypto.createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
/** A password nobody knows, for an account whose owner has not accepted their invite yet. */
|
||||
export async function unusablePasswordHash(): Promise<string> {
|
||||
return bcrypt.hash(crypto.randomBytes(32).toString("hex"), 12);
|
||||
}
|
||||
|
||||
/** Whether the account is waiting for its first password (not a reset). */
|
||||
export function invitePending(user: Pick<IUser, "inviteExpiresAt" | "invitePurpose">): boolean {
|
||||
return !!user.inviteExpiresAt && user.invitePurpose !== "reset";
|
||||
}
|
||||
|
||||
/**
|
||||
* Give the user a fresh one-time password link (any earlier link stops
|
||||
* working) and return it to send them. The caller saves the user.
|
||||
*/
|
||||
export function issueInvite(user: IUser, req: NextRequest, purpose: LinkPurpose = "invite"): string {
|
||||
const token = crypto.randomBytes(32).toString("base64url");
|
||||
user.inviteTokenHash = hashInviteToken(token);
|
||||
user.inviteExpiresAt = new Date(Date.now() + (purpose === "reset" ? RESET_TTL_MS : INVITE_TTL_MS));
|
||||
user.invitePurpose = purpose;
|
||||
const origin = process.env.APP_URL?.replace(/\/$/, "") || req.nextUrl.origin;
|
||||
return `${origin}/invite/${token}`;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { tenantGuard } from "@/lib/server/tenantGuard";
|
||||
import { Schema, model, models, Model, Types, Document } from "mongoose";
|
||||
|
||||
export interface IBranch extends Document {
|
||||
@@ -6,6 +7,12 @@ export interface IBranch extends Document {
|
||||
branchName: string;
|
||||
locationCity: string;
|
||||
managerId: Types.ObjectId | null;
|
||||
// A deactivated branch keeps all its sales, purchases and stock history
|
||||
// and still appears in reports for past periods, but takes no new staff,
|
||||
// transfers or purchases and does not count towards the plan's limit.
|
||||
// Rows created before this field existed have no value: treat as active
|
||||
// (query with `isActive: { $ne: false }`).
|
||||
isActive: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
@@ -16,9 +23,15 @@ const branchSchema = new Schema<IBranch>(
|
||||
branchName: { type: String, required: true, trim: true },
|
||||
locationCity: { type: String, required: true, trim: true },
|
||||
managerId: { type: Schema.Types.ObjectId, ref: "User", default: null },
|
||||
isActive: { type: Boolean, default: true },
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
/** Filter for branches that are in use. */
|
||||
export const ACTIVE_BRANCH = { isActive: { $ne: false } } as const;
|
||||
|
||||
branchSchema.plugin(tenantGuard);
|
||||
|
||||
export const Branch =
|
||||
(models.Branch as Model<IBranch>) || model<IBranch>("Branch", branchSchema);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { tenantGuard } from "@/lib/server/tenantGuard";
|
||||
import { Schema, model, models, Model, Types, Document } from "mongoose";
|
||||
|
||||
export interface IDailyInventory extends Document {
|
||||
@@ -40,6 +41,8 @@ dailyInventorySchema.index({ branchId: 1, date: 1 });
|
||||
// One ledger row per branch+product+day.
|
||||
dailyInventorySchema.index({ branchId: 1, productId: 1, date: 1 }, { unique: true });
|
||||
|
||||
dailyInventorySchema.plugin(tenantGuard);
|
||||
|
||||
export const DailyInventory =
|
||||
(models.DailyInventory as Model<IDailyInventory>) ||
|
||||
model<IDailyInventory>("DailyInventory", dailyInventorySchema);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { tenantGuard } from "@/lib/server/tenantGuard";
|
||||
import { Schema, model, models, Model, Types, Document } from "mongoose";
|
||||
|
||||
// Business expense categories. Kept as a constrained string set so the UI
|
||||
@@ -46,5 +47,7 @@ expenseSchema.index({ category: 1 });
|
||||
|
||||
// `models.Expense` guard avoids OverwriteModelError on serverless warm
|
||||
// re-invocations where the module is evaluated more than once.
|
||||
expenseSchema.plugin(tenantGuard);
|
||||
|
||||
export const Expense =
|
||||
(models.Expense as Model<IExpense>) || model<IExpense>("Expense", expenseSchema);
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { tenantGuard } from "@/lib/server/tenantGuard";
|
||||
import { Schema, model, models, Model, Types, Document } from "mongoose";
|
||||
|
||||
export interface IProduct extends Document {
|
||||
_id: Types.ObjectId;
|
||||
businessId: Types.ObjectId; // tenant this product belongs to
|
||||
label: string;
|
||||
// Size measured in `unit` (litres for water, a count for side items).
|
||||
// The field keeps its historical name so existing data needs no migration.
|
||||
sizeLiters: number;
|
||||
unit: string; // display unit, e.g. "L" for water, "pcs" / "tray" for eggs
|
||||
unit: string; // see PRODUCT_UNITS in src/lib/units.ts: "L", "pcs", "tray"...
|
||||
category: string; // e.g. "Water", "Eggs"
|
||||
unitPrice: number;
|
||||
sortOrder: number;
|
||||
@@ -30,6 +33,8 @@ const productSchema = new Schema<IProduct>(
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
productSchema.plugin(tenantGuard);
|
||||
|
||||
export const Product =
|
||||
(models.Product as Model<IProduct>) || model<IProduct>("Product", productSchema);
|
||||
|
||||
@@ -39,6 +44,7 @@ export interface IBranchPricing extends Document {
|
||||
branchId: Types.ObjectId;
|
||||
productId: Types.ObjectId;
|
||||
unitPrice: number;
|
||||
updatedBy: Types.ObjectId | null;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
@@ -48,11 +54,14 @@ const branchPricingSchema = new Schema<IBranchPricing>(
|
||||
branchId: { type: Schema.Types.ObjectId, ref: "Branch", required: true },
|
||||
productId: { type: Schema.Types.ObjectId, ref: "Product", required: true },
|
||||
unitPrice: { type: Number, required: true, min: 0 },
|
||||
updatedBy: { type: Schema.Types.ObjectId, ref: "User", default: null },
|
||||
},
|
||||
{ timestamps: { createdAt: false, updatedAt: true } }
|
||||
);
|
||||
branchPricingSchema.index({ branchId: 1, productId: 1 }, { unique: true });
|
||||
|
||||
branchPricingSchema.plugin(tenantGuard);
|
||||
|
||||
export const BranchPricing =
|
||||
(models.BranchPricing as Model<IBranchPricing>) ||
|
||||
model<IBranchPricing>("BranchPricing", branchPricingSchema);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { tenantGuard } from "@/lib/server/tenantGuard";
|
||||
import { Schema, model, models, Model, Types, Document } from "mongoose";
|
||||
|
||||
// A recorded stock purchase from a supplier. Completing a purchase is what
|
||||
@@ -40,5 +41,7 @@ const purchaseSchema = new Schema<IPurchase>(
|
||||
purchaseSchema.index({ branchId: 1, createdAt: -1 });
|
||||
purchaseSchema.index({ productId: 1 });
|
||||
|
||||
purchaseSchema.plugin(tenantGuard);
|
||||
|
||||
export const Purchase =
|
||||
(models.Purchase as Model<IPurchase>) || model<IPurchase>("Purchase", purchaseSchema);
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Schema, model, models, Model } from "mongoose";
|
||||
|
||||
export interface IStockLock {
|
||||
_id: string; // `${businessId}:${branchId}:${productId}`
|
||||
owner: string; // random id of the request holding the lock
|
||||
lockedUntil: Date; // lease expiry: a crashed request cannot hold the lock forever
|
||||
}
|
||||
|
||||
/**
|
||||
* A short lease on one product's stock at one branch, held while a request
|
||||
* reads the current balance and writes a movement that depends on it (see
|
||||
* withStockLock in src/lib/server/stock.ts). Rows are deleted on release;
|
||||
* an expired row is simply taken over by the next request.
|
||||
*/
|
||||
const stockLockSchema = new Schema<IStockLock>(
|
||||
{
|
||||
_id: { type: String, required: true },
|
||||
owner: { type: String, required: true },
|
||||
lockedUntil: { type: Date, required: true },
|
||||
},
|
||||
{ versionKey: false }
|
||||
);
|
||||
|
||||
export const StockLock =
|
||||
(models.StockLock as Model<IStockLock>) || model<IStockLock>("StockLock", stockLockSchema);
|
||||
@@ -1,3 +1,4 @@
|
||||
import { tenantGuard } from "@/lib/server/tenantGuard";
|
||||
import { Schema, model, models, Model, Types, Document } from "mongoose";
|
||||
|
||||
export const MOVEMENT_TYPES = ["SALE", "PURCHASE", "TRANSFER_OUT", "TRANSFER_IN", "ADJUSTMENT"] as const;
|
||||
@@ -46,6 +47,8 @@ stockMovementSchema.index({ type: 1, refId: 1 }, { unique: true });
|
||||
stockMovementSchema.index({ businessId: 1, branchId: 1, productId: 1 });
|
||||
stockMovementSchema.index({ businessId: 1, branchId: 1, createdAt: -1 });
|
||||
|
||||
stockMovementSchema.plugin(tenantGuard);
|
||||
|
||||
export const StockMovement =
|
||||
(models.StockMovement as Model<IStockMovement>) ||
|
||||
model<IStockMovement>("StockMovement", stockMovementSchema);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { tenantGuard } from "@/lib/server/tenantGuard";
|
||||
import { Schema, model, models, Model, Types, Document } from "mongoose";
|
||||
|
||||
export interface IStockTransfer extends Document {
|
||||
@@ -35,6 +36,8 @@ const stockTransferSchema = new Schema<IStockTransfer>(
|
||||
stockTransferSchema.index({ businessId: 1, clientUuid: 1 }, { unique: true });
|
||||
stockTransferSchema.index({ businessId: 1, createdAt: -1 });
|
||||
|
||||
stockTransferSchema.plugin(tenantGuard);
|
||||
|
||||
export const StockTransfer =
|
||||
(models.StockTransfer as Model<IStockTransfer>) ||
|
||||
model<IStockTransfer>("StockTransfer", stockTransferSchema);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { tenantGuard } from "@/lib/server/tenantGuard";
|
||||
import { Schema, model, models, Model, Types, Document } from "mongoose";
|
||||
|
||||
export type PaymentMethod = "CASH" | "MPESA";
|
||||
@@ -105,6 +106,8 @@ transactionSchema.index({ businessId: 1, createdAt: -1 });
|
||||
transactionSchema.index({ paymentStatus: 1 });
|
||||
transactionSchema.index({ businessId: 1, saleId: 1 });
|
||||
|
||||
transactionSchema.plugin(tenantGuard);
|
||||
|
||||
export const Transaction =
|
||||
(models.Transaction as Model<ITransaction>) ||
|
||||
model<ITransaction>("Transaction", transactionSchema);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { tenantGuard } from "@/lib/server/tenantGuard";
|
||||
import { Schema, model, models, Model, Types, Document } from "mongoose";
|
||||
import bcrypt from "bcryptjs";
|
||||
|
||||
@@ -10,12 +11,29 @@ export interface IUser extends Document {
|
||||
name: string;
|
||||
role: UserRole;
|
||||
branchId: Types.ObjectId | null; // null only valid for SUPER_ADMIN (business owner)
|
||||
// Email and phone are unique WITHIN a business, not across the platform,
|
||||
// so one person can work for two businesses (each account has its own
|
||||
// password and role). Login asks which business when the same email and
|
||||
// password match accounts in more than one.
|
||||
phoneNumber: string; // E.164-ish normalized Kenyan format — kept for contact/M-Pesa reference, not used for login
|
||||
email: string; // login identifier for every role, via the single /login page
|
||||
// Platform operator (cross-tenant console). Only set by `npm run seed` or
|
||||
// the identity migration, never through the app, and only honoured while
|
||||
// the email is also listed in PLATFORM_ADMIN_EMAILS.
|
||||
platformAdmin: boolean;
|
||||
passwordHash: string;
|
||||
isActive: boolean;
|
||||
failedLoginAttempts: number;
|
||||
lockedUntil: Date | null;
|
||||
// A one-time link through which the person sets their own password.
|
||||
// Only the SHA-256 of the token is stored.
|
||||
// invite: a new account; until accepted it has a random unknown password.
|
||||
// reset: a forgotten password; the old password keeps working until the
|
||||
// link is used, and using it signs the account out everywhere.
|
||||
// Rows from before invitePurpose existed have null, which means invite.
|
||||
inviteTokenHash: string | null;
|
||||
inviteExpiresAt: Date | null;
|
||||
invitePurpose: "invite" | "reset" | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
|
||||
@@ -28,16 +46,27 @@ const userSchema = new Schema<IUser>(
|
||||
name: { type: String, required: true, trim: true },
|
||||
role: { type: String, enum: USER_ROLES, required: true, default: "DELIVERY" },
|
||||
branchId: { type: Schema.Types.ObjectId, ref: "Branch", default: null },
|
||||
phoneNumber: { type: String, required: true, unique: true, index: true },
|
||||
email: { type: String, required: true, unique: true, lowercase: true, trim: true },
|
||||
phoneNumber: { type: String, required: true },
|
||||
email: { type: String, required: true, lowercase: true, trim: true },
|
||||
platformAdmin: { type: Boolean, default: false },
|
||||
passwordHash: { type: String, required: true, select: false },
|
||||
isActive: { type: Boolean, default: true },
|
||||
failedLoginAttempts: { type: Number, default: 0 },
|
||||
lockedUntil: { type: Date, default: null },
|
||||
inviteTokenHash: { type: String, default: null, index: { sparse: true } },
|
||||
inviteExpiresAt: { type: Date, default: null },
|
||||
invitePurpose: { type: String, enum: ["invite", "reset", null], default: null },
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
userSchema.index({ businessId: 1, email: 1 }, { unique: true });
|
||||
userSchema.index({ businessId: 1, phoneNumber: 1 }, { unique: true });
|
||||
// Login looks an email up across businesses. Named so it never clashes with
|
||||
// the old platform-wide unique `email_1` index, which the identity
|
||||
// migration (npm run migrate:identity) drops.
|
||||
userSchema.index({ email: 1 }, { name: "email_lookup" });
|
||||
|
||||
// Enforce role/branch invariants at the model layer — belt-and-braces
|
||||
// alongside API-level validation. Every role authenticates the same way
|
||||
// now (email + password on the single /login page), so there is no
|
||||
@@ -57,5 +86,7 @@ userSchema.methods.comparePassword = async function (password: string): Promise<
|
||||
return bcrypt.compare(password, this.passwordHash);
|
||||
};
|
||||
|
||||
userSchema.plugin(tenantGuard);
|
||||
|
||||
export const User =
|
||||
(models.User as Model<IUser>) || model<IUser>("User", userSchema);
|
||||
|
||||
@@ -26,21 +26,32 @@ import type { NextRequest } from "next/server";
|
||||
import { getAuth } from "@/lib/server/auth";
|
||||
import { User } from "@/lib/server/models/User";
|
||||
|
||||
/**
|
||||
* Whether this account is a platform operator. Two conditions, because
|
||||
* emails are only unique within a business: any owner can create a staff
|
||||
* account with any email in their own business, so an email match alone
|
||||
* must never grant cross-tenant access. The account must also carry the
|
||||
* platformAdmin flag, which the app never sets (seed/migration only).
|
||||
* Removing an email from PLATFORM_ADMIN_EMAILS revokes access at once.
|
||||
*/
|
||||
export function isPlatformAdmin(user: { email?: string | null; platformAdmin?: boolean | null }): boolean {
|
||||
return user.platformAdmin === true && isPlatformAdminEmail(user.email);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve and authorize the current request as a platform operator.
|
||||
* Returns the authenticated User's id/email on success, or null if the
|
||||
* caller is not a platform admin. The DB must already be connected.
|
||||
*
|
||||
* The JWT has no email, so we re-read the User and match its email
|
||||
* against PLATFORM_ADMIN_EMAILS.
|
||||
*/
|
||||
export async function requirePlatformAdmin(
|
||||
req: NextRequest
|
||||
): Promise<{ userId: string; email: string } | null> {
|
||||
const auth = getAuth(req);
|
||||
if (!auth) return null;
|
||||
const user = await User.findById(auth.sub).select("email isActive").lean();
|
||||
const user = await User.findOne({ _id: auth.sub, businessId: auth.businessId })
|
||||
.select("email isActive platformAdmin")
|
||||
.lean();
|
||||
if (!user || !user.isActive) return null;
|
||||
if (!isPlatformAdminEmail(user.email)) return null;
|
||||
if (!isPlatformAdmin(user)) return null;
|
||||
return { userId: auth.sub, email: user.email };
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Types } from "mongoose";
|
||||
import { Product } from "@/lib/server/models/Product";
|
||||
|
||||
/**
|
||||
* Two products with the same name (ignoring case) would be impossible to
|
||||
* tell apart on the terminal and in reports, so names are unique per
|
||||
* business — including deactivated products, which can be reactivated.
|
||||
*/
|
||||
export async function labelTakenError(
|
||||
businessId: Types.ObjectId | string,
|
||||
label: string,
|
||||
exceptId?: string
|
||||
): Promise<string | null> {
|
||||
const filter: Record<string, unknown> = { businessId, label: label.trim() };
|
||||
if (exceptId) filter._id = { $ne: exceptId };
|
||||
const clash = await Product.findOne(filter).collation({ locale: "en", strength: 2 }).select("label isActive").lean();
|
||||
if (!clash) return null;
|
||||
return clash.isActive
|
||||
? `A product called "${clash.label}" already exists.`
|
||||
: `A deactivated product called "${clash.label}" already exists. Reactivate it instead.`;
|
||||
}
|
||||
+101
-6
@@ -1,7 +1,10 @@
|
||||
import mongoose, { Types } from "mongoose";
|
||||
import { StockMovement, type MovementType } from "@/lib/server/models/StockMovement";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { ACTIVE_BRANCH, Branch } from "@/lib/server/models/Branch";
|
||||
import { Product } from "@/lib/server/models/Product";
|
||||
import { Purchase } from "@/lib/server/models/Purchase";
|
||||
import { StockLock } from "@/lib/server/models/StockLock";
|
||||
import { crossTenant } from "@/lib/server/tenantGuard";
|
||||
import type { ITransaction } from "@/lib/server/models/Transaction";
|
||||
|
||||
type Id = Types.ObjectId | string;
|
||||
@@ -24,7 +27,7 @@ export interface MovementInput {
|
||||
*/
|
||||
export async function recordMovement(m: MovementInput): Promise<void> {
|
||||
await StockMovement.updateOne(
|
||||
{ type: m.type, refId: m.refId },
|
||||
{ type: m.type, refId: m.refId, businessId: m.businessId },
|
||||
{
|
||||
$setOnInsert: {
|
||||
businessId: m.businessId,
|
||||
@@ -89,6 +92,7 @@ export interface StockLevel {
|
||||
quantity: number;
|
||||
lowStockThreshold: number;
|
||||
status: StockStatus;
|
||||
productActive: boolean;
|
||||
}
|
||||
|
||||
export function stockStatus(quantity: number, threshold: number): StockStatus {
|
||||
@@ -98,20 +102,22 @@ export function stockStatus(quantity: number, threshold: number): StockStatus {
|
||||
}
|
||||
|
||||
/**
|
||||
* Stock of every active product at every branch in scope — including
|
||||
* zero rows, so an owner sees "0" rather than a missing product. A
|
||||
* Stock of every active product at every active branch in scope —
|
||||
* including zero rows, so an owner sees "0" rather than a missing product.
|
||||
* A deactivated product is listed too wherever it still has stock, so
|
||||
* units bought before deactivation never silently disappear. 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 };
|
||||
const branchFilter: Record<string, unknown> = { businessId: bizObj, ...ACTIVE_BRANCH };
|
||||
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(),
|
||||
Product.find({ businessId: bizObj }).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" } } },
|
||||
@@ -123,6 +129,7 @@ export async function getStockLevels(businessId: Id, branchId?: Id | null): Prom
|
||||
for (const b of branches) {
|
||||
for (const p of products) {
|
||||
const quantity = totalByKey.get(`${b._id}:${p._id}`) ?? 0;
|
||||
if (!p.isActive && quantity === 0) continue;
|
||||
const lowStockThreshold = p.lowStockThreshold ?? 10;
|
||||
levels.push({
|
||||
branchId: b._id.toString(),
|
||||
@@ -133,8 +140,96 @@ export async function getStockLevels(businessId: Id, branchId?: Id | null): Prom
|
||||
quantity,
|
||||
lowStockThreshold,
|
||||
status: stockStatus(quantity, lowStockThreshold),
|
||||
productActive: p.isActive,
|
||||
});
|
||||
}
|
||||
}
|
||||
return levels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the PURCHASE movement for every catalogue purchase that has none.
|
||||
* Purchases recorded before the stock ledger existed (or while a write
|
||||
* failed) otherwise never show up as stock. Idempotent: run it as often
|
||||
* as you like. Returns how many movements were added.
|
||||
*/
|
||||
export async function backfillPurchaseMovements(businessId?: Id): Promise<number> {
|
||||
const filter: Record<string, unknown> = { productId: { $ne: null } };
|
||||
if (businessId) filter.businessId = new mongoose.Types.ObjectId(businessId.toString());
|
||||
const purchases = businessId
|
||||
? await Purchase.find(filter).lean()
|
||||
: await crossTenant("the backfill runs over every business", () => Purchase.find(filter).lean().exec());
|
||||
|
||||
let added = 0;
|
||||
for (const p of purchases) {
|
||||
const refId = p._id.toString();
|
||||
if (await StockMovement.exists({ type: "PURCHASE", refId, businessId: p.businessId })) continue;
|
||||
await recordMovement({
|
||||
businessId: p.businessId,
|
||||
branchId: p.branchId,
|
||||
productId: p.productId!,
|
||||
type: "PURCHASE",
|
||||
quantity: p.quantity,
|
||||
refId,
|
||||
note: `From ${p.supplierName} (backfilled)`,
|
||||
recordedBy: p.recordedBy,
|
||||
});
|
||||
added += 1;
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
const LOCK_LEASE_MS = 10_000;
|
||||
const LOCK_WAIT_MS = 5_000;
|
||||
|
||||
/** Another request kept the stock busy for longer than we are willing to wait. */
|
||||
export class StockBusyError extends Error {
|
||||
constructor() {
|
||||
super("This stock is being updated by someone else. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `fn` while holding the lock on one product's stock at one branch.
|
||||
*
|
||||
* Anything that reads the balance and then writes a movement based on it
|
||||
* (a transfer refusing to overdraw, a physical count computing its
|
||||
* correction) must run inside this. Without it, two transfers that each
|
||||
* see 10 in stock can both send 6, because the read and the write are
|
||||
* separate operations. With it, the second waits for the first and then
|
||||
* sees 4.
|
||||
*
|
||||
* The lock is a lease row: acquired with one atomic upsert that only
|
||||
* succeeds if no unexpired lease exists (otherwise the insert hits the
|
||||
* unique _id and fails), released by deleting it. Sales do not take the
|
||||
* lock - they are recorded even when stock runs out (see PILOT_READINESS).
|
||||
*/
|
||||
export async function withStockLock<T>(businessId: Id, branchId: Id, productId: Id, fn: () => Promise<T>): Promise<T> {
|
||||
const key = `${businessId}:${branchId}:${productId}`;
|
||||
const owner = crypto.randomUUID();
|
||||
const deadline = Date.now() + LOCK_WAIT_MS;
|
||||
let delay = 10;
|
||||
|
||||
for (;;) {
|
||||
const now = Date.now();
|
||||
try {
|
||||
await StockLock.updateOne(
|
||||
{ _id: key, lockedUntil: { $lt: new Date(now) } },
|
||||
{ $set: { owner, lockedUntil: new Date(now + LOCK_LEASE_MS) } },
|
||||
{ upsert: true }
|
||||
);
|
||||
break;
|
||||
} catch (err: unknown) {
|
||||
if ((err as { code?: number })?.code !== 11000) throw err;
|
||||
}
|
||||
if (Date.now() > deadline) throw new StockBusyError();
|
||||
await new Promise((r) => setTimeout(r, delay + Math.random() * delay));
|
||||
delay = Math.min(delay * 2, 200);
|
||||
}
|
||||
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
await StockLock.deleteOne({ _id: key, owner });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,25 +8,27 @@ import { Types } from "mongoose";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { User } from "@/lib/server/models/User";
|
||||
import { Business, IBusiness } from "@/lib/server/models/Business";
|
||||
import { TIERS, isUsable, type TierId, type SubscriptionStatus } from "@/lib/tiers";
|
||||
import { TIERS, effectiveMaxBranches, isUsable, type TierId, type SubscriptionStatus } from "@/lib/tiers";
|
||||
|
||||
export function tierOf(business: Pick<IBusiness, "tier">): TierId {
|
||||
return (business.tier as TierId) ?? "STARTER";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an error message string if adding one more branch would exceed
|
||||
* the business's plan, or null if it's allowed.
|
||||
* Returns an error message string if adding (or reactivating) one more
|
||||
* branch would exceed the business's plan, or null if it's allowed. Only
|
||||
* active branches count; trials get TRIAL_MAX_BRANCHES.
|
||||
*/
|
||||
export async function branchLimitError(
|
||||
businessId: Types.ObjectId | string,
|
||||
tier: TierId
|
||||
): Promise<string | null> {
|
||||
const max = TIERS[tier].maxBranches;
|
||||
export async function branchLimitError(businessId: Types.ObjectId | string): Promise<string | null> {
|
||||
const biz = await Business.findById(businessId).select("tier subscriptionStatus").lean();
|
||||
const tier = (biz?.tier as TierId) ?? "STARTER";
|
||||
const status = (biz?.subscriptionStatus as SubscriptionStatus) ?? "TRIALING";
|
||||
const max = effectiveMaxBranches(tier, status);
|
||||
if (max === null) return null; // unlimited
|
||||
const count = await Branch.countDocuments({ businessId });
|
||||
const count = await Branch.countDocuments({ businessId, isActive: { $ne: false } });
|
||||
if (count >= max) {
|
||||
return `Your ${TIERS[tier].name} plan allows ${max} branch${max === 1 ? "" : "es"}. Upgrade to add more.`;
|
||||
const plan = status === "TRIALING" ? "free trial" : `${TIERS[tier].name} plan`;
|
||||
return `Your ${plan} allows ${max} active branch${max === 1 ? "" : "es"}. Upgrade to add more.`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { AsyncLocalStorage } from "async_hooks";
|
||||
import { Types, type MongooseQueryMiddleware, type Schema } from "mongoose";
|
||||
|
||||
/**
|
||||
* Tenant isolation, enforced instead of remembered.
|
||||
*
|
||||
* Every model that holds one business's data is guarded: a query against
|
||||
* it that does not name exactly one business (`businessId: <id>`) throws
|
||||
* TenantScopeError before it reaches the database. A route that forgets
|
||||
* the business filter therefore fails loudly in development and in the
|
||||
* test suite, instead of quietly reading or changing another business's
|
||||
* data in production.
|
||||
*
|
||||
* The few queries that legitimately span businesses (login looking an
|
||||
* email up everywhere, an invite token, the payment provider's callback,
|
||||
* the platform console, maintenance scripts) must say so explicitly:
|
||||
*
|
||||
* await crossTenant("login looks the email up in every business", () => User.find(...));
|
||||
*
|
||||
* Guarded: find, findOne (and findById / exists), findOneAndUpdate /
|
||||
* Delete / Replace, updateOne / updateMany, replaceOne, deleteOne /
|
||||
* deleteMany, countDocuments, distinct, and aggregate (its first stage
|
||||
* must be a $match naming the business). populate() runs a find on the
|
||||
* referenced model, so populate through `scopedPopulate` below.
|
||||
*
|
||||
* Not guarded, by design: Business (the tenant itself, always looked up by
|
||||
* the id from the session), UserSession (keyed by the signed-in user),
|
||||
* MpesaCallbackLog (provider audit log), StockLock (key already contains
|
||||
* the business). Document saves and inserts are covered by `businessId`
|
||||
* being a required field.
|
||||
*/
|
||||
|
||||
export class TenantScopeError extends Error {
|
||||
constructor(model: string, op: string) {
|
||||
super(
|
||||
`Tenant isolation: ${model}.${op} must filter by a single businessId ` +
|
||||
`(or run inside crossTenant("why", ...) if it really spans businesses).`
|
||||
);
|
||||
this.name = "TenantScopeError";
|
||||
}
|
||||
}
|
||||
|
||||
const crossTenantReason = new AsyncLocalStorage<string>();
|
||||
|
||||
/**
|
||||
* Run `fn`, whose queries deliberately span businesses. `reason` documents
|
||||
* why. The result is awaited inside the scope, so a lazy Mongoose query
|
||||
* returned by `fn` executes while the exemption applies.
|
||||
*/
|
||||
export function crossTenant<T>(reason: string, fn: () => PromiseLike<T>): Promise<T> {
|
||||
if (!reason.trim()) throw new Error("crossTenant needs a reason");
|
||||
return crossTenantReason.run(reason, async () => await fn());
|
||||
}
|
||||
|
||||
/** True when the filter pins exactly one business. */
|
||||
export function namesOneBusiness(filter: unknown): boolean {
|
||||
if (!filter || typeof filter !== "object") return false;
|
||||
const f = filter as Record<string, unknown>;
|
||||
const v = f.businessId;
|
||||
if (typeof v === "string" || v instanceof Types.ObjectId) return true;
|
||||
if (v && typeof v === "object" && "$eq" in (v as object)) {
|
||||
const eq = (v as { $eq: unknown }).$eq;
|
||||
return typeof eq === "string" || eq instanceof Types.ObjectId;
|
||||
}
|
||||
return Array.isArray(f.$and) && f.$and.some(namesOneBusiness);
|
||||
}
|
||||
|
||||
const QUERY_OPS: MongooseQueryMiddleware[] = [
|
||||
"find",
|
||||
"findOne",
|
||||
"findOneAndUpdate",
|
||||
"findOneAndDelete",
|
||||
"findOneAndReplace",
|
||||
"updateOne",
|
||||
"updateMany",
|
||||
"replaceOne",
|
||||
"deleteOne",
|
||||
"deleteMany",
|
||||
"countDocuments",
|
||||
"distinct",
|
||||
];
|
||||
|
||||
const guardedSchemas = new WeakSet<Schema>();
|
||||
|
||||
/** Whether a schema has the guard (the test suite checks every business-scoped model does). */
|
||||
export function isTenantGuarded(schema: Schema): boolean {
|
||||
return guardedSchemas.has(schema);
|
||||
}
|
||||
|
||||
/** Mongoose plugin: apply to every schema with a `businessId` path. */
|
||||
export function tenantGuard(schema: Schema): void {
|
||||
guardedSchemas.add(schema);
|
||||
|
||||
schema.pre(QUERY_OPS, function (this: any) {
|
||||
if (crossTenantReason.getStore()) return;
|
||||
if (!namesOneBusiness(this.getFilter())) throw new TenantScopeError(this.model.modelName, this.op);
|
||||
});
|
||||
|
||||
schema.pre("aggregate", function (this: any) {
|
||||
if (crossTenantReason.getStore()) return;
|
||||
const first = this.pipeline()[0];
|
||||
if (!first || !namesOneBusiness(first.$match)) {
|
||||
throw new TenantScopeError(this._model?.modelName ?? "Model", "aggregate");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* populate() options that keep the referenced documents inside the
|
||||
* business too (populate queries the referenced model, which is guarded).
|
||||
*/
|
||||
export function scopedPopulate(path: string, select: string, businessId: string | Types.ObjectId) {
|
||||
return { path, select, match: { businessId } };
|
||||
}
|
||||
@@ -9,10 +9,17 @@ import type { AuthUser, Product } from "@/lib/types";
|
||||
|
||||
const KEY = "aquaflow_terminal_session";
|
||||
|
||||
/** The branch's stock as the server last reported it. */
|
||||
export interface StockSnapshot {
|
||||
byProduct: Record<string, number>;
|
||||
fetchedAt: string;
|
||||
}
|
||||
|
||||
export interface SessionSnapshot {
|
||||
user: AuthUser;
|
||||
features: { mpesa: boolean };
|
||||
products: Product[];
|
||||
stock?: StockSnapshot;
|
||||
savedAt: string;
|
||||
}
|
||||
|
||||
@@ -32,6 +39,7 @@ export function saveSession(update: Partial<SessionSnapshot> & { user: AuthUser
|
||||
const next: SessionSnapshot = {
|
||||
features: update.features ?? (sameUser ? prev!.features : { mpesa: false }),
|
||||
products: update.products ?? (sameUser ? prev!.products : []),
|
||||
stock: update.stock ?? (sameUser ? prev!.stock : undefined),
|
||||
user: update.user,
|
||||
savedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { clearSession } from "@/lib/sessionCache";
|
||||
|
||||
/**
|
||||
* End this device's session and forget the cached terminal session. Works
|
||||
* offline too: the server session then expires on its own, and this device
|
||||
* keeps nothing that would sign it back in.
|
||||
*/
|
||||
export async function signOut(): Promise<void> {
|
||||
try {
|
||||
await apiFetch("/api/auth/logout", { method: "POST" });
|
||||
} catch {
|
||||
// Offline or already signed out.
|
||||
}
|
||||
clearSession();
|
||||
}
|
||||
@@ -13,6 +13,7 @@ export interface TierDef {
|
||||
priceKsh: number; // monthly price in KSh
|
||||
maxBranches: number | null; // null = unlimited
|
||||
maxUsers: number | null; // total users in the business (owner + managers + staff); null = unlimited
|
||||
branchPricing: boolean; // may set a different price per branch
|
||||
features: string[];
|
||||
}
|
||||
|
||||
@@ -23,6 +24,7 @@ export const TIERS: Record<TierId, TierDef> = {
|
||||
priceKsh: 3500,
|
||||
maxBranches: 1,
|
||||
maxUsers: 6, // owner + up to 5 staff/manager
|
||||
branchPricing: false,
|
||||
features: [
|
||||
"1 branch",
|
||||
"Up to 5 staff accounts",
|
||||
@@ -37,6 +39,7 @@ export const TIERS: Record<TierId, TierDef> = {
|
||||
priceKsh: 7500,
|
||||
maxBranches: 5,
|
||||
maxUsers: 30,
|
||||
branchPricing: true,
|
||||
features: [
|
||||
"Up to 5 branches",
|
||||
"Up to 30 staff accounts",
|
||||
@@ -51,6 +54,7 @@ export const TIERS: Record<TierId, TierDef> = {
|
||||
priceKsh: 15000,
|
||||
maxBranches: null,
|
||||
maxUsers: null,
|
||||
branchPricing: true,
|
||||
features: [
|
||||
"Unlimited branches",
|
||||
"Unlimited staff accounts",
|
||||
@@ -66,6 +70,28 @@ export const DEFAULT_TIER: TierId = "STARTER";
|
||||
// Days of free trial a brand-new business gets on signup.
|
||||
export const TRIAL_DAYS = 14;
|
||||
|
||||
// Branches allowed while a business is TRIALING, whatever its tier, so a
|
||||
// new owner can try the multi-branch features (transfers, per-branch
|
||||
// stock and reports) before paying. After the trial the tier's own limit
|
||||
// applies to adding branches; existing branches are never removed.
|
||||
export const TRIAL_MAX_BRANCHES = 2;
|
||||
|
||||
/**
|
||||
* Whether the business may set branch-specific prices right now: a plan
|
||||
* feature (Growth and up), also available during the free trial so it can
|
||||
* be tried with the trial's two branches.
|
||||
*/
|
||||
export function canUseBranchPricing(tier: TierId, status: SubscriptionStatus): boolean {
|
||||
return TIERS[tier].branchPricing || status === "TRIALING";
|
||||
}
|
||||
|
||||
/** Branch limit for a business right now (null = unlimited). */
|
||||
export function effectiveMaxBranches(tier: TierId, status: SubscriptionStatus): number | null {
|
||||
const max = TIERS[tier].maxBranches;
|
||||
if (status !== "TRIALING" || max === null) return max;
|
||||
return Math.max(max, TRIAL_MAX_BRANCHES);
|
||||
}
|
||||
|
||||
export type SubscriptionStatus = "TRIALING" | "ACTIVE" | "PAST_DUE" | "SUSPENDED";
|
||||
|
||||
export function formatKsh(amount: number): string {
|
||||
|
||||
@@ -7,6 +7,7 @@ export interface Branch {
|
||||
branchName: string;
|
||||
locationCity: string;
|
||||
managerId: string | null;
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
@@ -94,6 +95,7 @@ export interface StockLevel {
|
||||
quantity: number;
|
||||
lowStockThreshold: number;
|
||||
status: "OK" | "LOW" | "OUT";
|
||||
productActive: boolean;
|
||||
}
|
||||
|
||||
export interface StockMovementRow {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// Units a product can be measured in. Water refills are sized in litres;
|
||||
// side items (eggs, bottles, bags) are counted.
|
||||
export const PRODUCT_UNITS = ["L", "ml", "kg", "g", "pcs", "tray", "pack"] as const;
|
||||
export type ProductUnit = (typeof PRODUCT_UNITS)[number];
|
||||
|
||||
export const UNIT_LABELS: Record<ProductUnit, string> = {
|
||||
L: "litres",
|
||||
ml: "millilitres",
|
||||
kg: "kilograms",
|
||||
g: "grams",
|
||||
pcs: "pieces",
|
||||
tray: "trays",
|
||||
pack: "packs",
|
||||
};
|
||||
|
||||
/** "20L", "500ml", "30 pcs", "1 tray". */
|
||||
export function formatSize(size: number, unit: string | undefined): string {
|
||||
const u = unit || "L";
|
||||
return u === "L" || u === "ml" || u === "kg" || u === "g" ? `${size}${u}` : `${size} ${u}`;
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import * as login from "@/app/api/auth/login/route";
|
||||
import * as signup from "@/app/api/auth/signup/route";
|
||||
import * as stkpush from "@/app/api/mpesa/stkpush/route";
|
||||
import * as callback from "@/app/api/mpesa/callback/route";
|
||||
import { json, makeTenant, params, req, uuid } from "./helpers";
|
||||
import { json, makeTenant, params, req, uuid, db } from "./helpers";
|
||||
|
||||
describe("role-based access on the backend", () => {
|
||||
it("blocks cashiers from owner-level money endpoints with 403", async () => {
|
||||
@@ -78,7 +78,7 @@ describe("user deactivation", () => {
|
||||
params({ id: t.cashierA.id })
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect((await User.findById(t.cashierA.id))!.isActive).toBe(false);
|
||||
expect((await db(() => User.findById(t.cashierA.id)))!.isActive).toBe(false);
|
||||
expect(await UserSession.countDocuments({ userId: t.cashierA.id })).toBe(0);
|
||||
});
|
||||
|
||||
@@ -105,7 +105,7 @@ describe("tenant status", () => {
|
||||
it("refuses login for a suspended business", async () => {
|
||||
const t = await makeTenant();
|
||||
const passwordHash = await bcrypt.hash("correct-horse", 4);
|
||||
await User.updateOne({ _id: t.cashierA.id }, { passwordHash });
|
||||
await db(() => User.updateOne({ _id: t.cashierA.id }, { passwordHash }));
|
||||
await Business.updateOne({ _id: t.businessId }, { subscriptionStatus: "SUSPENDED" });
|
||||
|
||||
const res = await login.POST(
|
||||
@@ -119,7 +119,7 @@ describe("tenant status", () => {
|
||||
it("still allows login for an active business", async () => {
|
||||
const t = await makeTenant();
|
||||
const passwordHash = await bcrypt.hash("correct-horse", 4);
|
||||
await User.updateOne({ _id: t.managerA.id }, { passwordHash });
|
||||
await db(() => User.updateOne({ _id: t.managerA.id }, { passwordHash }));
|
||||
const res = await login.POST(
|
||||
req("POST", "/api/auth/login", {
|
||||
body: { email: t.managerA.email, password: "correct-horse", deviceId: uuid() },
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { User } from "@/lib/server/models/User";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { UserSession } from "@/lib/server/models/UserSession";
|
||||
import * as invite from "@/app/api/users/[id]/invite/route";
|
||||
import * as invites from "@/app/api/invites/[token]/route";
|
||||
import * as users from "@/app/api/users/route";
|
||||
import * as userById from "@/app/api/users/[id]/route";
|
||||
import * as password from "@/app/api/auth/password/route";
|
||||
import * as login from "@/app/api/auth/login/route";
|
||||
import * as ownerReset from "@/app/api/platform/businesses/[id]/owner-reset/route";
|
||||
import { db, json, makeTenant, params, req, uuid, type Actor } from "./helpers";
|
||||
|
||||
const DEVICE = "00000000-0000-4000-8000-000000000001"; // the device tokenFor() signs in on
|
||||
|
||||
async function setPassword(a: Actor, pw: string) {
|
||||
await db(() => User.updateOne({ _id: a.id }, { passwordHash: bcrypt.hashSync(pw, 4) }));
|
||||
}
|
||||
const signIn = (a: Actor, pw: string) =>
|
||||
login.POST(req("POST", "/x", { body: { email: a.email, password: pw, deviceId: uuid() } }));
|
||||
const tokenOf = (url: string) => url.split("/invite/")[1];
|
||||
const sessions = (a: Actor) => db(() => UserSession.countDocuments({ userId: a.id }));
|
||||
|
||||
describe("password reset links", () => {
|
||||
it("lets a manager reset their cashier's forgotten password; the old one works until the link is used", async () => {
|
||||
const t = await makeTenant();
|
||||
await setPassword(t.cashierA, "old-password");
|
||||
await signIn(t.cashierA, "old-password"); // a session on some phone
|
||||
|
||||
const r = await json(await invite.POST(req("POST", "/x", { as: t.managerA }), params({ id: t.cashierA.id })));
|
||||
expect(r.status).toBe(200);
|
||||
expect(r.body.purpose).toBe("reset");
|
||||
expect((await signIn(t.cashierA, "old-password")).status).toBe(200);
|
||||
|
||||
const page = await json(await invites.GET(req("GET", "/x"), params({ token: tokenOf(r.body.inviteUrl) })));
|
||||
expect(page.body.purpose).toBe("reset");
|
||||
|
||||
const accept = await invites.POST(req("POST", "/x", { body: { password: "new-password" } }), params({ token: tokenOf(r.body.inviteUrl) }));
|
||||
expect(accept.status).toBe(200);
|
||||
expect(await sessions(t.cashierA)).toBe(0); // every device signed out
|
||||
expect((await signIn(t.cashierA, "old-password")).status).toBe(401);
|
||||
expect((await signIn(t.cashierA, "new-password")).status).toBe(200);
|
||||
});
|
||||
|
||||
it("does not show a reset as a pending invite", async () => {
|
||||
const t = await makeTenant();
|
||||
await invite.POST(req("POST", "/x", { as: t.owner }), params({ id: t.cashierA.id }));
|
||||
const list = await json(await users.GET(req("GET", "/api/users", { as: t.owner })));
|
||||
expect(list.body.users.find((u: any) => u._id === t.cashierA.id).invitePending).toBe(false);
|
||||
});
|
||||
|
||||
it("expires a reset link after 24 hours", async () => {
|
||||
const t = await makeTenant();
|
||||
const r = await json(await invite.POST(req("POST", "/x", { as: t.owner }), params({ id: t.cashierA.id })));
|
||||
const user = await db(() => User.findById(t.cashierA.id).lean());
|
||||
const hours = (user!.inviteExpiresAt!.getTime() - Date.now()) / 3_600_000;
|
||||
expect(hours).toBeGreaterThan(23.9);
|
||||
expect(hours).toBeLessThanOrEqual(24);
|
||||
await db(() => User.updateOne({ _id: t.cashierA.id }, { inviteExpiresAt: new Date(Date.now() - 1000) }));
|
||||
expect((await invites.GET(req("GET", "/x"), params({ token: tokenOf(r.body.inviteUrl) }))).status).toBe(404);
|
||||
});
|
||||
|
||||
it("keeps managers to their own cashiers, and nobody resets themselves", async () => {
|
||||
const t = await makeTenant();
|
||||
const post = (as: Actor, id: string) => invite.POST(req("POST", "/x", { as }), params({ id }));
|
||||
expect((await post(t.managerA, t.cashierB.id)).status).toBe(403);
|
||||
expect((await post(t.managerA, t.owner.id)).status).toBe(403);
|
||||
expect((await post(t.owner, t.owner.id)).status).toBe(409);
|
||||
expect((await post(t.cashierA, t.cashierB.id)).status).toBe(403);
|
||||
});
|
||||
|
||||
it("lets the platform operator give a business owner a reset link, and nobody else", async () => {
|
||||
const t = await makeTenant("Customer Co");
|
||||
const home = await makeTenant("Operator Co");
|
||||
await db(() => User.updateOne({ _id: home.owner.id }, { email: "operator@aquaflow.test", platformAdmin: true }));
|
||||
const operator = { ...home.owner, email: "operator@aquaflow.test" };
|
||||
|
||||
const ok = await json(await ownerReset.POST(req("POST", "/x", { as: operator }), params({ id: t.businessId })));
|
||||
expect(ok.status).toBe(200);
|
||||
expect(ok.body).toMatchObject({ purpose: "reset", email: t.owner.email.toLowerCase() });
|
||||
|
||||
expect((await ownerReset.POST(req("POST", "/x", { as: t.owner }), params({ id: t.businessId }))).status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe("changing your own password", () => {
|
||||
it("needs the current password, then signs out every other device but this one", async () => {
|
||||
const t = await makeTenant();
|
||||
await setPassword(t.managerA, "current-pass");
|
||||
await signIn(t.managerA, "current-pass"); // another device
|
||||
await db(() => UserSession.create({ userId: t.managerA.id, deviceId: DEVICE, refreshTokenHash: "x", expiresAt: new Date(Date.now() + 86_400_000) }));
|
||||
expect(await sessions(t.managerA)).toBe(2);
|
||||
|
||||
const change = (currentPassword: string, newPassword: string) =>
|
||||
password.POST(req("POST", "/x", { as: t.managerA, body: { currentPassword, newPassword } }));
|
||||
expect((await change("wrong-pass", "brand-new-pass")).status).toBe(400);
|
||||
expect((await change("current-pass", "short")).status).toBe(400);
|
||||
expect((await change("current-pass", "brand-new-pass")).status).toBe(200);
|
||||
|
||||
expect(await sessions(t.managerA)).toBe(1);
|
||||
expect(await db(() => UserSession.exists({ userId: t.managerA.id, deviceId: DEVICE }))).toBeTruthy();
|
||||
expect((await signIn(t.managerA, "brand-new-pass")).status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("moving staff between branches", () => {
|
||||
it("moves a manager, updates both branches' manager, and signs them out", async () => {
|
||||
const t = await makeTenant();
|
||||
await db(() => Branch.updateOne({ _id: t.branchA }, { managerId: t.managerA.id }));
|
||||
await db(() => UserSession.create({ userId: t.managerA.id, deviceId: uuid(), refreshTokenHash: "x", expiresAt: new Date(Date.now() + 86_400_000) }));
|
||||
|
||||
const res = await userById.PATCH(req("PATCH", "/x", { as: t.owner, body: { branchId: t.branchB } }), params({ id: t.managerA.id }));
|
||||
expect(res.status).toBe(200);
|
||||
const [a, b, mgr] = await Promise.all([
|
||||
db(() => Branch.findById(t.branchA).lean()),
|
||||
db(() => Branch.findById(t.branchB).lean()),
|
||||
db(() => User.findById(t.managerA.id).lean()),
|
||||
]);
|
||||
expect(a!.managerId).toBeNull();
|
||||
expect(b!.managerId!.toString()).toBe(t.managerA.id);
|
||||
expect(mgr!.branchId!.toString()).toBe(t.branchB);
|
||||
expect(await sessions(t.managerA)).toBe(0);
|
||||
});
|
||||
|
||||
it("only lets the owner move people, and only to an active branch", async () => {
|
||||
const t = await makeTenant();
|
||||
const move = (as: Actor, branchId: string) =>
|
||||
userById.PATCH(req("PATCH", "/x", { as, body: { branchId } }), params({ id: t.cashierA.id }));
|
||||
expect((await move(t.managerA, t.branchB)).status).toBe(403);
|
||||
await db(() => Branch.updateOne({ _id: t.branchB }, { isActive: false }));
|
||||
expect((await move(t.owner, t.branchB)).status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("where sign-in lands", () => {
|
||||
it("sends the platform operator to the platform console, owners to the dashboard, cashiers to the till", async () => {
|
||||
const t = await makeTenant();
|
||||
await Promise.all([setPassword(t.owner, "owner-pass"), setPassword(t.cashierA, "cashier-pass")]);
|
||||
expect((await json(await signIn(t.owner, "owner-pass"))).body.redirectTo).toBe("/admin/dashboard");
|
||||
expect((await json(await signIn(t.cashierA, "cashier-pass"))).body.redirectTo).toBe("/terminal");
|
||||
|
||||
await db(() => User.updateOne({ _id: t.owner.id }, { email: "operator@aquaflow.test", platformAdmin: true }));
|
||||
const operator = { ...t.owner, email: "operator@aquaflow.test" };
|
||||
expect((await json(await signIn(operator, "owner-pass"))).body.redirectTo).toBe("/platform");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Business } from "@/lib/server/models/Business";
|
||||
import { BranchPricing } from "@/lib/server/models/Product";
|
||||
import * as prices from "@/app/api/branch-prices/route";
|
||||
import * as products from "@/app/api/products/route";
|
||||
import * as cash from "@/app/api/transactions/cash/route";
|
||||
import { json, makeTenant, req, uuid, type Actor, type Tenant, db } from "./helpers";
|
||||
|
||||
const setPrice = (as: Actor, branchId: string, productId: string, unitPrice: number) =>
|
||||
prices.PUT(req("PUT", "/api/branch-prices", { as, body: { branchId, productId, unitPrice } }));
|
||||
|
||||
const tillPrice = async (as: Actor, productId: string) => {
|
||||
const { body } = await json(await products.GET(req("GET", "/api/products", { as })));
|
||||
return body.products.find((p: any) => p._id === productId).unitPrice;
|
||||
};
|
||||
|
||||
describe("branch prices", () => {
|
||||
it("charges the branch's own price at that branch only, through the till and the sale", async () => {
|
||||
const t = await makeTenant();
|
||||
expect((await setPrice(t.owner, t.branchA, t.water20, 180)).status).toBe(200);
|
||||
|
||||
expect(await tillPrice(t.cashierA, t.water20)).toBe(180);
|
||||
expect(await tillPrice(t.cashierB, t.water20)).toBe(200);
|
||||
|
||||
const sale = await json(
|
||||
await cash.POST(req("POST", "/x", { as: t.cashierA, body: { sales: [{ clientUuid: uuid(), lines: [{ productId: t.water20, quantity: 2 }] }] } }))
|
||||
);
|
||||
expect(sale.body.results[0]).toMatchObject({ status: "saved", amountTotal: 360 });
|
||||
});
|
||||
|
||||
it("lists default and branch prices, and the catalogue view keeps showing defaults", async () => {
|
||||
const t = await makeTenant();
|
||||
await setPrice(t.owner, t.branchA, t.water20, 180);
|
||||
const { body } = await json(await prices.GET(req("GET", "/api/branch-prices?branchId=" + t.branchA, { as: t.owner })));
|
||||
const row = body.prices.find((p: any) => p.productId === t.water20);
|
||||
expect(row).toMatchObject({ defaultPrice: 200, branchPrice: 180 });
|
||||
expect(body.allowed).toBe(true);
|
||||
|
||||
const catalogue = await json(await products.GET(req("GET", "/api/products?includeInactive=1", { as: t.managerA })));
|
||||
expect(catalogue.body.products.find((p: any) => p._id === t.water20).unitPrice).toBe(200);
|
||||
});
|
||||
|
||||
it("removes the override when set back to the default, or reset", async () => {
|
||||
const t = await makeTenant();
|
||||
await setPrice(t.owner, t.branchA, t.water20, 180);
|
||||
await setPrice(t.owner, t.branchA, t.water20, 200);
|
||||
expect(await db(() => BranchPricing.countDocuments({}))).toBe(0);
|
||||
|
||||
await setPrice(t.owner, t.branchA, t.water5, 55);
|
||||
const reset = await prices.DELETE(
|
||||
req("DELETE", `/api/branch-prices?branchId=${t.branchA}&productId=${t.water5}`, { as: t.owner })
|
||||
);
|
||||
expect(reset.status).toBe(200);
|
||||
expect(await tillPrice(t.cashierA, t.water5)).toBe(60);
|
||||
});
|
||||
|
||||
it("lets a manager see only their own branch's prices, and not change them", async () => {
|
||||
const t = await makeTenant();
|
||||
const own = await json(await prices.GET(req("GET", "/api/branch-prices?branchId=" + t.branchB, { as: t.managerA })));
|
||||
expect(own.body.branchId).toBe(t.branchA); // pinned to their branch
|
||||
expect((await setPrice(t.managerA, t.branchA, t.water20, 150)).status).toBe(403);
|
||||
expect((await prices.GET(req("GET", "/api/branch-prices", { as: t.cashierA }))).status).toBe(403);
|
||||
});
|
||||
|
||||
it("follows the plan: Growth and trials may set prices, a paid Starter may only reset them", async () => {
|
||||
const t: Tenant = await makeTenant();
|
||||
await Business.updateOne({ _id: t.businessId }, { tier: "STARTER", subscriptionStatus: "TRIALING" });
|
||||
expect((await setPrice(t.owner, t.branchA, t.water20, 180)).status).toBe(200);
|
||||
|
||||
await Business.updateOne({ _id: t.businessId }, { tier: "STARTER", subscriptionStatus: "ACTIVE" });
|
||||
expect((await setPrice(t.owner, t.branchA, t.water20, 170)).status).toBe(403);
|
||||
// Prices set during the trial keep applying until reset.
|
||||
expect(await tillPrice(t.cashierA, t.water20)).toBe(180);
|
||||
const reset = await prices.DELETE(
|
||||
req("DELETE", `/api/branch-prices?branchId=${t.branchA}&productId=${t.water20}`, { as: t.owner })
|
||||
);
|
||||
expect(reset.status).toBe(200);
|
||||
expect(await tillPrice(t.cashierA, t.water20)).toBe(200);
|
||||
});
|
||||
|
||||
it("rejects zero prices and another tenant's branch or product", async () => {
|
||||
const t = await makeTenant("Alpha");
|
||||
const other = await makeTenant("Beta");
|
||||
expect((await setPrice(t.owner, t.branchA, t.water20, 0)).status).toBe(400);
|
||||
expect((await setPrice(t.owner, other.branchA, t.water20, 150)).status).toBe(404);
|
||||
expect((await setPrice(t.owner, t.branchA, other.water20, 150)).status).toBe(404);
|
||||
expect((await prices.GET(req("GET", "/api/branch-prices?branchId=" + other.branchA, { as: t.owner }))).status).toBe(404);
|
||||
expect(await db(() => BranchPricing.countDocuments({}))).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { stockOf } from "@/lib/server/stock";
|
||||
import { StockTransfer } from "@/lib/server/models/StockTransfer";
|
||||
import { StockLock } from "@/lib/server/models/StockLock";
|
||||
import * as adjustments from "@/app/api/stock/adjustments/route";
|
||||
import * as transfers from "@/app/api/stock/transfers/route";
|
||||
import { makeTenant, req, uuid, type Tenant, db } from "./helpers";
|
||||
|
||||
async function openingStock(t: Tenant, quantity: number) {
|
||||
await adjustments.POST(
|
||||
req("POST", "/x", {
|
||||
as: t.owner,
|
||||
body: { clientUuid: uuid(), branchId: t.branchA, productId: t.water20, mode: "DELTA", quantity },
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const transferOut = (t: Tenant, quantity: number) =>
|
||||
transfers.POST(
|
||||
req("POST", "/x", {
|
||||
as: t.owner,
|
||||
body: { clientUuid: uuid(), fromBranchId: t.branchA, toBranchId: t.branchB, productId: t.water20, quantity },
|
||||
})
|
||||
);
|
||||
|
||||
describe("concurrent stock changes", () => {
|
||||
it("never lets simultaneous transfers send more than the branch holds", async () => {
|
||||
const t = await makeTenant();
|
||||
await openingStock(t, 10);
|
||||
|
||||
// Five managers press "Record transfer" for 4 units at the same moment.
|
||||
const statuses = (await Promise.all(Array.from({ length: 5 }, () => transferOut(t, 4)))).map((r) => r.status);
|
||||
|
||||
expect(statuses.filter((s) => s === 201)).toHaveLength(2);
|
||||
expect(statuses.filter((s) => s === 409)).toHaveLength(3);
|
||||
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(2);
|
||||
expect(await stockOf(t.businessId, t.branchB, t.water20)).toBe(8);
|
||||
expect(await db(() => StockTransfer.countDocuments({}))).toBe(2);
|
||||
});
|
||||
|
||||
it("holds across repeated races, not just once", async () => {
|
||||
for (let round = 0; round < 5; round++) {
|
||||
const t = await makeTenant("Round" + round);
|
||||
await openingStock(t, 9);
|
||||
const statuses = (await Promise.all(Array.from({ length: 4 }, () => transferOut(t, 3)))).map((r) => r.status);
|
||||
expect(statuses.filter((s) => s === 201)).toHaveLength(3);
|
||||
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("applies a double-tapped transfer once even when both taps race", async () => {
|
||||
const t = await makeTenant();
|
||||
await openingStock(t, 10);
|
||||
const body = { clientUuid: uuid(), fromBranchId: t.branchA, toBranchId: t.branchB, productId: t.water20, quantity: 6 };
|
||||
const statuses = (
|
||||
await Promise.all([
|
||||
transfers.POST(req("POST", "/x", { as: t.owner, body })),
|
||||
transfers.POST(req("POST", "/x", { as: t.owner, body })),
|
||||
])
|
||||
).map((r) => r.status);
|
||||
expect(statuses.sort()).toEqual([200, 201]);
|
||||
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(4);
|
||||
});
|
||||
|
||||
it("takes over a lock left behind by a crashed request once it expires", async () => {
|
||||
const t = await makeTenant();
|
||||
await openingStock(t, 10);
|
||||
await StockLock.create({
|
||||
_id: `${t.businessId}:${t.branchA}:${t.water20}`,
|
||||
owner: "crashed-request",
|
||||
lockedUntil: new Date(Date.now() - 1000),
|
||||
});
|
||||
expect((await transferOut(t, 3)).status).toBe(201);
|
||||
expect(await StockLock.countDocuments({})).toBe(0);
|
||||
});
|
||||
|
||||
it("serialises a physical count with a transfer, so the count is never applied to a stale balance", async () => {
|
||||
const t = await makeTenant();
|
||||
await openingStock(t, 10);
|
||||
|
||||
// A count of 10 and a transfer of 6 race. Whichever runs second must
|
||||
// see the first: either the count resets 4 back to 10 after the
|
||||
// transfer, or the transfer moves 6 out of the counted 10.
|
||||
const [count, transfer] = await Promise.all([
|
||||
adjustments.POST(
|
||||
req("POST", "/x", {
|
||||
as: t.owner,
|
||||
body: { clientUuid: uuid(), branchId: t.branchA, productId: t.water20, mode: "COUNT", quantity: 10 },
|
||||
})
|
||||
),
|
||||
transferOut(t, 6),
|
||||
]);
|
||||
expect([count.status, transfer.status]).toEqual([201, 201]);
|
||||
const a = await stockOf(t.businessId, t.branchA, t.water20);
|
||||
expect([4, 10]).toContain(a);
|
||||
expect(await stockOf(t.businessId, t.branchB, t.water20)).toBe(6);
|
||||
});
|
||||
|
||||
it("does not block transfers of different products or branches on each other", async () => {
|
||||
const t = await makeTenant();
|
||||
await openingStock(t, 10);
|
||||
await adjustments.POST(
|
||||
req("POST", "/x", {
|
||||
as: t.owner,
|
||||
body: { clientUuid: uuid(), branchId: t.branchA, productId: t.water5, mode: "DELTA", quantity: 10 },
|
||||
})
|
||||
);
|
||||
const results = await Promise.all([
|
||||
transferOut(t, 5),
|
||||
transfers.POST(
|
||||
req("POST", "/x", {
|
||||
as: t.owner,
|
||||
body: { clientUuid: uuid(), fromBranchId: t.branchA, toBranchId: t.branchB, productId: t.water5, quantity: 5 },
|
||||
})
|
||||
),
|
||||
]);
|
||||
expect(results.map((r) => r.status)).toEqual([201, 201]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import mongoose from "mongoose";
|
||||
import { costOfGoodsSold } from "@/lib/server/costing";
|
||||
import { StockMovement } from "@/lib/server/models/StockMovement";
|
||||
import { Transaction } from "@/lib/server/models/Transaction";
|
||||
import { Purchase } from "@/lib/server/models/Purchase";
|
||||
import { startOfMonthNairobi } from "@/lib/server/businessDay";
|
||||
import * as cash from "@/app/api/transactions/cash/route";
|
||||
import * as purchases from "@/app/api/purchases/route";
|
||||
import * as adjustments from "@/app/api/stock/adjustments/route";
|
||||
import * as transfers from "@/app/api/stock/transfers/route";
|
||||
import * as profit from "@/app/api/reports/profit/route";
|
||||
import { json, makeTenant, req, uuid, type Actor, type Tenant } from "./helpers";
|
||||
|
||||
const ALL_TIME = { from: new Date(0), to: new Date(Date.now() + 86_400_000) };
|
||||
|
||||
const buy = (t: Tenant, branchId: string, quantity: number, unitCost: number, productId = t.water20) =>
|
||||
purchases.POST(req("POST", "/x", { as: t.owner, body: { branchId, supplierName: "Supplier", productId, quantity, unitCost } }));
|
||||
|
||||
const sell = (cashier: Actor, quantity: number, productId: string) =>
|
||||
cash.POST(req("POST", "/x", { as: cashier, body: { sales: [{ clientUuid: uuid(), lines: [{ productId, quantity }] }] } }));
|
||||
|
||||
const adjust = (t: Tenant, mode: "COUNT" | "DELTA", quantity: number) =>
|
||||
adjustments.POST(
|
||||
req("POST", "/x", { as: t.owner, body: { clientUuid: uuid(), branchId: t.branchA, productId: t.water20, mode, quantity } })
|
||||
);
|
||||
|
||||
/** Move everything recorded so far to `when` (tests need history in an earlier period). */
|
||||
async function backdate(t: Tenant, when: Date) {
|
||||
// The raw collection: Mongoose treats createdAt as immutable.
|
||||
const filter = { businessId: new mongoose.Types.ObjectId(t.businessId) };
|
||||
await StockMovement.collection.updateMany(filter, { $set: { createdAt: when } });
|
||||
await Transaction.collection.updateMany(filter, { $set: { createdAt: when } });
|
||||
await Purchase.collection.updateMany(filter, { $set: { createdAt: when } });
|
||||
}
|
||||
|
||||
describe("cost of goods sold: FIFO per branch", () => {
|
||||
it("costs the oldest stock first, not an average", async () => {
|
||||
const t = await makeTenant();
|
||||
await buy(t, t.branchA, 10, 10);
|
||||
await buy(t, t.branchA, 10, 20);
|
||||
await sell(t.cashierA, 15, t.water20);
|
||||
const c = await costOfGoodsSold(t.businessId, ALL_TIME);
|
||||
expect(c).toMatchObject({ costOfGoodsSold: 200, unitsCosted: 15, unitsWithoutCost: 0 }); // 10x10 + 5x20 (the average would say 225)
|
||||
});
|
||||
|
||||
it("costs each branch at what that branch paid", async () => {
|
||||
const t = await makeTenant();
|
||||
await buy(t, t.branchA, 10, 10);
|
||||
await buy(t, t.branchB, 10, 30);
|
||||
await sell(t.cashierB, 2, t.water20);
|
||||
await sell(t.cashierA, 1, t.water20);
|
||||
expect((await costOfGoodsSold(t.businessId, ALL_TIME)).costOfGoodsSold).toBe(70);
|
||||
expect((await costOfGoodsSold(t.businessId, { ...ALL_TIME, branchId: t.branchA })).costOfGoodsSold).toBe(10);
|
||||
expect((await costOfGoodsSold(t.businessId, { ...ALL_TIME, branchId: t.branchB })).costOfGoodsSold).toBe(60);
|
||||
});
|
||||
|
||||
it("carries the sending branch's cost with a transfer", async () => {
|
||||
const t = await makeTenant();
|
||||
await buy(t, t.branchA, 10, 10);
|
||||
await transfers.POST(
|
||||
req("POST", "/x", {
|
||||
as: t.owner,
|
||||
body: { clientUuid: uuid(), fromBranchId: t.branchA, toBranchId: t.branchB, productId: t.water20, quantity: 5 },
|
||||
})
|
||||
);
|
||||
await buy(t, t.branchB, 5, 30);
|
||||
await sell(t.cashierB, 6, t.water20);
|
||||
// B's oldest stock is the 5 transferred at 10, then 1 of its own at 30.
|
||||
expect((await costOfGoodsSold(t.businessId, { ...ALL_TIME, branchId: t.branchB })).costOfGoodsSold).toBe(80);
|
||||
});
|
||||
|
||||
it("costs a sale made before its stock was recorded by the stock that arrives next", async () => {
|
||||
const t = await makeTenant();
|
||||
await sell(t.cashierA, 3, t.water20); // offline sale, nothing on the books yet
|
||||
expect(await costOfGoodsSold(t.businessId, ALL_TIME)).toMatchObject({ costOfGoodsSold: 0, unitsWithoutCost: 3 });
|
||||
await buy(t, t.branchA, 10, 12);
|
||||
expect(await costOfGoodsSold(t.businessId, ALL_TIME)).toMatchObject({ costOfGoodsSold: 36, unitsWithoutCost: 0 });
|
||||
});
|
||||
|
||||
it("reports written-off stock as a loss, not as cost of goods sold, and deducts it in net profit", async () => {
|
||||
const t = await makeTenant();
|
||||
await buy(t, t.branchA, 10, 10);
|
||||
await adjust(t, "COUNT", 8);
|
||||
expect(await costOfGoodsSold(t.businessId, ALL_TIME)).toMatchObject({ costOfGoodsSold: 0, stockLosses: 20 });
|
||||
const { body } = await json(await profit.GET(req("GET", "/api/reports/profit", { as: t.owner })));
|
||||
expect(body).toMatchObject({ stockLosses: 20, grossProfit: 0, netProfit: -20 });
|
||||
});
|
||||
|
||||
it("values opening stock at the product's purchase price", async () => {
|
||||
const t = await makeTenant();
|
||||
await adjust(t, "DELTA", 10); // opening stock, before any purchase was recorded
|
||||
await buy(t, t.branchA, 10, 15);
|
||||
await sell(t.cashierA, 12, t.water20);
|
||||
expect((await costOfGoodsSold(t.businessId, ALL_TIME)).costOfGoodsSold).toBe(180);
|
||||
});
|
||||
|
||||
it("counts only the period's sales, costed against what was left from earlier periods", async () => {
|
||||
const t = await makeTenant();
|
||||
await buy(t, t.branchA, 10, 10);
|
||||
await sell(t.cashierA, 6, t.water20);
|
||||
const lastMonth = new Date(startOfMonthNairobi().getTime() - 5 * 86_400_000);
|
||||
await backdate(t, lastMonth);
|
||||
await buy(t, t.branchA, 10, 20);
|
||||
await sell(t.cashierA, 6, t.water20); // 4 left from last month at 10, then 2 at 20
|
||||
|
||||
const { body } = await json(await profit.GET(req("GET", "/api/reports/profit", { as: t.owner })));
|
||||
expect(body).toMatchObject({ costMethod: "FIFO per branch", unitsSold: 6, costOfGoodsSold: 80, unitsWithoutCost: 0 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,241 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import mongoose from "mongoose";
|
||||
import { Business } from "@/lib/server/models/Business";
|
||||
import { Branch } from "@/lib/server/models/Branch";
|
||||
import { User } from "@/lib/server/models/User";
|
||||
import { Product } from "@/lib/server/models/Product";
|
||||
import { Purchase } from "@/lib/server/models/Purchase";
|
||||
import { backfillPurchaseMovements, stockOf, getStockLevels } from "@/lib/server/stock";
|
||||
import * as branches from "@/app/api/branches/route";
|
||||
import * as branchById from "@/app/api/branches/[id]/route";
|
||||
import * as users from "@/app/api/users/route";
|
||||
import * as invites from "@/app/api/invites/[token]/route";
|
||||
import * as reinvite from "@/app/api/users/[id]/invite/route";
|
||||
import * as login from "@/app/api/auth/login/route";
|
||||
import * as products from "@/app/api/products/route";
|
||||
import * as productById from "@/app/api/products/[id]/route";
|
||||
import * as purchases from "@/app/api/purchases/route";
|
||||
import * as profit from "@/app/api/reports/profit/route";
|
||||
import * as cash from "@/app/api/transactions/cash/route";
|
||||
import * as adjustments from "@/app/api/stock/adjustments/route";
|
||||
import * as transfers from "@/app/api/stock/transfers/route";
|
||||
import { json, makeTenant, params, req, uuid, type Tenant, db } from "./helpers";
|
||||
|
||||
async function setPlan(t: Tenant, tier: string, subscriptionStatus: string) {
|
||||
await Business.updateOne({ _id: t.businessId }, { tier, subscriptionStatus });
|
||||
}
|
||||
|
||||
const newBranch = (name: string) => ({ branchName: name, locationCity: "Nakuru" });
|
||||
|
||||
describe("F-01 trial branch allowance", () => {
|
||||
it("lets a trialling Starter business run two branches, not three", async () => {
|
||||
const t = await makeTenant(); // already has branches A and B
|
||||
await setPlan(t, "STARTER", "TRIALING");
|
||||
const third = await branches.POST(req("POST", "/x", { as: t.owner, body: newBranch("C") }));
|
||||
expect(third.status).toBe(403);
|
||||
expect((await third.json()).error).toMatch(/free trial allows 2/);
|
||||
});
|
||||
|
||||
it("counts only active branches, and a paid Starter plan allows one", async () => {
|
||||
const t = await makeTenant();
|
||||
await setPlan(t, "STARTER", "TRIALING");
|
||||
await db(() => Branch.updateOne({ _id: t.branchB }, { isActive: false }));
|
||||
expect((await branches.POST(req("POST", "/x", { as: t.owner, body: newBranch("C") }))).status).toBe(201);
|
||||
|
||||
await setPlan(t, "STARTER", "ACTIVE");
|
||||
expect((await branches.POST(req("POST", "/x", { as: t.owner, body: newBranch("D") }))).status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe("F-06 branch deactivation", () => {
|
||||
it("refuses while the branch still holds stock or active staff, then succeeds once emptied", async () => {
|
||||
const t = await makeTenant();
|
||||
await adjustments.POST(
|
||||
req("POST", "/x", { as: t.owner, body: { clientUuid: uuid(), branchId: t.branchB, productId: t.water20, mode: "DELTA", quantity: 4 } })
|
||||
);
|
||||
const deactivate = () =>
|
||||
branchById.PATCH(req("PATCH", "/x", { as: t.owner, body: { isActive: false } }), params({ id: t.branchB }));
|
||||
|
||||
const withStock = await deactivate();
|
||||
expect(withStock.status).toBe(409);
|
||||
expect((await withStock.json()).error).toMatch(/4 x 20L Jerrycan/);
|
||||
|
||||
await transfers.POST(
|
||||
req("POST", "/x", {
|
||||
as: t.owner,
|
||||
body: { clientUuid: uuid(), fromBranchId: t.branchB, toBranchId: t.branchA, productId: t.water20, quantity: 4 },
|
||||
})
|
||||
);
|
||||
const withStaff = await deactivate();
|
||||
expect(withStaff.status).toBe(409);
|
||||
expect((await withStaff.json()).error).toMatch(/active staff/);
|
||||
|
||||
await db(() => User.updateOne({ _id: t.cashierB.id }, { isActive: false }));
|
||||
expect((await deactivate()).status).toBe(200);
|
||||
|
||||
// Hidden from pickers, kept on the Branches page.
|
||||
const active = await json(await branches.GET(req("GET", "/api/branches", { as: t.owner })));
|
||||
const all = await json(await branches.GET(req("GET", "/api/branches?includeInactive=1", { as: t.owner })));
|
||||
expect(active.body.branches.map((b: any) => b._id)).toEqual([t.branchA]);
|
||||
expect(all.body.branches).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("will not reactivate a branch past the plan's limit", async () => {
|
||||
const t = await makeTenant();
|
||||
await db(() => Branch.updateOne({ _id: t.branchB }, { isActive: false }));
|
||||
await setPlan(t, "STARTER", "ACTIVE");
|
||||
const res = await branchById.PATCH(req("PATCH", "/x", { as: t.owner, body: { isActive: true } }), params({ id: t.branchB }));
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe("F-03 report period validation", () => {
|
||||
it("rejects a reversed period instead of showing an empty report", async () => {
|
||||
const t = await makeTenant();
|
||||
const res = await profit.GET(req("GET", "/api/reports/profit?fromDate=2026-10-12&toDate=2026-10-11", { as: t.owner }));
|
||||
expect(res.status).toBe(400);
|
||||
const sameDay = await profit.GET(req("GET", "/api/reports/profit?fromDate=2026-10-11&toDate=2026-10-11", { as: t.owner }));
|
||||
expect(sameDay.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("F-07 cost of goods sold", () => {
|
||||
it("costs only the units sold, first-in-first-out, and reports purchases separately", async () => {
|
||||
const t = await makeTenant();
|
||||
const buy = (quantity: number, unitCost: number) =>
|
||||
purchases.POST(req("POST", "/x", { as: t.managerA, body: { supplierName: "Kiwanja", productId: t.water20, quantity, unitCost } }));
|
||||
await buy(20, 10);
|
||||
await buy(10, 13);
|
||||
await cash.POST(
|
||||
req("POST", "/x", {
|
||||
as: t.cashierA,
|
||||
body: { sales: [{ clientUuid: uuid(), lines: [{ productId: t.water20, quantity: 3 }, { productId: t.water5, quantity: 1 }] }] },
|
||||
})
|
||||
);
|
||||
const { body } = await json(await profit.GET(req("GET", "/api/reports/profit", { as: t.owner })));
|
||||
expect(body).toMatchObject({
|
||||
revenue: 660, // 3 x 200 + 1 x 60
|
||||
unitsSold: 4,
|
||||
costOfGoodsSold: 30, // 3 x 10 from the oldest purchase; the 5L was never purchased
|
||||
unitsWithoutCost: 1,
|
||||
grossProfit: 630,
|
||||
stockPurchases: 330,
|
||||
cashSurplus: 330,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("purchase-to-stock backfill", () => {
|
||||
it("turns pre-ledger purchases into stock, once", async () => {
|
||||
const t = await makeTenant();
|
||||
await Purchase.create({
|
||||
businessId: t.businessId,
|
||||
branchId: t.branchA,
|
||||
supplierName: "Old supplier",
|
||||
productId: t.water20,
|
||||
productLabel: "20L Jerrycan",
|
||||
quantity: 20,
|
||||
unitCost: 10,
|
||||
totalCost: 200,
|
||||
recordedBy: t.owner.id,
|
||||
});
|
||||
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(0);
|
||||
expect(await backfillPurchaseMovements()).toBe(1);
|
||||
expect(await backfillPurchaseMovements()).toBe(0);
|
||||
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(20);
|
||||
});
|
||||
});
|
||||
|
||||
describe("F-04 / F-05 / CAT-12 catalogue", () => {
|
||||
it("lists deactivated products for managers and keeps their stock visible", async () => {
|
||||
const t = await makeTenant();
|
||||
await adjustments.POST(
|
||||
req("POST", "/x", { as: t.owner, body: { clientUuid: uuid(), branchId: t.branchA, productId: t.water5, mode: "DELTA", quantity: 7 } })
|
||||
);
|
||||
await db(() => Product.updateOne({ _id: t.water5 }, { isActive: false }));
|
||||
|
||||
const forManager = await json(await products.GET(req("GET", "/api/products?includeInactive=1", { as: t.managerA })));
|
||||
const forCashier = await json(await products.GET(req("GET", "/api/products?includeInactive=1", { as: t.cashierA })));
|
||||
expect(forManager.body.products).toHaveLength(2);
|
||||
expect(forCashier.body.products).toHaveLength(1);
|
||||
|
||||
const levels = await getStockLevels(t.businessId);
|
||||
expect(levels.find((l) => l.productId === t.water5 && l.branchId === t.branchA)).toMatchObject({
|
||||
quantity: 7,
|
||||
productActive: false,
|
||||
});
|
||||
expect(levels.some((l) => l.productId === t.water5 && l.branchId === t.branchB)).toBe(false);
|
||||
});
|
||||
|
||||
it("stores count units, refuses duplicate names and zero prices", async () => {
|
||||
const t = await makeTenant();
|
||||
const create = (body: object) => products.POST(req("POST", "/x", { as: t.owner, body }));
|
||||
const tray = await json(await create({ label: "Tray of Eggs", sizeLiters: 30, unit: "pcs", unitPrice: 400 }));
|
||||
expect(tray.status).toBe(201);
|
||||
expect(tray.body.product.unit).toBe("pcs");
|
||||
|
||||
expect((await create({ label: "tray of eggs", sizeLiters: 1, unit: "tray", unitPrice: 400 })).status).toBe(409);
|
||||
expect((await create({ label: "Free sample", sizeLiters: 1, unit: "pcs", unitPrice: 0 })).status).toBe(400);
|
||||
expect((await create({ label: "Bucket", sizeLiters: 1, unit: "buckets", unitPrice: 50 })).status).toBe(400);
|
||||
|
||||
const rename = await productById.PATCH(
|
||||
req("PATCH", "/x", { as: t.owner, body: { label: "20L JERRYCAN" } }),
|
||||
params({ id: t.water5 })
|
||||
);
|
||||
expect(rename.status).toBe(409);
|
||||
});
|
||||
});
|
||||
|
||||
describe("STA-04 staff invites", () => {
|
||||
async function invite(t: Tenant) {
|
||||
const res = await json(
|
||||
await users.POST(
|
||||
req("POST", "/api/users", {
|
||||
as: t.managerA,
|
||||
body: { name: "New Cashier", role: "DELIVERY", phoneNumber: "0711222333", email: "new.cashier@aquaflow.test" },
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
return { userId: res.body.user._id as string, token: (res.body.inviteUrl as string).split("/invite/")[1] };
|
||||
}
|
||||
|
||||
const signIn = (password: string) =>
|
||||
login.POST(req("POST", "/x", { body: { email: "new.cashier@aquaflow.test", password, deviceId: uuid() } }));
|
||||
|
||||
it("lets the invited person set their own password, once", async () => {
|
||||
const t = await makeTenant();
|
||||
const { token } = await invite(t);
|
||||
|
||||
const who = await json(await invites.GET(req("GET", "/x"), params({ token })));
|
||||
expect(who.body).toMatchObject({ name: "New Cashier", email: "new.cashier@aquaflow.test" });
|
||||
|
||||
expect((await invites.POST(req("POST", "/x", { body: { password: "short" } }), params({ token }))).status).toBe(400);
|
||||
expect((await invites.POST(req("POST", "/x", { body: { password: "my-own-secret" } }), params({ token }))).status).toBe(200);
|
||||
expect((await signIn("my-own-secret")).status).toBe(200);
|
||||
|
||||
// The link is single-use.
|
||||
expect((await invites.GET(req("GET", "/x"), params({ token }))).status).toBe(404);
|
||||
});
|
||||
|
||||
it("issues a fresh link that replaces the old one, and rejects expired links", async () => {
|
||||
const t = await makeTenant();
|
||||
const { userId, token } = await invite(t);
|
||||
const again = await json(await reinvite.POST(req("POST", "/x", { as: t.managerA }), params({ id: userId })));
|
||||
expect(again.status).toBe(200);
|
||||
const fresh = (again.body.inviteUrl as string).split("/invite/")[1];
|
||||
|
||||
expect((await invites.GET(req("GET", "/x"), params({ token }))).status).toBe(404);
|
||||
expect((await invites.GET(req("GET", "/x"), params({ token: fresh }))).status).toBe(200);
|
||||
|
||||
await db(() => User.updateOne({ _id: new mongoose.Types.ObjectId(userId) }, { inviteExpiresAt: new Date(Date.now() - 1000) }));
|
||||
expect((await invites.GET(req("GET", "/x"), params({ token: fresh }))).status).toBe(404);
|
||||
});
|
||||
|
||||
it("does not let a manager re-invite another branch's staff", async () => {
|
||||
const t = await makeTenant();
|
||||
await db(() => User.updateOne({ _id: t.cashierB.id }, { inviteExpiresAt: new Date(Date.now() + 60_000) }));
|
||||
const res = await reinvite.POST(req("POST", "/x", { as: t.managerA }), params({ id: t.cashierB.id }));
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { User, UserRole } from "@/lib/server/models/User";
|
||||
import { Product } from "@/lib/server/models/Product";
|
||||
import { signAccessToken } from "@/lib/server/jwt";
|
||||
import { ACCESS_COOKIE } from "@/lib/server/auth";
|
||||
import { crossTenant } from "@/lib/server/tenantGuard";
|
||||
|
||||
let phoneSeq = 0;
|
||||
function nextPhone(): string {
|
||||
@@ -131,3 +132,8 @@ export async function json<T = any>(res: Response): Promise<{ status: number; bo
|
||||
export function uuid(): string {
|
||||
return randomUUID();
|
||||
}
|
||||
|
||||
/** Tests may inspect and arrange any business's data directly. */
|
||||
export function db<T>(fn: () => PromiseLike<T>): Promise<T> {
|
||||
return crossTenant("test inspects the database directly", fn);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { User } from "@/lib/server/models/User";
|
||||
import * as users from "@/app/api/users/route";
|
||||
import * as login from "@/app/api/auth/login/route";
|
||||
import * as me from "@/app/api/auth/me/route";
|
||||
import * as platformBusinesses from "@/app/api/platform/businesses/route";
|
||||
import { ACCESS_COOKIE } from "@/lib/server/auth";
|
||||
import { json, makeTenant, req, uuid, type Actor, type Tenant, db } from "./helpers";
|
||||
|
||||
const PERSON = { name: "Wanjiru", email: "wanjiru@aquaflow.test", phoneNumber: "0722000111" };
|
||||
const OPERATOR = "operator@aquaflow.test"; // listed in PLATFORM_ADMIN_EMAILS by tests/setup.ts
|
||||
|
||||
async function hire(t: Tenant, as: Actor, person = PERSON) {
|
||||
return users.POST(
|
||||
req("POST", "/api/users", { as, body: { ...person, role: "DELIVERY", branchId: t.branchA, password: "password-123" } })
|
||||
);
|
||||
}
|
||||
|
||||
const signIn = (email: string, password: string, businessId?: string) =>
|
||||
login.POST(req("POST", "/api/auth/login", { body: { email, password, deviceId: uuid(), businessId } }));
|
||||
|
||||
async function setPassword(email: string, businessId: string, password: string) {
|
||||
await User.updateOne({ email, businessId }, { passwordHash: await bcrypt.hash(password, 4) });
|
||||
}
|
||||
|
||||
function accessCookie(res: Response): string {
|
||||
const cookie = res.headers.get("set-cookie") ?? "";
|
||||
return cookie.match(new RegExp(`${ACCESS_COOKIE}=([^;]+)`))![1];
|
||||
}
|
||||
|
||||
describe("email and phone are unique per business", () => {
|
||||
it("lets one person work for two businesses with the same email and phone", async () => {
|
||||
const a = await makeTenant("Alpha");
|
||||
const b = await makeTenant("Beta");
|
||||
expect((await hire(a, a.owner)).status).toBe(201);
|
||||
expect((await hire(b, b.owner)).status).toBe(201);
|
||||
expect(await db(() => User.countDocuments({ email: PERSON.email }))).toBe(2);
|
||||
});
|
||||
|
||||
it("still refuses a duplicate inside the same business", async () => {
|
||||
const a = await makeTenant("Alpha");
|
||||
await hire(a, a.owner);
|
||||
const sameEmail = await hire(a, a.owner, { ...PERSON, phoneNumber: "0733000222" });
|
||||
const samePhone = await hire(a, a.owner, { ...PERSON, email: "other@aquaflow.test" });
|
||||
expect([sameEmail.status, samePhone.status]).toEqual([409, 409]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("login when an email exists in several businesses", () => {
|
||||
it("signs straight in when only one account's password matches", async () => {
|
||||
const a = await makeTenant("Alpha");
|
||||
const b = await makeTenant("Beta");
|
||||
await hire(a, a.owner);
|
||||
await hire(b, b.owner);
|
||||
await setPassword(PERSON.email, a.businessId, "alpha-secret");
|
||||
await setPassword(PERSON.email, b.businessId, "beta-secret");
|
||||
|
||||
const res = await json(await signIn(PERSON.email, "beta-secret"));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.user.businessId).toBe(b.businessId);
|
||||
});
|
||||
|
||||
it("asks which business when the same password opens both, then signs in to the one chosen", async () => {
|
||||
const a = await makeTenant("Alpha");
|
||||
const b = await makeTenant("Beta");
|
||||
await hire(a, a.owner);
|
||||
await hire(b, b.owner);
|
||||
await setPassword(PERSON.email, a.businessId, "same-secret");
|
||||
await setPassword(PERSON.email, b.businessId, "same-secret");
|
||||
|
||||
const ask = await json(await signIn(PERSON.email, "same-secret"));
|
||||
expect(ask.status).toBe(300);
|
||||
expect(ask.body.chooseBusiness.map((c: any) => c.businessName).sort()).toEqual(["Alpha", "Beta"]);
|
||||
|
||||
const chosen = await json(await signIn(PERSON.email, "same-secret", a.businessId));
|
||||
expect(chosen.status).toBe(200);
|
||||
expect(chosen.body.user.businessId).toBe(a.businessId);
|
||||
});
|
||||
|
||||
it("reveals nothing about other businesses to a wrong password", async () => {
|
||||
const a = await makeTenant("Alpha");
|
||||
const b = await makeTenant("Beta");
|
||||
await hire(a, a.owner);
|
||||
await hire(b, b.owner);
|
||||
const res = await json(await signIn(PERSON.email, "wrong-password"));
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body.chooseBusiness).toBeUndefined();
|
||||
expect(res.body.error).toBe("Incorrect email or password");
|
||||
});
|
||||
|
||||
it("does not let a wrong guess at one business unlock or reset the other", async () => {
|
||||
const a = await makeTenant("Alpha");
|
||||
const b = await makeTenant("Beta");
|
||||
await hire(a, a.owner);
|
||||
await hire(b, b.owner);
|
||||
await setPassword(PERSON.email, a.businessId, "alpha-secret");
|
||||
await setPassword(PERSON.email, b.businessId, "beta-secret");
|
||||
for (let i = 0; i < 2; i++) await signIn(PERSON.email, "wrong");
|
||||
await signIn(PERSON.email, "alpha-secret"); // resets Alpha's counter only
|
||||
const [alpha, beta] = await Promise.all([
|
||||
User.findOne({ email: PERSON.email, businessId: a.businessId }),
|
||||
User.findOne({ email: PERSON.email, businessId: b.businessId }),
|
||||
]);
|
||||
expect([alpha!.failedLoginAttempts, beta!.failedLoginAttempts]).toEqual([0, 2]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("platform operator access", () => {
|
||||
it("is not granted by an email match alone: another business cannot mint an operator", async () => {
|
||||
const mallory = await makeTenant("Mallory Water");
|
||||
await hire(mallory, mallory.owner, { name: "Fake operator", email: OPERATOR, phoneNumber: "0744000333" });
|
||||
await setPassword(OPERATOR, mallory.businessId, "i-am-the-operator");
|
||||
|
||||
const res = await signIn(OPERATOR, "i-am-the-operator");
|
||||
expect(res.status).toBe(200);
|
||||
expect((await res.clone().json()).isPlatformAdmin).toBe(false);
|
||||
|
||||
const consoleRes = await platformBusinesses.GET(
|
||||
req("GET", "/api/platform/businesses", { cookies: { [ACCESS_COOKIE]: accessCookie(res) } })
|
||||
);
|
||||
expect(consoleRes.status).toBe(403);
|
||||
});
|
||||
|
||||
it("is granted to the flagged account whose email is listed", async () => {
|
||||
const home = await makeTenant("Operator Co");
|
||||
await hire(home, home.owner, { name: "Operator", email: OPERATOR, phoneNumber: "0755000444" });
|
||||
await User.updateOne({ email: OPERATOR, businessId: home.businessId }, { platformAdmin: true });
|
||||
await setPassword(OPERATOR, home.businessId, "real-operator");
|
||||
|
||||
const res = await signIn(OPERATOR, "real-operator");
|
||||
const cookies = { [ACCESS_COOKIE]: accessCookie(res) };
|
||||
expect((await platformBusinesses.GET(req("GET", "/x", { cookies }))).status).toBe(200);
|
||||
expect((await json(await me.GET(req("GET", "/x", { cookies })))).body.user.isPlatformAdmin).toBe(true);
|
||||
});
|
||||
|
||||
it("is revoked by removing the email from PLATFORM_ADMIN_EMAILS, even with the flag", async () => {
|
||||
const home = await makeTenant("Operator Co");
|
||||
await hire(home, home.owner, { name: "Operator", email: OPERATOR, phoneNumber: "0755000444" });
|
||||
await User.updateOne({ email: OPERATOR, businessId: home.businessId }, { platformAdmin: true });
|
||||
await setPassword(OPERATOR, home.businessId, "real-operator");
|
||||
const cookies = { [ACCESS_COOKIE]: accessCookie(await signIn(OPERATOR, "real-operator")) };
|
||||
|
||||
const listed = process.env.PLATFORM_ADMIN_EMAILS;
|
||||
process.env.PLATFORM_ADMIN_EMAILS = "";
|
||||
try {
|
||||
expect((await platformBusinesses.GET(req("GET", "/x", { cookies }))).status).toBe(403);
|
||||
} finally {
|
||||
process.env.PLATFORM_ADMIN_EMAILS = listed;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import mongoose from "mongoose";
|
||||
import { readdirSync } from "fs";
|
||||
import path from "path";
|
||||
import { crossTenant, isTenantGuarded, TenantScopeError } from "@/lib/server/tenantGuard";
|
||||
import { User } from "@/lib/server/models/User";
|
||||
import { Transaction } from "@/lib/server/models/Transaction";
|
||||
import { Expense } from "@/lib/server/models/Expense";
|
||||
import { StockMovement } from "@/lib/server/models/StockMovement";
|
||||
import { stockOf } from "@/lib/server/stock";
|
||||
import * as cash from "@/app/api/transactions/cash/route";
|
||||
import * as transactions from "@/app/api/transactions/route";
|
||||
import * as expenses from "@/app/api/expenses/route";
|
||||
import * as purchases from "@/app/api/purchases/route";
|
||||
import * as stock from "@/app/api/stock/route";
|
||||
import * as movements from "@/app/api/stock/movements/route";
|
||||
import * as transfers from "@/app/api/stock/transfers/route";
|
||||
import * as adjustments from "@/app/api/stock/adjustments/route";
|
||||
import * as summary from "@/app/api/dashboard/summary/route";
|
||||
import * as reconciliation from "@/app/api/dashboard/reconciliation/route";
|
||||
import * as profit from "@/app/api/reports/profit/route";
|
||||
import * as users from "@/app/api/users/route";
|
||||
import * as userById from "@/app/api/users/[id]/route";
|
||||
import * as reinvite from "@/app/api/users/[id]/invite/route";
|
||||
import * as branchById from "@/app/api/branches/[id]/route";
|
||||
import * as productById from "@/app/api/products/[id]/route";
|
||||
import * as branchPrices from "@/app/api/branch-prices/route";
|
||||
import * as dispatch from "@/app/api/inventory/dispatch/route";
|
||||
import * as eveningCount from "@/app/api/inventory/evening-count/route";
|
||||
import { db, json, makeTenant, params, req, uuid, type Tenant } from "./helpers";
|
||||
|
||||
// Models that hold one business's data but are deliberately unguarded (see tenantGuard.ts).
|
||||
const UNGUARDED = new Set(["Business", "UserSession", "MpesaCallbackLog", "StockLock"]);
|
||||
|
||||
describe("the tenant guard", () => {
|
||||
it("is on every model that stores a businessId", async () => {
|
||||
// Load every model file so none can be skipped by accident.
|
||||
const dir = path.resolve(__dirname, "../src/lib/server/models");
|
||||
for (const file of readdirSync(dir)) await import(path.join(dir, file));
|
||||
|
||||
const scoped = Object.values(mongoose.models).filter((m) => m.schema.path("businessId") && !UNGUARDED.has(m.modelName));
|
||||
expect(scoped.length).toBeGreaterThanOrEqual(10);
|
||||
const unguarded = scoped.filter((m) => !isTenantGuarded(m.schema)).map((m) => m.modelName);
|
||||
expect(unguarded).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses queries that do not name exactly one business", async () => {
|
||||
const t = await makeTenant();
|
||||
const attempts: [string, () => PromiseLike<unknown>][] = [
|
||||
["find", () => Transaction.find({ branchId: t.branchA })],
|
||||
["findById", () => User.findById(t.cashierA.id)],
|
||||
["exists", () => StockMovement.exists({ type: "SALE" })],
|
||||
["updateMany", () => Expense.updateMany({}, { amount: 0 })],
|
||||
["deleteMany", () => Transaction.deleteMany({ paymentMethod: "CASH" })],
|
||||
["countDocuments", () => User.countDocuments({})],
|
||||
["$in over businesses", () => User.find({ businessId: { $in: [t.businessId, new mongoose.Types.ObjectId()] } })],
|
||||
["$exists", () => User.find({ businessId: { $exists: true } })],
|
||||
["aggregate without $match", () => Transaction.aggregate([{ $group: { _id: "$businessId" } }])],
|
||||
["aggregate matching later", () => Transaction.aggregate([{ $sort: { createdAt: -1 } }, { $match: { businessId: t.businessId } }])],
|
||||
["unscoped populate", () => Expense.find({ businessId: t.businessId }).populate("branchId")],
|
||||
];
|
||||
await Expense.create({ businessId: t.businessId, branchId: t.branchA, category: "Rent", amount: 1, description: "x", recordedBy: t.owner.id });
|
||||
for (const [label, run] of attempts) {
|
||||
await expect(Promise.resolve().then(run), label).rejects.toBeInstanceOf(TenantScopeError);
|
||||
}
|
||||
});
|
||||
|
||||
it("allows scoped queries, and cross-business ones only with a stated reason", async () => {
|
||||
const t = await makeTenant();
|
||||
expect(await User.countDocuments({ businessId: t.businessId })).toBe(4);
|
||||
expect(await User.countDocuments({ $and: [{ businessId: t.businessId }, { role: "DELIVERY" }] })).toBe(2);
|
||||
expect(await crossTenant("test", () => User.countDocuments({}))).toBe(4);
|
||||
expect(() => crossTenant(" ", () => User.countDocuments({}))).toThrow(/reason/);
|
||||
// The exemption ends with the callback.
|
||||
await expect(Promise.resolve().then(() => User.countDocuments({}))).rejects.toBeInstanceOf(TenantScopeError);
|
||||
});
|
||||
});
|
||||
|
||||
/** Give tenant B one of everything, so a leak into tenant A's view would show. */
|
||||
async function seedVictim(b: Tenant) {
|
||||
await adjustments.POST(
|
||||
req("POST", "/x", { as: b.owner, body: { clientUuid: uuid(), branchId: b.branchA, productId: b.water20, mode: "DELTA", quantity: 50 } })
|
||||
);
|
||||
await cash.POST(
|
||||
req("POST", "/x", { as: b.cashierA, body: { sales: [{ clientUuid: uuid(), lines: [{ productId: b.water20, quantity: 3 }] }] } })
|
||||
);
|
||||
await expenses.POST(req("POST", "/x", { as: b.owner, body: { branchId: b.branchA, category: "Rent", amount: 7777, description: "B rent" } }));
|
||||
await purchases.POST(
|
||||
req("POST", "/x", { as: b.owner, body: { branchId: b.branchA, supplierName: "B supplier", productId: b.water20, quantity: 5, unitCost: 99 } })
|
||||
);
|
||||
await transfers.POST(
|
||||
req("POST", "/x", { as: b.owner, body: { clientUuid: uuid(), fromBranchId: b.branchA, toBranchId: b.branchB, productId: b.water20, quantity: 2 } })
|
||||
);
|
||||
}
|
||||
|
||||
describe("route sweep: another business's ids get nothing", () => {
|
||||
it("every read route returns none of business B's data to business A, whatever ids A sends", async () => {
|
||||
const a = await makeTenant("Alpha");
|
||||
const b = await makeTenant("Beta");
|
||||
await seedVictim(b);
|
||||
|
||||
const reads: [string, Response][] = [];
|
||||
const get = async (label: string, handler: (r: any) => Promise<Response>, url: string) =>
|
||||
reads.push([label, await handler(req("GET", url, { as: a.owner }))]);
|
||||
const q = "?branchId=" + b.branchA;
|
||||
await get("transactions", transactions.GET, "/api/transactions" + q);
|
||||
await get("expenses", expenses.GET, "/api/expenses" + q);
|
||||
await get("purchases", purchases.GET, "/api/purchases" + q);
|
||||
await get("stock", stock.GET, "/api/stock" + q);
|
||||
await get("movements", movements.GET, "/api/stock/movements" + q);
|
||||
await get("transfers", transfers.GET, "/api/stock/transfers" + q);
|
||||
await get("summary", summary.GET, "/api/dashboard/summary" + q);
|
||||
await get("reconciliation", reconciliation.GET, "/api/dashboard/reconciliation" + q);
|
||||
await get("profit", profit.GET, "/api/reports/profit" + q);
|
||||
await get("users", users.GET, "/api/users" + q);
|
||||
await get("branch prices", branchPrices.GET, "/api/branch-prices" + q);
|
||||
|
||||
const bIds = [b.businessId, b.branchA, b.branchB, b.water20, b.owner.id, b.cashierA.id];
|
||||
for (const [label, res] of reads) {
|
||||
const text = await res.text();
|
||||
for (const id of bIds) expect(text.includes(id), `${label} leaked ${id}`).toBe(false);
|
||||
expect(text.includes("7777") || text.includes("B supplier"), `${label} leaked B's figures`).toBe(false);
|
||||
}
|
||||
// Totals A sees are A's own (zero), not B's sale.
|
||||
const totals = JSON.parse(await (await summary.GET(req("GET", "/api/dashboard/summary" + q, { as: a.owner }))).text());
|
||||
expect(totals.totals.cashTotal).toBe(0);
|
||||
});
|
||||
|
||||
it("every write route refuses business B's ids and leaves B's data untouched", async () => {
|
||||
const a = await makeTenant("Alpha");
|
||||
const b = await makeTenant("Beta");
|
||||
await seedVictim(b);
|
||||
const before = {
|
||||
stockA: await stockOf(b.businessId, b.branchA, b.water20),
|
||||
cashier: await db(() => User.findById(b.cashierA.id).lean()),
|
||||
sales: await Transaction.countDocuments({ businessId: b.businessId }),
|
||||
};
|
||||
|
||||
const as = a.owner;
|
||||
const writes: [string, Response][] = [
|
||||
["deactivate B's cashier", await userById.PATCH(req("PATCH", "/x", { as, body: { isActive: false } }), params({ id: b.cashierA.id }))],
|
||||
["move B's cashier", await userById.PATCH(req("PATCH", "/x", { as, body: { branchId: a.branchA } }), params({ id: b.cashierA.id }))],
|
||||
["re-invite B's cashier", await reinvite.POST(req("POST", "/x", { as }), params({ id: b.cashierA.id }))],
|
||||
["rename B's branch", await branchById.PATCH(req("PATCH", "/x", { as, body: { branchName: "Pwned" } }), params({ id: b.branchA }))],
|
||||
["reprice B's product", await productById.PATCH(req("PATCH", "/x", { as, body: { unitPrice: 1 } }), params({ id: b.water20 }))],
|
||||
["branch price on B", await branchPrices.PUT(req("PUT", "/x", { as, body: { branchId: b.branchA, productId: b.water20, unitPrice: 1 } }))],
|
||||
["adjust B's stock", await adjustments.POST(req("POST", "/x", { as, body: { clientUuid: uuid(), branchId: b.branchA, productId: b.water20, mode: "COUNT", quantity: 0 } }))],
|
||||
["transfer out of B", await transfers.POST(req("POST", "/x", { as, body: { clientUuid: uuid(), fromBranchId: b.branchA, toBranchId: a.branchA, productId: b.water20, quantity: 1 } }))],
|
||||
["transfer into B", await transfers.POST(req("POST", "/x", { as, body: { clientUuid: uuid(), fromBranchId: a.branchA, toBranchId: b.branchA, productId: a.water20, quantity: 1 } }))],
|
||||
["expense on B", await expenses.POST(req("POST", "/x", { as, body: { branchId: b.branchA, category: "Rent", amount: 1, description: "x" } }))],
|
||||
["purchase into B", await purchases.POST(req("POST", "/x", { as, body: { branchId: b.branchA, supplierName: "x", productId: b.water20, quantity: 1, unitCost: 1 } }))],
|
||||
["dispatch at B", await dispatch.POST(req("POST", "/x", { as, body: { branchId: b.branchA, productId: b.water20, morningDispatched: 1 } }))],
|
||||
["count at B", await eveningCount.POST(req("POST", "/x", { as, body: { branchId: b.branchA, productId: b.water20, eveningPhysicalCount: 1 } }))],
|
||||
["sale of B's product", await cash.POST(req("POST", "/x", { as: a.cashierA, body: { sales: [{ clientUuid: uuid(), lines: [{ productId: b.water20, quantity: 1 }] }] } }))],
|
||||
];
|
||||
for (const [label, res] of writes) {
|
||||
if (label.startsWith("sale")) {
|
||||
expect((await json(res)).body.results[0].status, label).toBe("rejected");
|
||||
} else {
|
||||
expect(res.status, label).toBeGreaterThanOrEqual(400);
|
||||
}
|
||||
}
|
||||
|
||||
expect(await stockOf(b.businessId, b.branchA, b.water20)).toBe(before.stockA);
|
||||
expect(await db(() => User.findById(b.cashierA.id).lean())).toMatchObject({
|
||||
isActive: before.cashier!.isActive,
|
||||
branchId: before.cashier!.branchId,
|
||||
});
|
||||
expect(await Transaction.countDocuments({ businessId: b.businessId })).toBe(before.sales);
|
||||
expect(await Expense.countDocuments({ businessId: b.businessId })).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Product } from "@/lib/server/models/Product";
|
||||
import { Purchase } from "@/lib/server/models/Purchase";
|
||||
import { Transaction } from "@/lib/server/models/Transaction";
|
||||
import { backfillPurchaseMovements, stockOf } from "@/lib/server/stock";
|
||||
import * as cash from "@/app/api/transactions/cash/route";
|
||||
import * as transfers from "@/app/api/stock/transfers/route";
|
||||
import * as profit from "@/app/api/reports/profit/route";
|
||||
import * as summary from "@/app/api/dashboard/summary/route";
|
||||
import { json, makeTenant, req, uuid, type Actor } from "./helpers";
|
||||
|
||||
/**
|
||||
* The "Completion and retest plan" from the 11 October 2026 test report
|
||||
* (AquaFlow_Initial_Test_Report, pages 9-10), with its expected numbers.
|
||||
*/
|
||||
describe("initial test report: completion and retest plan", () => {
|
||||
it("matches every planned balance and total", async () => {
|
||||
const t = await makeTenant("ZERRO");
|
||||
const [refill3] = await Product.insertMany([
|
||||
{ businessId: t.businessId, label: "QA 20261011 3L Refill", sizeLiters: 3, unitPrice: 40 },
|
||||
]);
|
||||
const l3 = refill3._id.toString();
|
||||
const l5 = t.water5; // KES 60
|
||||
|
||||
// Fixtures recorded before the ledger existed (QA-20261011-STOCK-A-3L / -5L),
|
||||
// brought into stock by the one-off backfill.
|
||||
await Purchase.insertMany([
|
||||
{ businessId: t.businessId, branchId: t.branchA, supplierName: "QA", productId: l3, productLabel: "3L", quantity: 20, unitCost: 10, totalCost: 200, recordedBy: t.owner.id },
|
||||
{ businessId: t.businessId, branchId: t.branchA, supplierName: "QA", productId: l5, productLabel: "5L", quantity: 10, unitCost: 20, totalCost: 200, recordedBy: t.owner.id },
|
||||
]);
|
||||
await backfillPurchaseMovements(t.businessId);
|
||||
const stock = async (branch: string, product: string) => stockOf(t.businessId, branch, product);
|
||||
expect([await stock(t.branchA, l3), await stock(t.branchA, l5)]).toEqual([20, 10]);
|
||||
|
||||
const sell = async (as: Actor, lines: { productId: string; quantity: number }[], offline = false) =>
|
||||
json(
|
||||
await cash.POST(
|
||||
req("POST", "/x", {
|
||||
as,
|
||||
body: {
|
||||
sales: [
|
||||
{
|
||||
clientUuid: uuid(),
|
||||
staffId: as.id,
|
||||
branchId: as.branchId,
|
||||
lines,
|
||||
...(offline ? { clientSubmittedAt: new Date().toISOString() } : {}),
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
// Online sale: 2 x 3L + 1 x 5L = KES 140; A balances 18 and 9.
|
||||
const online = await sell(t.cashierA, [{ productId: l3, quantity: 2 }, { productId: l5, quantity: 1 }]);
|
||||
expect(online.body.results[0]).toMatchObject({ status: "saved", amountTotal: 140 });
|
||||
expect([await stock(t.branchA, l3), await stock(t.branchA, l5)]).toEqual([18, 9]);
|
||||
|
||||
// Transfer 5 x 3L from A to B: A 13, B 5, combined 18.
|
||||
const transfer = await transfers.POST(
|
||||
req("POST", "/x", {
|
||||
as: t.owner,
|
||||
body: { clientUuid: uuid(), fromBranchId: t.branchA, toBranchId: t.branchB, productId: l3, quantity: 5 },
|
||||
})
|
||||
);
|
||||
expect(transfer.status).toBe(201);
|
||||
expect([await stock(t.branchA, l3), await stock(t.branchB, l3)]).toEqual([13, 5]);
|
||||
|
||||
// Two offline sales replayed on reconnect (sale 2: 1 x 3L; sale 3: 2 x 3L + 1 x 5L),
|
||||
// then replayed again: exactly two new sales (three lines), A 10 x 3L and 8 x 5L.
|
||||
const before = await Transaction.countDocuments({ businessId: t.businessId });
|
||||
const queued = [
|
||||
{ clientUuid: uuid(), staffId: t.cashierA.id, branchId: t.branchA, clientSubmittedAt: new Date().toISOString(), lines: [{ productId: l3, quantity: 1 }] },
|
||||
{ clientUuid: uuid(), staffId: t.cashierA.id, branchId: t.branchA, clientSubmittedAt: new Date().toISOString(), lines: [{ productId: l3, quantity: 2 }, { productId: l5, quantity: 1 }] },
|
||||
];
|
||||
for (let pass = 0; pass < 2; pass++) {
|
||||
const r = await json(await cash.POST(req("POST", "/x", { as: t.cashierA, body: { sales: queued } })));
|
||||
expect(r.body.results.map((x: any) => x.status)).toEqual(pass === 0 ? ["saved", "saved"] : ["duplicate", "duplicate"]);
|
||||
}
|
||||
expect((await Transaction.countDocuments({ businessId: t.businessId })) - before).toBe(3);
|
||||
expect([await stock(t.branchA, l3), await stock(t.branchA, l5)]).toEqual([10, 8]);
|
||||
|
||||
// Branch B sells 1 x 3L for KES 40.
|
||||
await sell(t.cashierB, [{ productId: l3, quantity: 1 }]);
|
||||
|
||||
// Final: A 3L 10, B 3L 4, A 5L 8; combined 3L 14 = 20 - 6 sold, 5L 8 = 10 - 2 sold.
|
||||
expect([await stock(t.branchA, l3), await stock(t.branchB, l3), await stock(t.branchA, l5)]).toEqual([10, 4, 8]);
|
||||
|
||||
// Revenue: A KES 320, B KES 40, total KES 360 — on the report and the owner dashboard.
|
||||
const report = async (q: string) => (await json(await profit.GET(req("GET", "/api/reports/profit" + q, { as: t.owner })))).body;
|
||||
expect((await report("")).revenue).toBe(360);
|
||||
expect((await report("?branchId=" + t.branchA)).revenue).toBe(320);
|
||||
expect((await report("?branchId=" + t.branchB)).revenue).toBe(40);
|
||||
|
||||
const dash = (await json(await summary.GET(req("GET", "/api/dashboard/summary", { as: t.owner })))).body;
|
||||
expect(dash.totals.cashTotal).toBe(360);
|
||||
const ranking = Object.fromEntries(dash.branchRanking.map((b: any) => [b.branchName, b.revenue]));
|
||||
expect(ranking).toEqual({ "ZERRO A": 320, "ZERRO B": 40 });
|
||||
});
|
||||
});
|
||||
+7
-7
@@ -4,7 +4,7 @@ import { Product, BranchPricing } from "@/lib/server/models/Product";
|
||||
import { stockOf } from "@/lib/server/stock";
|
||||
import * as cash from "@/app/api/transactions/cash/route";
|
||||
import type { SaleResult } from "@/lib/syncProtocol";
|
||||
import { json, makeTenant, req, uuid, type Actor, type Tenant } from "./helpers";
|
||||
import { json, makeTenant, req, uuid, type Actor, type Tenant, db } from "./helpers";
|
||||
|
||||
function sale(t: Tenant, cashier: Actor, lines: { productId: string; quantity: number; unitPrice?: number }[], extra = {}) {
|
||||
return {
|
||||
@@ -31,7 +31,7 @@ describe("offline sale sync", () => {
|
||||
const { status, body } = await post(t.cashierA, [s]);
|
||||
expect(status).toBe(200);
|
||||
expect(body.results).toEqual([{ clientUuid: s.clientUuid, status: "saved", amountTotal: 580, priceMismatch: false }]);
|
||||
expect(await Transaction.countDocuments({ saleId: s.clientUuid })).toBe(2);
|
||||
expect(await db(() => Transaction.countDocuments({ saleId: s.clientUuid }))).toBe(2);
|
||||
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(-2);
|
||||
expect(await stockOf(t.businessId, t.branchA, t.water5)).toBe(-3);
|
||||
});
|
||||
@@ -42,7 +42,7 @@ describe("offline sale sync", () => {
|
||||
await post(t.cashierA, [s]);
|
||||
const replay = await post(t.cashierA, [s]);
|
||||
expect(replay.body.results[0]).toMatchObject({ clientUuid: s.clientUuid, status: "duplicate" });
|
||||
expect(await Transaction.countDocuments({ saleId: s.clientUuid })).toBe(1);
|
||||
expect(await db(() => Transaction.countDocuments({ saleId: s.clientUuid }))).toBe(1);
|
||||
expect(await stockOf(t.businessId, t.branchA, t.water20)).toBe(-1);
|
||||
});
|
||||
|
||||
@@ -78,7 +78,7 @@ describe("offline sale sync", () => {
|
||||
const otherCashiersSale = sale(t, t.cashierB, [{ productId: t.water20, quantity: 1 }]);
|
||||
const { body } = await post(t.cashierA, [otherCashiersSale]);
|
||||
expect(body.results[0].status).toBe("rejected");
|
||||
expect(await Transaction.countDocuments({})).toBe(0);
|
||||
expect(await db(() => Transaction.countDocuments({}))).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps a sale at the branch where it happened after the cashier is moved", async () => {
|
||||
@@ -86,7 +86,7 @@ describe("offline sale sync", () => {
|
||||
const s = sale(t, t.cashierA, [{ productId: t.water20, quantity: 1 }]); // recorded at branch A
|
||||
const moved = { ...t.cashierA, branchId: t.branchB };
|
||||
await post(moved, [s]);
|
||||
const txn = await Transaction.findOne({ saleId: s.clientUuid });
|
||||
const txn = await db(() => Transaction.findOne({ saleId: s.clientUuid }));
|
||||
expect(txn!.branchId.toString()).toBe(t.branchA);
|
||||
});
|
||||
|
||||
@@ -97,13 +97,13 @@ describe("offline sale sync", () => {
|
||||
const foreignBranch = sale(t, t.cashierA, [{ productId: t.water20, quantity: 1 }], { branchId: other.branchA });
|
||||
const { body } = await post(t.cashierA, [foreignProduct, foreignBranch]);
|
||||
expect(body.results.map((r) => r.status)).toEqual(["rejected", "rejected"]);
|
||||
expect(await Transaction.countDocuments({})).toBe(0);
|
||||
expect(await db(() => Transaction.countDocuments({}))).toBe(0);
|
||||
});
|
||||
|
||||
it("uses the branch price, flags a price the device showed differently, and keeps deactivated products sellable", async () => {
|
||||
const t = await makeTenant();
|
||||
await BranchPricing.create({ businessId: t.businessId, branchId: t.branchA, productId: t.water20, unitPrice: 180 });
|
||||
await Product.updateOne({ _id: t.water5 }, { isActive: false });
|
||||
await db(() => Product.updateOne({ _id: t.water5 }, { isActive: false }));
|
||||
const s = sale(t, t.cashierA, [
|
||||
{ productId: t.water20, quantity: 1, unitPrice: 200 }, // stale price on the device
|
||||
{ productId: t.water5, quantity: 1, unitPrice: 60 },
|
||||
|
||||
Reference in New Issue
Block a user