Files
route-commerce/src/actions/square-sync-ui.ts
T
tyler 63842a9efc 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
2026-06-04 17:09:40 +00:00

89 lines
2.3 KiB
TypeScript

"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { assertBrandAccess } from "@/lib/brand-scope";
import { svcHeaders } from "@/lib/svc-headers";
export type SyncLogEntry = {
id: string;
brand_id: string;
event_type: string;
direction: string | null;
entity_type: string | null;
entity_id: string | null;
status: string;
message: string | null;
details: Record<string, unknown>;
created_at: string;
};
export type SyncResult = {
success: boolean;
synced: number;
errors: string[];
};
export async function syncSquareNow(
brandId: string,
type: "products" | "orders" | "all"
): Promise<SyncResult> {
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"] };
try {
assertBrandAccess(adminUser, brandId);
} catch {
return { success: false, synced: 0, errors: ["Not authorized"] };
}
const response = await fetch(`/api/square/sync`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ brandId, type }),
});
if (!response.ok) {
const errText = await response.text();
return { success: false, synced: 0, errors: [`HTTP ${response.status}: ${errText}`] };
}
const result = await response.json();
return {
success: result.success ?? true,
synced: result.synced ?? 0,
errors: result.errors ?? [],
};
}
export async function getSyncLog(brandId: string): Promise<{
success: boolean;
logs: SyncLogEntry[];
}> {
const adminUser = await getAdminUser();
if (!adminUser) return { success: false, logs: [] };
if (!adminUser.can_manage_orders) return { success: false, logs: [] };
try {
assertBrandAccess(adminUser, brandId);
} catch {
return { success: false, logs: [] };
}
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
const response = await fetch(
`${supabaseUrl}/rest/v1/square_sync_log?brand_id=eq.${brandId}&order=created_at.desc&limit=10`,
{
headers: svcHeaders(supabaseKey),
}
);
if (!response.ok) {
return { success: false, logs: [] };
}
const logs: SyncLogEntry[] = await response.json();
return { success: true, logs };
}