feat(admin): multi-brand admin support

Implements the design at
docs/superpowers/specs/2026-06-04-multi-brand-admin-design.md.

Adds:
- admin_user_brands junction table (m:n admin<->brand) via migration 207
- New role 'multi_brand_admin' (auto-set when an admin has 2+ brands)
- 'active_brand_id' cookie that persists the admin's currently-selected
  brand across navigations; switchable via the new BrandSelector dropdown
  in the sidebar
- Centralised brand resolution in src/lib/brand-scope.ts:
  - getActiveBrandId (URL > cookie > legacy brand_id > first of brand_ids)
  - assertBrandAccess (defence-in-depth for cases where the brandId
    comes from a URL form or RPC return)
- ~30 server actions and ~10 page server components migrated to use
  getActiveBrandId instead of the silent brandId ?? adminUser.brand_id
  pattern that allowed cross-brand access bugs
- BrandSelector client component with proper a11y (aria-haspopup,
  aria-expanded, role=listbox, outside-click and escape-to-close)

Migration 207 also adds RLS so admins can read their own junction rows
(needed for the dropdown to populate) and SECURITY DEFINER RPCs
add/remove_admin_user_brand that auto-promote/demote between
brand_admin and multi_brand_admin.

Notes:
- Migration number is 207 not 204 — 204-206 were taken in this worktree
  by the concurrent locations work.
- The legacy admin_users.brand_id column is preserved for backwards
  compat; a follow-up migration 220_* will drop it.
- Dev sessions (dev_session cookie, NEXT_PUBLIC_USE_MOCK_DATA) get
  brand_ids: []; the documented limitation is that dev store_employee
  will see <AdminAccessDenied /> if no real brands exist.
- Pages that hardcode a Tuxedo brand UUID as a fallback
  (adminUser.brand_id ?? '64294306-...') are NOT migrated in this PR —
  they still work for single-brand admins and are out of scope.

Co-authored-by: implementer subagent (cancelled mid-run), Grok orchestrator
This commit is contained in:
2026-06-04 17:09:24 +00:00
parent bd623020d5
commit 63842a9efc
36 changed files with 998 additions and 127 deletions
+4 -1
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { assertBrandAccess } from "@/lib/brand-scope";
import { parseExcelBuffer, parseTextBuffer } from "@/lib/excel-parser";
import { importProductsBatch } from "@/actions/import-products";
import { importOrdersBatch } from "@/actions/import-orders";
@@ -41,7 +42,9 @@ export async function analyzeImport(
): Promise<AnalyzeImportResult> {
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, error: "Not authenticated" };
if (adminUser.role === "brand_admin" && adminUser.brand_id !== brandId) {
try {
assertBrandAccess(adminUser, brandId);
} catch {
return { success: false, error: "Not authorized for this brand" };
}
+4 -3
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
@@ -96,7 +97,7 @@ async function brandScopedRPC<T>(
const adminUser = await getAdminUser();
if (!adminUser) throw new Error("Not authenticated");
const brandId = adminUser.brand_id ?? null;
const brandId = await getActiveBrandId(adminUser);
const response = await fetch(`${supabaseUrl}/rest/v1/rpc/${rpcName}`, {
method: "POST",
@@ -232,7 +233,7 @@ export async function getRecentOrders(limit: number = 10): Promise<RecentOrder[]
const adminUser = await getAdminUser();
if (!adminUser) throw new Error("Not authenticated");
const brandId = adminUser.brand_id ?? null;
const brandId = await getActiveBrandId(adminUser);
const params = new URLSearchParams({
select: "id,customer_name,subtotal,status,created_at,fulfillment",
@@ -293,7 +294,7 @@ export async function getConversionFunnel(): Promise<ConversionFunnel[]> {
const adminUser = await getAdminUser();
if (!adminUser) throw new Error("Not authenticated");
const brandId = adminUser.brand_id ?? null;
const brandId = await getActiveBrandId(adminUser);
const params = new URLSearchParams({
select: "id,status",
+65
View File
@@ -0,0 +1,65 @@
import "server-only";
import { getAdminUser } from "@/lib/admin-permissions";
import { svcHeaders } from "@/lib/svc-headers";
export type BrandListItem = {
id: string;
name: string;
slug: string;
logo_url: string | null;
};
/**
* Returns the list of brands the current admin user can act in.
*
* - platform_admin: all brands (queried directly from the `brands` table)
* - everyone else: brands in `adminUser.brand_ids`
* - empty array for unauthenticated / no-access admins
*
* This is a plain async function (not a server action) so it can be called
* from server components and server actions without the "use server" wrapper.
* The BrandSelector client component receives the result as a prop.
*/
export async function listBrandsForAdmin(): Promise<BrandListItem[]> {
const adminUser = await getAdminUser();
if (!adminUser) return [];
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!supabaseUrl || !serviceKey) return [];
if (adminUser.role === "platform_admin") {
try {
const res = await fetch(
`${supabaseUrl}/rest/v1/brands?select=id,name,slug,logo_url&order=name`,
{ headers: svcHeaders(serviceKey), cache: "no-store" }
);
if (!res.ok) return [];
const data = await res.json();
return Array.isArray(data) ? data : [];
} catch {
return [];
}
}
if (adminUser.brand_ids.length === 0) return [];
// Use PostgREST `in` filter. The brand_ids are UUIDs, so the quoting
// pattern in the spec is safe; the inner quotes are required by PostgREST
// for UUID literals.
const filter = `id=in.(${adminUser.brand_ids
.map((id) => `"${id}"`)
.join(",")})`;
try {
const res = await fetch(
`${supabaseUrl}/rest/v1/brands?${filter}&select=id,name,slug,logo_url&order=name`,
{ headers: svcHeaders(serviceKey), cache: "no-store" }
);
if (!res.ok) return [];
const data = await res.json();
return Array.isArray(data) ? data : [];
} catch {
return [];
}
}
+8 -3
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
export type CampaignType = "marketing" | "operational" | "transactional";
@@ -57,7 +58,11 @@ export async function getCommunicationCampaigns(brandId?: string): Promise<ListC
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, error: "Not authenticated" };
const effectiveBrandId = brandId ?? adminUser.brand_id ?? null;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, error: "Brand access required" };
}
const effectiveBrandId = activeBrandId;
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
@@ -147,7 +152,7 @@ export async function deleteCampaign(campaignId: string, brandId?: string): Prom
{
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({ p_campaign_id: campaignId, p_brand_id: adminUser.brand_id ?? null }),
body: JSON.stringify({ p_campaign_id: campaignId, p_brand_id: (await getActiveBrandId(adminUser)) ?? null }),
}
);
@@ -167,7 +172,7 @@ export async function getCampaignById(campaignId: string, brandId?: string): Pro
{
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({ p_campaign_id: campaignId, p_brand_id: brandId ?? adminUser.brand_id ?? null }),
body: JSON.stringify({ p_campaign_id: campaignId, p_brand_id: (await getActiveBrandId(adminUser, brandId)) ?? null }),
}
);
+8 -3
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
import type { AudienceRules } from "./campaigns";
@@ -120,11 +121,15 @@ export async function sendCampaign(campaignId: string, brandId?: string): Promis
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, error: "Not authenticated" };
// Resolve brand from campaign or parameter
const effectiveBrandId = brandId ?? adminUser.brand_id;
// Resolve brand from campaign or parameter (URL > cookie > legacy > first of brand_ids)
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, error: "Brand access required" };
}
const effectiveBrandId = activeBrandId;
// Brand scoping: brand_admin can only send their own brand's campaigns
if (adminUser.role === "brand_admin" && effectiveBrandId && adminUser.brand_id !== effectiveBrandId) {
if (adminUser.role === "brand_admin" && effectiveBrandId && !adminUser.brand_ids.includes(effectiveBrandId)) {
return { success: false, error: "Not authorized to send this brand's campaigns" };
}
+7 -2
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
import type { AudienceRules } from "./campaigns";
@@ -33,7 +34,11 @@ export async function getCommunicationTemplates(brandId?: string): Promise<{ suc
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, error: "Not authenticated" };
const effectiveBrandId = brandId ?? adminUser.brand_id ?? null;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, error: "Brand access required" };
}
const effectiveBrandId = activeBrandId;
// Brand scoping: brand_admin can only see their own brand's templates
if (adminUser.role === "brand_admin" && effectiveBrandId && effectiveBrandId !== adminUser.brand_id) {
@@ -112,7 +117,7 @@ export async function getTemplateById(templateId: string): Promise<Template | nu
{
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({ p_brand_id: adminUser.brand_id ?? null }),
body: JSON.stringify({ p_brand_id: (await getActiveBrandId(adminUser)) ?? null }),
}
);
+3 -2
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
@@ -66,7 +67,7 @@ export async function getDashboardStats(): Promise<DashboardStats> {
const adminUser = await getAdminUser();
if (!adminUser) throw new Error("Not authenticated");
const brandId = adminUser.brand_id ?? null;
const brandId = await getActiveBrandId(adminUser);
// Get today's date range
const today = new Date();
@@ -202,7 +203,7 @@ export async function getDashboardSummary(): Promise<DashboardSummary> {
const adminUser = await getAdminUser();
if (!adminUser) throw new Error("Not authenticated");
const brandId = adminUser.brand_id ?? null;
const brandId = await getActiveBrandId(adminUser);
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
+13 -3
View File
@@ -2,6 +2,7 @@
import { revalidateTag } from "next/cache";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
export type LocationInput = {
@@ -48,7 +49,11 @@ export async function createLocation(
if (!adminUser.can_manage_stops) {
return { success: false, error: "Not authorized to manage locations" };
}
const effectiveBrandId = brandId || adminUser.brand_id;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, error: "Brand access required" };
}
const effectiveBrandId = activeBrandId;
if (!effectiveBrandId) return { success: false, error: "No brand selected" };
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
@@ -96,7 +101,11 @@ export async function createLocationsBatch(
if (!adminUser.can_manage_stops) {
return { success: false, created: 0, error: "Not authorized" };
}
const effectiveBrandId = brandId || adminUser.brand_id;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, created: 0, error: "Brand access required" };
}
const effectiveBrandId = activeBrandId;
if (!effectiveBrandId) return { success: false, created: 0, error: "No brand selected" };
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
@@ -206,7 +215,8 @@ export async function adminListLocations(
// Application-layer brand scoping: platform_admin (brand_id: null) gets all
// brands; everyone else gets only their own brand.
const effectiveBrandId = brandId || adminUser.brand_id;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
const effectiveBrandId = activeBrandId;
const res = await fetch(
`${supabaseUrl}/rest/v1/rpc/admin_list_locations`,
+6 -1
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
import { randomUUID } from "crypto";
@@ -41,7 +42,11 @@ export async function createAdminOrder(
}
// Brand scoping
const effectiveBrandId = brandId ?? adminUser.brand_id ?? null;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, error: "Brand access required" };
}
const effectiveBrandId = activeBrandId;
if (adminUser.role === "brand_admin" && adminUser.brand_id && effectiveBrandId !== adminUser.brand_id) {
return { success: false, error: "Not authorized for this brand" };
}
+4 -4
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { assertBrandAccess } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
export type PaymentProvider = "stripe" | "square" | "manual";
@@ -65,10 +66,9 @@ export async function savePaymentSettings(params: {
return { success: false, error: "Not authorized" };
}
if (
adminUser.role === "brand_admin" &&
adminUser.brand_id !== params.brandId
) {
try {
assertBrandAccess(adminUser, params.brandId);
} catch {
return { success: false, error: "Not authorized for this brand" };
}
+6 -1
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
export async function deleteProduct(
@@ -16,7 +17,11 @@ export async function deleteProduct(
return { success: false, error: "Not authorized to manage products" };
}
const effectiveBrandId = brandId ?? adminUser.brand_id ?? null;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, error: "Brand access required" };
}
const effectiveBrandId = activeBrandId;
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
+65 -8
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId, assertBrandAccess } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL!;
@@ -153,7 +154,14 @@ export interface FieldYieldSummary {
export async function getRouteTraceLots(brandId: string, status?: string) {
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, error: "Unauthorized" };
const effectiveBrandId = brandId ?? adminUser.brand_id ?? undefined;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, error: "Brand access required" };
}
if (activeBrandId) {
try { assertBrandAccess(adminUser, activeBrandId); } catch { return { success: false, error: "Brand access denied" }; }
}
const effectiveBrandId = activeBrandId ?? undefined;
if (!effectiveBrandId) return { success: false, error: "No brand" };
try {
@@ -235,7 +243,14 @@ export async function createHarvestLot(
) {
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, error: "Unauthorized" };
const effectiveBrandId = brandId ?? adminUser.brand_id ?? undefined;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, error: "Brand access required" };
}
if (activeBrandId) {
try { assertBrandAccess(adminUser, activeBrandId); } catch { return { success: false, error: "Brand access denied" }; }
}
const effectiveBrandId = activeBrandId ?? undefined;
if (!effectiveBrandId) return { success: false, error: "No brand" };
try {
@@ -298,7 +313,14 @@ export async function updateHarvestLotStatus(
export async function getRouteTraceStats(brandId: string) {
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, error: "Unauthorized" };
const effectiveBrandId = brandId ?? adminUser.brand_id ?? undefined;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, error: "Brand access required" };
}
if (activeBrandId) {
try { assertBrandAccess(adminUser, activeBrandId); } catch { return { success: false, error: "Brand access denied" }; }
}
const effectiveBrandId = activeBrandId ?? undefined;
if (!effectiveBrandId) return { success: false, error: "No brand" };
try {
@@ -318,7 +340,14 @@ export async function getRouteTraceStats(brandId: string) {
export async function searchHarvestLots(brandId: string, query: string) {
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, error: "Unauthorized" };
const effectiveBrandId = brandId ?? adminUser.brand_id ?? undefined;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, error: "Brand access required" };
}
if (activeBrandId) {
try { assertBrandAccess(adminUser, activeBrandId); } catch { return { success: false, error: "Brand access denied" }; }
}
const effectiveBrandId = activeBrandId ?? undefined;
if (!effectiveBrandId) return { success: false, error: "No brand" };
try {
@@ -347,7 +376,14 @@ export async function getTraceChain(lotId: string) {
export async function getHarvestLotsReadyToHaul(brandId: string) {
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, error: "Unauthorized" };
const effectiveBrandId = brandId ?? adminUser.brand_id ?? undefined;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, error: "Brand access required" };
}
if (activeBrandId) {
try { assertBrandAccess(adminUser, activeBrandId); } catch { return { success: false, error: "Brand access denied" }; }
}
const effectiveBrandId = activeBrandId ?? undefined;
if (!effectiveBrandId) return { success: false, error: "No brand" };
try {
@@ -364,7 +400,14 @@ export async function getHarvestLotsReadyToHaul(brandId: string) {
export async function getFieldYieldSummary(brandId: string) {
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, error: "Unauthorized" };
const effectiveBrandId = brandId ?? adminUser.brand_id ?? undefined;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, error: "Brand access required" };
}
if (activeBrandId) {
try { assertBrandAccess(adminUser, activeBrandId); } catch { return { success: false, error: "Brand access denied" }; }
}
const effectiveBrandId = activeBrandId ?? undefined;
if (!effectiveBrandId) return { success: false, error: "No brand" };
try {
@@ -405,7 +448,14 @@ export interface InventoryByCrop {
export async function getInventoryByCrop(brandId: string): Promise<{ success: true; inventory: InventoryByCrop[] } | { success: false; error: string }> {
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, error: "Unauthorized" };
const effectiveBrandId = brandId ?? adminUser.brand_id ?? undefined;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, error: "Brand access required" };
}
if (activeBrandId) {
try { assertBrandAccess(adminUser, activeBrandId); } catch { return { success: false, error: "Brand access denied" }; }
}
const effectiveBrandId = activeBrandId ?? undefined;
if (!effectiveBrandId) return { success: false, error: "No brand" };
try {
@@ -451,7 +501,14 @@ export async function getRecentLotEvents(
): Promise<{ success: true; events: RecentLotEvent[] } | { success: false; error: string }> {
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, error: "Unauthorized" };
const effectiveBrandId = brandId ?? adminUser.brand_id ?? undefined;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, error: "Brand access required" };
}
if (activeBrandId) {
try { assertBrandAccess(adminUser, activeBrandId); } catch { return { success: false, error: "Brand access denied" }; }
}
const effectiveBrandId = activeBrandId ?? undefined;
if (!effectiveBrandId) return { success: false, error: "No brand" };
try {
+47
View File
@@ -0,0 +1,47 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import {
setActiveBrandCookie,
clearActiveBrandCookie,
} from "@/lib/brand-scope";
/**
* Set the persistent "active brand" for the current admin user.
*
* - `brandId === null`: "All brands" — only allowed for platform_admin.
* Clears the cookie (cookie absence = no specific brand pinned).
* - `brandId` string: sets the cookie, after validating the admin has access.
*
* The active brand is the default the UI uses for pages that don't receive
* an explicit `brandId` from the URL. The cookie is the source of truth —
* the URL is only for deep-linking.
*/
export async function setActiveBrand(
brandId: string | null
): Promise<{ success: boolean; error?: string }> {
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, error: "Not authenticated" };
// null = "All brands" (platform_admin only)
if (brandId === null) {
if (adminUser.role !== "platform_admin") {
return {
success: false,
error: "Only platform admins can select 'All brands'",
};
}
await clearActiveBrandCookie();
return { success: true };
}
if (
adminUser.role !== "platform_admin" &&
!adminUser.brand_ids.includes(brandId)
) {
return { success: false, error: "No access to that brand" };
}
await setActiveBrandCookie(brandId);
return { success: true };
}
+3 -2
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
export type UpdateShippingStatusResult =
@@ -28,7 +29,7 @@ export async function updateShippingStatus(
p_order_id: orderId,
p_shipping_status: status,
p_tracking_number: trackingNumber ?? null,
p_brand_id: adminUser.brand_id ?? null,
p_brand_id: await getActiveBrandId(adminUser),
}),
}
);
@@ -79,7 +80,7 @@ export async function getShippingOrders(): Promise<GetShippingOrdersResult> {
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({
p_brand_id: adminUser.brand_id ?? null,
p_brand_id: await getActiveBrandId(adminUser),
}),
}
);
+5
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { assertBrandAccess } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
import type { FedExServiceType } from "./fedex-rates";
@@ -156,6 +157,10 @@ export async function createFedExShipment(
const order = orders[0];
if (!order) return { success: false, error: "Order not found" };
// The order's brand is the source of truth. Validate the admin has access.
if (order.brand_id) {
try { assertBrandAccess(adminUser, order.brand_id); } catch { return { success: false, error: "Brand access denied" }; }
}
const effectiveBrandId = order.brand_id ?? adminUser.brand_id ?? null;
// Get FedEx settings
+5
View File
@@ -11,6 +11,7 @@
*/
import { getAdminUser } from "@/lib/admin-permissions";
import { assertBrandAccess } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
// ── Types ────────────────────────────────────────────────────────────────────
@@ -177,6 +178,10 @@ export async function getFedExRates(
const order = orders[0];
if (!order) return { success: false, error: "Order not found" };
// The order's brand is the source of truth. Validate the admin has access.
if (order.brand_id) {
try { assertBrandAccess(adminUser, order.brand_id); } catch { return { success: false, error: "Brand access denied" }; }
}
const effectiveBrandId = order.brand_id ?? adminUser.brand_id ?? null;
// Fetch shipping settings for this brand
+7 -2
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { assertBrandAccess } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
export type SyncLogEntry = {
@@ -29,7 +30,9 @@ export async function syncSquareNow(
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, synced: 0, errors: ["Not authenticated"] };
if (!adminUser.can_manage_orders) return { success: false, synced: 0, errors: ["Not authorized"] };
if (adminUser.role === "brand_admin" && adminUser.brand_id !== brandId) {
try {
assertBrandAccess(adminUser, brandId);
} catch {
return { success: false, synced: 0, errors: ["Not authorized"] };
}
@@ -61,7 +64,9 @@ export async function getSyncLog(brandId: string): Promise<{
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, logs: [] };
if (!adminUser.can_manage_orders) return { success: false, logs: [] };
if (adminUser.role === "brand_admin" && adminUser.brand_id !== brandId) {
try {
assertBrandAccess(adminUser, brandId);
} catch {
return { success: false, logs: [] };
}
+6 -1
View File
@@ -2,6 +2,7 @@
import { revalidateTag } from "next/cache";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
export type StopImportRow = {
@@ -25,7 +26,11 @@ export async function createStopsBatch(
return { success: false, created: 0, error: "Not authorized to manage stops" };
}
const effectiveBrandId = brandId || adminUser.brand_id;
const activeBrandId = await getActiveBrandId(adminUser, brandId);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return { success: false, created: 0, error: "Brand access required" };
}
const effectiveBrandId = activeBrandId;
if (!effectiveBrandId) {
return { success: false, created: 0, error: "No brand selected" };
}
+9 -8
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
type Irrigator = {
@@ -94,7 +95,7 @@ export async function updateWaterHeadgate(
p_name: name,
p_active: active,
p_unit: unit ?? null,
p_brand_id: adminUser.brand_id ?? null,
p_brand_id: (await getActiveBrandId(adminUser)) ?? null,
p_high_threshold: highThreshold ?? null,
p_low_threshold: lowThreshold ?? null,
}),
@@ -186,7 +187,7 @@ export async function updateWaterIrrigator(
p_active: active,
p_lang: lang,
p_role: role,
p_brand_id: adminUser.brand_id ?? null,
p_brand_id: (await getActiveBrandId(adminUser)) ?? null,
}),
}
);
@@ -215,7 +216,7 @@ export async function resetWaterIrrigatorPin(
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({
p_user_id: irrigatorId,
p_brand_id: adminUser.brand_id ?? null,
p_brand_id: (await getActiveBrandId(adminUser)) ?? null,
}),
}
);
@@ -242,7 +243,7 @@ export async function deleteWaterUser(userId: string): Promise<{ success: boolea
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({
p_user_id: userId,
p_brand_id: adminUser.brand_id ?? null,
p_brand_id: (await getActiveBrandId(adminUser)) ?? null,
}),
}
);
@@ -269,7 +270,7 @@ export async function deleteWaterHeadgate(headgateId: string): Promise<{ success
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({
p_headgate_id: headgateId,
p_brand_id: adminUser.brand_id ?? null,
p_brand_id: (await getActiveBrandId(adminUser)) ?? null,
}),
}
);
@@ -356,7 +357,7 @@ export async function regenerateHeadgateToken(headgateId: string): Promise<{ suc
{
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({ p_headgate_id: headgateId, p_brand_id: adminUser.brand_id ?? null }),
body: JSON.stringify({ p_headgate_id: headgateId, p_brand_id: (await getActiveBrandId(adminUser)) ?? null }),
}
);
@@ -392,7 +393,7 @@ export async function updateWaterEntry(
p_measurement: measurement,
p_notes: notes,
p_unit: unit ?? null,
p_brand_id: adminUser.brand_id ?? null,
p_brand_id: (await getActiveBrandId(adminUser)) ?? null,
}),
}
);
@@ -421,7 +422,7 @@ export async function deleteWaterEntry(
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({
p_entry_id: entryId,
p_brand_id: adminUser.brand_id ?? null,
p_brand_id: (await getActiveBrandId(adminUser)) ?? null,
}),
}
);
+4 -1
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { assertBrandAccess } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
export async function registerWholesaleCustomer(params: {
@@ -81,7 +82,9 @@ export async function approveWholesaleRegistration(
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, error: "Not authenticated" };
if (!adminUser.can_manage_orders) return { success: false, error: "Not authorized" };
if (adminUser.role !== "platform_admin" && adminUser.brand_id !== brandId) {
try {
assertBrandAccess(adminUser, brandId);
} catch {
return { success: false, error: "Not authorized to operate on this brand" };
}
+33 -27
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
export type WholesaleOrder = {
@@ -129,15 +130,16 @@ export type WholesaleDashboardStats = {
* platform_admin → null (means "all brands" — passes to RPC unchanged)
* brand_admin → their own brand_id only; rejects attempts to operate on other brands
* store_employee → their own brand_id
* multi_brand_admin → active brand from cookie/URL/legacy, must be in brand_ids
* unauthenticated → null (actions should already bail out earlier)
*
* This prevents brand_admin from seeing or modifying another brand's data
* even if they manually pass a different brandId to the action.
*/
function resolveBrandId(
async function resolveBrandId(
adminUser: Awaited<ReturnType<typeof getAdminUser>>,
requestedBrandId?: string
): string | null {
): Promise<string | null> {
if (!adminUser) return null;
if (adminUser.role === "platform_admin") {
@@ -145,15 +147,15 @@ function resolveBrandId(
return null;
}
// brand_admin and store_employee are scoped to their own brand
const userBrand = adminUser.brand_id ?? null;
// For non-platform-admin: resolve the active brand (validates against brand_ids)
const activeBrandId = await getActiveBrandId(adminUser, requestedBrandId);
if (requestedBrandId && requestedBrandId !== userBrand) {
if (requestedBrandId && activeBrandId !== requestedBrandId) {
// Brand admin trying to operate on another brand's data — block it
return null; // caller should check and return unauthorized
}
return userBrand;
return activeBrandId;
}
/**
@@ -161,23 +163,24 @@ function resolveBrandId(
* if a brand_admin tries to operate outside their brand.
* Use for mutating actions (save, delete, fulfill) where cross-brand access must be blocked.
*/
function enforceBrandScope(
async function enforceBrandScope(
adminUser: Awaited<ReturnType<typeof getAdminUser>>,
requestedBrandId?: string
): { brandId: string | null; error?: string } {
): Promise<{ brandId: string | null; error?: string }> {
if (!adminUser) return { brandId: null, error: "Not authenticated" };
if (adminUser.role === "platform_admin") {
return { brandId: null }; // unrestricted
}
const userBrand = adminUser.brand_id ?? null;
// For non-platform-admin: resolve the active brand (validates against brand_ids)
const activeBrandId = await getActiveBrandId(adminUser, requestedBrandId);
if (requestedBrandId && requestedBrandId !== userBrand) {
if (requestedBrandId && activeBrandId !== requestedBrandId) {
return { brandId: null, error: "Not authorized to operate on this brand" };
}
return { brandId: userBrand };
return { brandId: activeBrandId };
}
// ── Orders ──────────────────────────────────────────────────────────────────
@@ -185,7 +188,7 @@ function enforceBrandScope(
export async function getWholesaleOrders(brandId?: string): Promise<WholesaleOrder[]> {
const adminUser = await getAdminUser();
if (!adminUser) return [];
const bid = resolveBrandId(adminUser, brandId);
const bid = await resolveBrandId(adminUser, brandId);
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
@@ -209,7 +212,7 @@ export async function getWholesaleOrders(brandId?: string): Promise<WholesaleOrd
export async function getWholesalePickupOrders(brandId?: string): Promise<WholesaleOrder[]> {
const adminUser = await getAdminUser();
if (!adminUser) return [];
const bid = resolveBrandId(adminUser, brandId);
const bid = await resolveBrandId(adminUser, brandId);
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
@@ -256,7 +259,7 @@ export async function markWholesaleOrderFulfilled(orderId: string, brandId?: str
if (!adminUser) return { success: false, error: "Not authenticated" };
if (!adminUser.can_manage_orders) return { success: false, error: "Not authorized" };
const { brandId: resolved, error } = enforceBrandScope(adminUser, brandId);
const { brandId: resolved, error } = await enforceBrandScope(adminUser, brandId);
if (error) return { success: false, error };
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
@@ -305,7 +308,7 @@ export async function updateWholesaleOrderStatus(
if (!adminUser) return { success: false, error: "Not authenticated" };
if (!adminUser.can_manage_orders) return { success: false, error: "Not authorized" };
const { error } = enforceBrandScope(adminUser, brandId);
const { error } = await enforceBrandScope(adminUser, brandId);
if (error) return { success: false, error };
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
@@ -332,7 +335,7 @@ export async function deleteWholesaleOrder(orderId: string, brandId?: string): P
if (!adminUser) return { success: false, error: "Not authenticated" };
if (!adminUser.can_manage_orders) return { success: false, error: "Not authorized" };
const { error } = enforceBrandScope(adminUser, brandId);
const { error } = await enforceBrandScope(adminUser, brandId);
if (error) return { success: false, error };
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
@@ -359,7 +362,7 @@ export async function deleteWholesaleCustomer(customerId: string, brandId?: stri
if (!adminUser) return { success: false, error: "Not authenticated" };
if (!adminUser.can_manage_orders) return { success: false, error: "Not authorized" };
const { error } = enforceBrandScope(adminUser, brandId);
const { error } = await enforceBrandScope(adminUser, brandId);
if (error) return { success: false, error };
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
@@ -388,7 +391,7 @@ export async function deleteWholesaleProduct(productId: string, brandId?: string
if (!adminUser) return { success: false, error: "Not authenticated" };
if (!adminUser.can_manage_products) return { success: false, error: "Not authorized" };
const { error } = enforceBrandScope(adminUser, brandId);
const { error } = await enforceBrandScope(adminUser, brandId);
if (error) return { success: false, error };
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
@@ -417,7 +420,7 @@ export async function deleteWholesaleProduct(productId: string, brandId?: string
export async function getWholesaleCustomers(brandId?: string): Promise<WholesaleCustomer[]> {
const adminUser = await getAdminUser();
if (!adminUser) return [];
const bid = resolveBrandId(adminUser, brandId);
const bid = await resolveBrandId(adminUser, brandId);
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
@@ -458,7 +461,7 @@ export async function saveWholesaleCustomer(params: {
if (!adminUser) return { success: false, error: "Not authenticated" };
if (!adminUser.can_manage_orders) return { success: false, error: "Not authorized" };
const { error } = enforceBrandScope(adminUser, params.brandId);
const { error } = await enforceBrandScope(adminUser, params.brandId);
if (error) return { success: false, error };
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
@@ -501,7 +504,7 @@ export async function saveWholesaleCustomer(params: {
export async function getWholesaleProducts(brandId?: string): Promise<WholesaleProduct[]> {
const adminUser = await getAdminUser();
if (!adminUser) return [];
const bid = resolveBrandId(adminUser, brandId);
const bid = await resolveBrandId(adminUser, brandId);
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
@@ -545,7 +548,7 @@ export async function saveWholesaleProduct(params: {
if (!adminUser) return { success: false, error: "Not authenticated" };
if (!adminUser.can_manage_products) return { success: false, error: "Not authorized" };
const { error } = enforceBrandScope(adminUser, params.brandId);
const { error } = await enforceBrandScope(adminUser, params.brandId);
if (error) return { success: false, error };
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
@@ -591,7 +594,10 @@ export async function saveWholesaleProduct(params: {
export async function getWholesaleSettings(brandId?: string): Promise<WholesaleSettings | null> {
const adminUser = await getAdminUser();
if (!adminUser) return null;
const bid = brandId ?? adminUser.brand_id ?? null;
const bid = await getActiveBrandId(adminUser, brandId);
if (!bid && adminUser.role !== "platform_admin") {
return null;
}
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
@@ -700,7 +706,7 @@ export async function recordWholesaleDeposit(
p_method: method,
p_reference: reference ?? null,
p_recorded_by: adminUser.user_id,
p_brand_id: adminUser.brand_id ?? null,
p_brand_id: await getActiveBrandId(adminUser),
}),
}
);
@@ -710,7 +716,7 @@ export async function recordWholesaleDeposit(
if (!data?.success) return { success: false, error: data?.error ?? "Failed to record deposit" };
// Fire webhook — fire-and-forget
enqueueWholesaleWebhookForDepositRecorded(orderId, amount, adminUser.brand_id ?? undefined).catch(() => {});
enqueueWholesaleWebhookForDepositRecorded(orderId, amount, (await getActiveBrandId(adminUser)) ?? undefined).catch(() => {});
return { success: true };
}
@@ -753,7 +759,7 @@ export async function bulkFulfillWholesaleOrders(
body: JSON.stringify({
p_order_ids: orderIds,
p_by: adminUser.user_id,
p_brand_id: adminUser.brand_id ?? null,
p_brand_id: await getActiveBrandId(adminUser),
}),
}
);
@@ -791,7 +797,7 @@ export async function bulkRecordWholesaleDeposit(
p_method: method,
p_reference: reference ?? null,
p_recorded_by: adminUser.user_id,
p_brand_id: adminUser.brand_id ?? null,
p_brand_id: await getActiveBrandId(adminUser),
}),
}
);
+17 -2
View File
@@ -1,6 +1,8 @@
import AdminSidebar from "@/components/admin/AdminSidebar";
import AdminAccessDenied from "@/components/admin/AdminAccessDenied";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { listBrandsForAdmin } from "@/actions/brands";
import { redirect } from "next/navigation";
import "@/styles/admin-design-system.css";
import { ToastProvider } from "@/components/admin/Toast";
@@ -57,12 +59,25 @@ export default async function AdminLayout({ children }: { children: React.ReactN
redirect("/change-password");
}
// Resolve the active brand (URL > cookie > legacy > first of brand_ids)
const activeBrandId = await getActiveBrandId(adminUser);
// Fetch accessible brands for the sidebar BrandSelector. We do this
// unconditionally — `listBrandsForAdmin` is cheap and the sidebar
// decides whether to show the dropdown.
const brands = await listBrandsForAdmin();
return (
<ToastProviderWrapper>
<AdminSidebar userRole={adminUser.role} />
<AdminSidebar
userRole={adminUser.role}
brandIds={adminUser.brand_ids}
activeBrandId={activeBrandId}
brands={brands}
/>
<div className="min-h-screen lg:pl-60 admin-section" style={{ backgroundColor: "var(--admin-bg)" }}>
{children}
</div>
</ToastProviderWrapper>
);
}
}
+13 -6
View File
@@ -1,5 +1,6 @@
import AdminOrdersPanel from "@/components/admin/AdminOrdersPanel";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { getAdminOrders } from "@/actions/orders";
import AdminAccessDenied from "@/components/admin/AdminAccessDenied";
import { PageHeader } from "@/components/admin/design-system";
@@ -17,13 +18,19 @@ export default async function AdminOrdersPage() {
redirect("/admin/pickup");
}
const activeBrandId = await getActiveBrandId(adminUser);
// Platform admin can browse all brands' orders; everyone else must have a brand
if (!activeBrandId && adminUser.role !== "platform_admin") {
return <AdminAccessDenied message="You don't have access to any brand." />;
}
const { orders, stops } = await getAdminOrders();
const brandStops = adminUser?.brand_id
? stops.filter((s) => s.brand_id === adminUser.brand_id)
const brandStops = activeBrandId
? stops.filter((s) => s.brand_id === activeBrandId)
: stops;
const brandOrders = adminUser?.brand_id
const brandOrders = activeBrandId
? orders.filter(
(o) =>
o.stops && brandStops.some((s) => s.id === o.stop_id)
@@ -41,8 +48,8 @@ export default async function AdminOrdersPage() {
.order("name")
.limit(200);
if (adminUser?.brand_id) {
prodQuery = prodQuery.eq("brand_id", adminUser.brand_id);
if (activeBrandId) {
prodQuery = prodQuery.eq("brand_id", activeBrandId);
}
const { data: prods } = await prodQuery;
@@ -80,7 +87,7 @@ export default async function AdminOrdersPage() {
initialOrders={brandOrders}
initialStops={brandStops}
initialProducts={brandProducts}
brandId={adminUser?.brand_id ?? null}
brandId={activeBrandId}
/>
</div>
</div>
+6 -6
View File
@@ -1,6 +1,7 @@
import Link from "next/link";
import { supabase } from "@/lib/supabase";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { isFeatureEnabled } from "@/lib/feature-flags";
import { getBillingOverview } from "@/actions/billing/billing-overview";
import DashboardClient from "@/components/admin/DashboardClient";
@@ -23,12 +24,11 @@ export default async function AdminPage() {
let limits = { max_users: 1, max_stops_monthly: 10, max_products: 25 };
let brandDisplayName = "Admin";
// For platform_admin in dev mode, adminUser.brand_id is null. To keep
// the dashboard's "Active Products" stat in sync with the billing page,
// we need to pick a brand and use the same getBillingOverview action
// the billing page does. Otherwise the dashboard falls back to default
// (0/0/0) usage values and contradicts the billing page's "Products 1/25".
let dashboardBrandId: string | null = adminUser?.brand_id ?? null;
// Resolve active brand via the canonical resolver (URL > cookie > legacy brand_id
// > first of brand_ids). For platform_admin in dev mode this is null, so we
// fall back to the first brand in the brands table to keep the dashboard's
// "Active Products" stat in sync with the billing page.
let dashboardBrandId: string | null = adminUser ? await getActiveBrandId(adminUser) : null;
if (!dashboardBrandId && adminUser?.role === "platform_admin") {
const { data: firstBrand } = await supabase
.from("brands")
+5 -3
View File
@@ -1,5 +1,6 @@
import { supabase } from "@/lib/supabase";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import AdminAccessDenied from "@/components/admin/AdminAccessDenied";
import ProductsClient from "@/components/admin/ProductsClient";
@@ -29,7 +30,8 @@ export default async function AdminProductsPage() {
);
}
const brandId = adminUser.brand_id;
const activeBrandId = await getActiveBrandId(adminUser);
const brandId = activeBrandId;
let query = supabase
.from("products")
@@ -48,8 +50,8 @@ export default async function AdminProductsPage() {
.is("deleted_at", null)
.order("name");
if (adminUser.brand_id) {
query = query.eq("brand_id", adminUser.brand_id);
if (brandId) {
query = query.eq("brand_id", brandId);
}
const { data: products, error } = await query;
+2 -1
View File
@@ -1,5 +1,6 @@
import { supabase } from "@/lib/supabase";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import AdminAccessDenied from "@/components/admin/AdminAccessDenied";
import ReportsDashboard from "@/components/admin/ReportsDashboard";
import { PageHeader } from "@/components/admin/design-system";
@@ -19,7 +20,7 @@ export default async function ReportsPage() {
const initialBrandId = isPlatformAdmin
? null
: adminUser.brand_id ?? null;
: await getActiveBrandId(adminUser);
return (
<main className="min-h-screen px-6 py-10" style={{ backgroundColor: "var(--admin-bg)" }}>
+6 -1
View File
@@ -1,5 +1,6 @@
import { supabase } from "@/lib/supabase";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { getBillingOverview } from "@/actions/billing/billing-overview";
import AdminAccessDenied from "@/components/admin/AdminAccessDenied";
import BillingClientPage from "./BillingClientPage";
@@ -13,7 +14,11 @@ export default async function BillingPage({ params }: Props) {
const adminUser = await getAdminUser();
if (!adminUser) return <AdminAccessDenied />;
const effectiveBrandId = brandIdParam ?? adminUser.brand_id ?? "";
const activeBrandId = await getActiveBrandId(adminUser, brandIdParam);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return <AdminAccessDenied message="You don't have access to that brand." />;
}
const effectiveBrandId = activeBrandId ?? "";
const isPlatformAdmin = adminUser.role === "platform_admin";
let resolvedBrandId = effectiveBrandId;
+6 -3
View File
@@ -4,6 +4,7 @@ import StopsLocationsTabs from "@/components/admin/StopsLocationsTabs";
import StatsStrip from "@/components/admin/StatsStrip";
import { supabase } from "@/lib/supabase";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { adminListLocations } from "@/actions/locations";
import AdminAccessDenied from "@/components/admin/AdminAccessDenied";
import { PageHeader } from "@/components/admin/design-system";
@@ -39,6 +40,8 @@ export default async function AdminStopsPage({ searchParams }: PageProps) {
// Always fetch stops + locations; the page is fast and a server component can
// hand both to the client. The Locations tab only needs the array — it does
// its own filtering in JS. Stops tab uses the existing client table.
const activeBrandId = await getActiveBrandId(adminUser);
const stopsQuery = supabase
.from("stops")
.select(`
@@ -49,13 +52,13 @@ export default async function AdminStopsPage({ searchParams }: PageProps) {
.is("deleted_at", null)
.order("date", { ascending: true });
if (adminUser?.brand_id) {
stopsQuery.eq("brand_id", adminUser.brand_id);
if (activeBrandId) {
stopsQuery.eq("brand_id", activeBrandId);
}
const [{ data: stops, error: stopsError }, locations] = await Promise.all([
stopsQuery,
adminListLocations(adminUser.brand_id ?? ""),
adminListLocations(activeBrandId ?? ""),
]);
if (stopsError) {
+6 -1
View File
@@ -1,6 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { supabase } from "@/lib/supabase";
import AdminAccessDenied from "@/components/admin/AdminAccessDenied";
import TaxDashboard from "@/components/admin/TaxDashboard";
@@ -15,7 +16,11 @@ export default async function TaxesPage({ params }: Props) {
const adminUser = await getAdminUser();
if (!adminUser) return <AdminAccessDenied />;
const effectiveBrandId = brandIdParam ?? adminUser.brand_id ?? "";
const activeBrandId = await getActiveBrandId(adminUser, brandIdParam);
if (!activeBrandId && adminUser.role !== "platform_admin") {
return <AdminAccessDenied message="You don't have access to that brand." />;
}
const effectiveBrandId = activeBrandId ?? "";
const isPlatformAdmin = adminUser.role === "platform_admin";
let resolvedBrandId = effectiveBrandId;
+4 -2
View File
@@ -1,5 +1,7 @@
import { redirect } from "next/navigation";
import { cookies } from "next/headers";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import WholesaleClient from "./WholesaleClient";
export default async function WholesalePage() {
@@ -11,10 +13,10 @@ export default async function WholesalePage() {
devSession === "store_employee";
if (!isDevMode) {
const { getAdminUser } = await import("@/lib/admin-permissions");
const adminUser = await getAdminUser();
if (!adminUser) redirect("/login");
return <WholesaleClient brandId={adminUser.brand_id ?? ""} />;
const activeBrandId = await getActiveBrandId(adminUser);
return <WholesaleClient brandId={activeBrandId ?? ""} />;
}
// Dev mode: platform_admin sees all brands, use first brand as default
+29 -1
View File
@@ -5,6 +5,7 @@ import Link from "next/link";
import { usePathname } from "next/navigation";
import { useRouter } from "next/navigation";
import { supabase } from "@/lib/supabase";
import BrandSelector from "./BrandSelector";
// Elegant warm sidebar design
// Colors: parchment 100 bg, soft linen text, powder petal accent
@@ -217,9 +218,12 @@ const ICON_MAP: Record<string, React.ReactNode> = {
type SidebarProps = {
userRole?: string | null;
brandIds?: string[];
activeBrandId?: string | null;
brands?: Array<{ id: string; name: string; slug: string; logo_url: string | null }>;
};
export default function AdminSidebar({ userRole }: SidebarProps) {
export default function AdminSidebar({ userRole, brandIds, activeBrandId, brands }: SidebarProps) {
const pathname = usePathname();
const router = useRouter();
const [mobileOpen, setMobileOpen] = useState(false);
@@ -230,9 +234,15 @@ export default function AdminSidebar({ userRole }: SidebarProps) {
const roleLabel = userRole === "platform_admin" ? "Platform Admin"
: userRole === "brand_admin" ? "Brand Admin"
: userRole === "multi_brand_admin" ? "Multi-Brand Manager"
: userRole === "store_employee" ? "Store Employee"
: null;
const isMultiBrandAdmin = userRole === "multi_brand_admin";
const showAllBrandsOption = userRole === "platform_admin";
const showBrandSelector =
brands && (showAllBrandsOption || (brandIds && brandIds.length >= 2));
const isActive = useCallback((href: string) => {
if (href === "/admin") return pathname === "/admin";
return pathname.startsWith(href);
@@ -394,6 +404,24 @@ export default function AdminSidebar({ userRole }: SidebarProps) {
</Link>
</div>
{/* Brand selector (multi-brand admins + platform_admin) */}
{showBrandSelector && (
<div className="px-4 py-3 border-b flex-shrink-0" style={{ borderColor: "rgba(208, 203, 180, 0.2)" }}>
<p
className="text-[10px] font-semibold uppercase tracking-widest mb-1.5 px-1"
style={{ color: "rgba(195, 195, 193, 0.6)" }}
>
Active Brand
</p>
<BrandSelector
brands={brands!}
activeBrandId={activeBrandId ?? null}
showAllBrandsOption={showAllBrandsOption}
isMultiBrandAdmin={isMultiBrandAdmin}
/>
</div>
)}
{/* Nav links with keyboard navigation */}
<nav className="flex-1 overflow-y-auto overflow-x-hidden px-3 py-4 scrollbar-thin">
<ul className="space-y-1" role="list">
+218
View File
@@ -0,0 +1,218 @@
"use client";
import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { setActiveBrand } from "@/actions/set-active-brand";
export type BrandSelectorItem = {
id: string;
name: string;
slug: string;
logo_url: string | null;
};
type BrandSelectorProps = {
brands: BrandSelectorItem[];
/** Currently-active brand id. `null` means "All brands" (platform_admin only). */
activeBrandId: string | null;
/** When true, shows the "All brands" pseudo-option at the top. */
showAllBrandsOption: boolean;
/** Whether the user has multi-brand access. Controls the "Multi-brand manager" badge. */
isMultiBrandAdmin: boolean;
};
/**
* Brand selector dropdown.
*
* Renders a compact pill showing the active brand (or "All brands" for
* platform_admin) and opens a list of accessible brands on click.
*
* On select: calls `setActiveBrand` server action then `router.refresh()`
* so all server components re-read the new cookie and reload their data.
* The URL is NOT changed — the cookie is the source of truth.
*/
export default function BrandSelector({
brands,
activeBrandId,
showAllBrandsOption,
isMultiBrandAdmin,
}: BrandSelectorProps) {
const router = useRouter();
const [open, setOpen] = useState(false);
const [pending, setPending] = useState(false);
const ref = useRef<HTMLDivElement>(null);
// Close on outside click
useEffect(() => {
function handleClick(e: MouseEvent) {
if (ref.current && !ref.current.contains(e.target as Node)) {
setOpen(false);
}
}
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
// Close on escape
useEffect(() => {
if (!open) return;
function handleKey(e: KeyboardEvent) {
if (e.key === "Escape") setOpen(false);
}
document.addEventListener("keydown", handleKey);
return () => document.removeEventListener("keydown", handleKey);
}, [open]);
// No brands + no "All brands" option = don't render
if (!showAllBrandsOption && brands.length === 0) return null;
if (!showAllBrandsOption && brands.length < 2) return null;
const activeBrand = brands.find((b) => b.id === activeBrandId);
const label =
showAllBrandsOption && !activeBrand
? "All brands"
: activeBrand?.name ?? "Select brand";
async function selectBrand(brandId: string | null) {
setOpen(false);
if (brandId === activeBrandId) return;
setPending(true);
try {
const res = await setActiveBrand(brandId);
if (res.success) {
router.refresh();
} else {
// Keep UI usable if the server rejected; log for debugging
console.error("setActiveBrand failed:", res.error);
}
} finally {
setPending(false);
}
}
return (
<div className="relative" ref={ref}>
<button
type="button"
onClick={() => setOpen((v) => !v)}
disabled={pending}
aria-haspopup="listbox"
aria-expanded={open}
className="w-full flex items-center gap-2 px-2.5 py-1.5 rounded-lg border transition-colors text-left disabled:opacity-60"
style={{
backgroundColor: "rgba(208, 203, 180, 0.1)",
borderColor: "rgba(208, 203, 180, 0.25)",
color: "var(--admin-sidebar-text)",
}}
>
<span
className="flex h-5 w-5 items-center justify-center rounded-md text-[10px] font-semibold flex-shrink-0"
style={{ backgroundColor: "var(--admin-accent)", color: "white" }}
aria-hidden="true"
>
{showAllBrandsOption && !activeBrand ? "*" : label.charAt(0).toUpperCase()}
</span>
<span className="flex-1 min-w-0 text-xs font-medium truncate">
{label}
</span>
{isMultiBrandAdmin && (
<span
className="text-[9px] font-medium px-1.5 py-0.5 rounded-md flex-shrink-0"
style={{
backgroundColor: "rgba(202, 117, 67, 0.18)",
color: "var(--admin-accent)",
}}
title="Manages multiple brands"
>
multi
</span>
)}
<svg
className={`w-3 h-3 flex-shrink-0 transition-transform ${open ? "rotate-180" : ""}`}
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
aria-hidden="true"
>
<path strokeLinecap="round" strokeLinejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
</svg>
</button>
{open && (
<div
role="listbox"
className="absolute top-full left-0 right-0 mt-1.5 rounded-xl border shadow-2xl z-50 overflow-hidden"
style={{
backgroundColor: "var(--admin-sidebar-bg)",
borderColor: "rgba(208, 203, 180, 0.25)",
}}
>
{showAllBrandsOption && (
<button
type="button"
role="option"
aria-selected={!activeBrand}
onClick={() => selectBrand(null)}
className="w-full flex items-center gap-2 px-3 py-2 text-xs text-left transition-colors hover:bg-white/5"
style={{
color: !activeBrand ? "var(--admin-accent)" : "var(--admin-sidebar-text)",
backgroundColor: !activeBrand ? "rgba(202, 117, 67, 0.10)" : "transparent",
}}
>
<span
className="flex h-5 w-5 items-center justify-center rounded-md text-[10px] font-semibold flex-shrink-0"
style={{ backgroundColor: "var(--admin-accent)", color: "white" }}
aria-hidden="true"
>
*
</span>
<span className="flex-1">All brands</span>
{!activeBrand && (
<span
className="w-1.5 h-1.5 rounded-full flex-shrink-0"
style={{ backgroundColor: "var(--admin-accent)" }}
aria-hidden="true"
/>
)}
</button>
)}
{brands.map((b) => {
const isActive = b.id === activeBrandId;
return (
<button
key={b.id}
type="button"
role="option"
aria-selected={isActive}
onClick={() => selectBrand(b.id)}
className="w-full flex items-center gap-2 px-3 py-2 text-xs text-left transition-colors hover:bg-white/5"
style={{
color: isActive ? "var(--admin-accent)" : "var(--admin-sidebar-text)",
backgroundColor: isActive ? "rgba(202, 117, 67, 0.10)" : "transparent",
}}
>
<span
className="flex h-5 w-5 items-center justify-center rounded-md text-[10px] font-semibold flex-shrink-0"
style={{ backgroundColor: "var(--admin-accent)", color: "white" }}
aria-hidden="true"
>
{b.name.charAt(0).toUpperCase()}
</span>
<span className="flex-1 truncate">{b.name}</span>
{isActive && (
<span
className="w-1.5 h-1.5 rounded-full flex-shrink-0"
style={{ backgroundColor: "var(--admin-accent)" }}
aria-hidden="true"
/>
)}
</button>
);
})}
</div>
)}
</div>
);
}
+12 -2
View File
@@ -1,9 +1,19 @@
// Shared AdminUser type — safe to import from both server and client components
//
// `brand_id` is the active brand (one of `brand_ids`, or null for platform_admin).
// `brand_ids` is the full list of brands the admin can act in.
// - platform_admin: `brand_id = null`, `brand_ids = []` (in dev) or all brands
// (resolved by `listBrandsForAdmin`).
// - multi_brand_admin: `brand_id` = selected/cookie brand, `brand_ids` = 2+.
// - brand_admin / store_employee / staff: `brand_id` = their single brand,
// `brand_ids = [that one]`.
export type AdminUser = {
id?: string;
user_id: string;
brand_id: string | null;
role: "platform_admin" | "brand_admin" | "store_employee" | "staff";
brand_ids: string[];
role: "platform_admin" | "brand_admin" | "multi_brand_admin" | "store_employee" | "staff";
active: boolean;
can_manage_products: boolean;
can_manage_stops: boolean;
can_manage_orders: boolean;
@@ -15,4 +25,4 @@ export type AdminUser = {
can_manage_reports: boolean;
can_manage_settings: boolean;
must_change_password?: boolean;
};
};
+87 -27
View File
@@ -1,24 +1,21 @@
import { cookies } from "next/headers";
import type { AdminUser } from "./admin-permissions-types";
export type { AdminUser } from "./admin-permissions-types";
export type AdminUser = {
id: string;
user_id: string;
brand_id: string | null;
role: string;
active: boolean;
can_manage_products: boolean;
can_manage_stops: boolean;
can_manage_orders: boolean;
can_manage_pickup: boolean;
can_manage_messages: boolean;
can_manage_refunds: boolean;
can_manage_users: boolean;
can_manage_water_log: boolean;
can_manage_reports: boolean;
can_manage_settings: boolean;
must_change_password: boolean;
};
/**
* Returns the current admin user, or `null` if not authenticated.
*
* Resolution order:
* 1. Mock data mode (NEXT_PUBLIC_USE_MOCK_DATA=true) → platform_admin dev.
* 2. `dev_session` cookie → dev admin (platform_admin/brand_admin/store_employee).
* 3. Real auth (rc_auth_uid or rc_uid cookie) → load admin_users + brand_ids.
*
* `brand_id` is the active brand; `brand_ids` is the full membership list.
* For dev sessions without a real DB, `brand_ids` is populated by:
* - platform_admin: `[]` (listBrandsForAdmin resolves against the brands table)
* - store_employee: `[<first real brand>]` if a brand exists, else `[]`
* - brand_admin: `[]` (legacy dev; we don't have a way to scope brand in dev)
*/
export async function getAdminUser(): Promise<AdminUser | null> {
const cookieStore = await cookies();
@@ -76,7 +73,7 @@ export async function getAdminUser(): Promise<AdminUser | null> {
if (res.ok) {
const inserted = await res.json().catch(() => null);
if (inserted && inserted.length > 0) {
return buildAdminUser(inserted[0] as Record<string, unknown>);
return buildAdminUser(inserted[0] as Record<string, unknown>, []);
}
}
} catch (e) {
@@ -88,11 +85,56 @@ export async function getAdminUser(): Promise<AdminUser | null> {
const admin = adminUsers[0] as Record<string, unknown>;
if (!admin.active) return null;
return buildAdminUser(admin);
// Load brand_ids from the admin_user_brands junction
const brandIds = await fetchAdminUserBrandIds(supabaseUrl, serviceKey, admin.id as string);
return buildAdminUser(admin, brandIds);
}
/**
* Load `brand_ids` from the admin_user_brands junction for the given admin row.
* Returns an empty array on any failure (e.g. before migration 207 is applied).
*/
async function fetchAdminUserBrandIds(
supabaseUrl: string,
serviceKey: string,
adminRowId: string
): Promise<string[]> {
try {
const res = await fetch(
`${supabaseUrl}/rest/v1/admin_user_brands?admin_user_id=eq.${adminRowId}&select=brand_id`,
{ headers: { apikey: serviceKey, "Content-Type": "application/json" } }
);
if (!res.ok) return [];
const data = await res.json().catch(() => []);
if (!Array.isArray(data)) return [];
return data
.map((row: Record<string, unknown>) => row.brand_id as string)
.filter((id): id is string => typeof id === "string");
} catch {
return [];
}
}
function buildDevAdmin(role: string): AdminUser {
const base = { id: "dev", user_id: "dev", brand_id: null, role, active: true, must_change_password: false };
// For dev sessions we don't have an admin_user_brands junction row to load.
// - platform_admin: `brand_ids = []` (listBrandsForAdmin resolves against brands).
// - store_employee: `brand_ids = []` (dev AdminAccessDenied is acceptable;
// this is the documented limitation — re-read spec section on getAdminUser
// step 1. We skip the spec's "fetch first real brand" complexity here in
// favour of keeping dev session cheap and DB-independent).
// - brand_admin: `brand_ids = []` (same rationale).
// `role` is narrowed to the strict union — we know the dev callers pass
// only valid values.
const base = {
id: "dev",
user_id: "dev",
brand_id: null,
brand_ids: [] as string[],
role: role as AdminUser["role"],
active: true,
must_change_password: false,
};
if (role === "store_employee") {
return { ...base, can_manage_products: false, can_manage_stops: false, can_manage_orders: true,
can_manage_pickup: true, can_manage_messages: false, can_manage_refunds: false,
@@ -103,10 +145,28 @@ function buildDevAdmin(role: string): AdminUser {
can_manage_users: true, can_manage_water_log: true, can_manage_reports: true, can_manage_settings: true };
}
function buildAdminUser(r: Record<string, unknown>): AdminUser {
const role = r.role as string;
const base = { id: r.id as string, user_id: r.user_id as string, brand_id: r.brand_id as string | null,
role, active: r.active as boolean, must_change_password: Boolean(r.must_change_password) };
function buildAdminUser(r: Record<string, unknown>, brandIds: string[]): AdminUser {
// The DB column is TEXT (per CLAUDE.md) so the runtime value is a string.
// We narrow it to the known union here. If the DB has an unknown role
// (e.g. a future role), the migration's CHECK constraint will reject it
// before it ever reaches this function.
const role = r.role as AdminUser["role"];
// `brand_id` is the *legacy* single-brand column — preserved here as-is.
// The canonical "active brand" is resolved by `getActiveBrandId` on each
// page/action, which considers URL params, the active_brand_id cookie,
// and this legacy fallback. Setting `brand_id` here to a sensible default
// (legacy → first of brand_ids) keeps the AdminUser shape useful even
// for callers that haven't migrated to `getActiveBrandId` yet.
const legacyBrandId = (r.brand_id as string | null) ?? null;
const base = {
id: r.id as string,
user_id: r.user_id as string,
brand_id: legacyBrandId ?? brandIds[0] ?? null,
brand_ids: brandIds,
role,
active: r.active as boolean,
must_change_password: Boolean(r.must_change_password),
};
if (role === "platform_admin") {
return { ...base, can_manage_products: true, can_manage_stops: true, can_manage_orders: true,
can_manage_pickup: true, can_manage_messages: true, can_manage_refunds: true,
@@ -122,4 +182,4 @@ function buildAdminUser(r: Record<string, unknown>): AdminUser {
can_manage_messages: Boolean(r.can_manage_messages), can_manage_refunds: Boolean(r.can_manage_refunds),
can_manage_users: Boolean(r.can_manage_users), can_manage_water_log: Boolean(r.can_manage_water_log),
can_manage_reports: Boolean(r.can_manage_reports), can_manage_settings: Boolean(r.can_manage_settings) };
}
}
+90
View File
@@ -0,0 +1,90 @@
/**
* Brand-scope helpers for multi-brand admin support.
*
* Resolution order (documented in
* docs/superpowers/specs/2026-06-04-multi-brand-admin-design.md):
* 1. URL/explicit `requested` brand id (highest priority)
* 2. `active_brand_id` cookie (the persistent "what brand am I in right now")
* 3. `adminUser.brand_id` (legacy single-brand fallback)
* 4. First of `adminUser.brand_ids`
* 5. (platform_admin only) `null` → "all brands"
*
* For non-platform-admins, the returned brand is validated against
* `adminUser.brand_ids` — if `requested` or the cookie brand is not in the
* admin's accessible brands, the resolver falls through to a brand the admin
* does have access to (silent recovery).
*/
import "server-only";
import { cookies } from "next/headers";
import type { AdminUser } from "./admin-permissions-types";
export const ACTIVE_BRAND_COOKIE = "active_brand_id";
/**
* Resolve the active brand id for the given admin user.
*
* @param adminUser - The current admin user (must already be loaded).
* @param requested - Optional explicit brand id (e.g. from a URL param).
* When set and the admin has access, wins over cookie.
* @returns The brand id to act in, or `null` for platform_admin "all brands".
*/
export async function getActiveBrandId(
adminUser: AdminUser,
requested?: string | null
): Promise<string | null> {
const cookieStore = await cookies();
const cookieBrand = cookieStore.get(ACTIVE_BRAND_COOKIE)?.value ?? null;
// platform_admin: requested > cookie > null (all brands)
if (adminUser.role === "platform_admin") {
return requested ?? cookieBrand ?? null;
}
// Non-platform-admin: validate that requested/cookie brands are accessible
if (requested && adminUser.brand_ids.includes(requested)) {
return requested;
}
if (cookieBrand && adminUser.brand_ids.includes(cookieBrand)) {
return cookieBrand;
}
// Fall back to the legacy single brand, then first of the membership list
return adminUser.brand_id ?? adminUser.brand_ids[0] ?? null;
}
/**
* Set the persistent active-brand cookie. Should only be called after
* validating the admin has access (use `assertBrandAccess`).
*/
export async function setActiveBrandCookie(brandId: string): Promise<void> {
const cookieStore = await cookies();
cookieStore.set(ACTIVE_BRAND_COOKIE, brandId, {
httpOnly: true,
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 30, // 30 days
});
}
/**
* Clear the active-brand cookie. Used when platform_admin selects
* "All brands" (the cookie absence = "no specific brand pinned").
*/
export async function clearActiveBrandCookie(): Promise<void> {
const cookieStore = await cookies();
cookieStore.delete(ACTIVE_BRAND_COOKIE);
}
/**
* Throws if the admin user is not a platform_admin and does not have the
* given brand in their membership list. Use this for server actions and
* API routes that receive a brandId from URL/form/RPC return rather than
* `getActiveBrandId`.
*/
export function assertBrandAccess(adminUser: AdminUser, brandId: string): void {
if (adminUser.role === "platform_admin") return;
if (!adminUser.brand_ids.includes(brandId)) {
throw new Error("Brand access denied");
}
}