Files
ERP/src/app/api/platform/businesses/route.ts
T
denis_ireri 83ec5ecd36 Enforce tenant isolation in the data layer instead of per route
Every route had to remember to add the business filter to every query;
nothing stopped one that forgot. The audit for this change found several
that had: the M-Pesa status re-check, the stock ledger's duplicate checks,
the daily-inventory and branch-price upserts, a cash-sale replay lookup,
several load-by-id lookups, and every populate().

- tenantGuard: a Mongoose plugin on all ten business-scoped models. Any
  find/update/delete/count/distinct, or an aggregate whose first stage is
  not a $match, that does not pin exactly one businessId throws
  TenantScopeError before reaching the database ($in, $exists and other
  operators do not count).
- crossTenant("reason", fn): the explicit, documented exemption for the
  queries that must span businesses - login's email lookup, refresh and
  invite-token lookups, the M-Pesa callback, the platform console and the
  maintenance scripts. git grep crossTenant lists them all.
- scopedPopulate: populated branch, product and staff names are also
  restricted to the business.
- Every flagged query site now names the business (or is exempted with a
  reason).
- Tests: a check that every model with a businessId field carries the
  guard; the guard refusing unscoped queries of every kind; and a route
  sweep where business A sends business B's ids to every read route
  (nothing of B's comes back) and every write route (all refused, B's
  data unchanged). Test-side database inspections go through db(), an
  explicit test exemption. Removing one route's business filter makes the
  suite fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 11:52:35 +03:00

88 lines
3.5 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { connectDb } from "@/lib/server/db";
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 { crossTenant } from "@/lib/server/tenantGuard";
import { TIERS, effectiveMaxBranches, type TierId, type SubscriptionStatus } from "@/lib/tiers";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
/**
* Platform command center — list EVERY business across all tenants with
* subscription + usage stats. Operator-only (platform admin email).
* This is the one place that intentionally crosses the tenant boundary;
* ordinary business owners can never reach it.
*/
export async function GET(req: NextRequest) {
await connectDb();
const admin = await requirePlatformAdmin(req);
if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
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 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 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) => {
const tier = (b.tier as TierId) ?? "STARTER";
const owner = ownerMap.get(String(b.ownerId));
return {
id: String(b._id),
name: b.name,
tier,
tierName: TIERS[tier].name,
priceKsh: TIERS[tier].priceKsh,
subscriptionStatus: b.subscriptionStatus ?? "TRIALING",
trialEndsAt: b.trialEndsAt ?? null,
currentPeriodEnd: b.currentPeriodEnd ?? null,
isActive: b.isActive,
createdAt: b.createdAt,
userCount: userMap.get(String(b._id)) ?? 0,
branchCount: branchMap.get(String(b._id)) ?? 0,
maxUsers: TIERS[tier].maxUsers,
maxBranches: effectiveMaxBranches(tier, (b.subscriptionStatus as SubscriptionStatus) ?? "TRIALING"),
owner: owner
? { name: owner.name, email: owner.email, phoneNumber: owner.phoneNumber }
: null,
};
});
// Headline MRR = sum of monthly price for businesses that are ACTIVE.
const mrr = rows
.filter((r) => r.subscriptionStatus === "ACTIVE")
.reduce((sum, r) => sum + r.priceKsh, 0);
return NextResponse.json({
businesses: rows,
stats: {
total: rows.length,
active: rows.filter((r) => r.subscriptionStatus === "ACTIVE").length,
trialing: rows.filter((r) => r.subscriptionStatus === "TRIALING").length,
suspended: rows.filter((r) => r.subscriptionStatus === "SUSPENDED").length,
mrr,
},
});
}