"use client"; import { ADMIN_REFUNDS_ENABLED } from "@/app/lib/features"; import { createContext, useContext, useEffect, useState, useCallback, useMemo, ReactNode } from "react"; import type { AdminBranchRef, AdminModule, AdminRole } from "@/app/lib/types"; // Ported from solvway-customer-portal's app/lib/MemberContext.tsx, extended // with hasRole/hasModule over the ACL tree (spec: "Access Is Gated By Role // And Module, As UX Only"). Session hydration is the single source of truth // for roles/aclMenu — the login response is minimal (see Task 4 interface // note) and the httpOnly cookie never carries them (spec: "The ACL tree is // not stored in the cookie"). interface AdminAuthCtx { name: string | null; roles: AdminRole[]; aclMenu: AdminModule | null; /** The signed-in admin's assigned branch (add-branch-counter-sale). Null when unassigned — * the Branch Counter POS page must show an empty state and suppress Place-sale. */ branch: AdminBranchRef | null; /** Countries the admin may see; null = all. */ countryScope: string[] | null; loading: boolean; refresh: () => Promise; /** Matches over roles[].name, e.g. hasRole("ROLE_ADMIN"). */ hasRole: (roleName: string) => boolean; /** Matches a flattened aclMenu node by its `name` OR its `url`. */ hasModule: (nameOrUrl: string) => boolean; /** Like hasModule but over the unfiltered tree: for actions the backend authorises that a feature switch must not hide, currently only Cancel shipment. */ hasGrantedModule: (nameOrUrl: string) => boolean; } const AdminAuthContext = createContext({ name: null, roles: [], aclMenu: null, branch: null, countryScope: null, loading: true, refresh: async () => {}, hasRole: () => false, hasModule: () => false, hasGrantedModule: () => false, }); /** Every node of the aclMenu tree — root plus all descendants, any type (R/M/A). */ export function flattenModules(root: AdminModule | null | undefined): AdminModule[] { if (!root) return []; const out: AdminModule[] = []; const walk = (node: AdminModule) => { out.push(node); for (const child of node.children ?? []) walk(child); }; walk(root); return out; } /** The aclMenu tree without the refund requests module while ADMIN_REFUNDS_ENABLED is off. */ function withoutRefunds(node: AdminModule): AdminModule { if (ADMIN_REFUNDS_ENABLED) return node; return { ...node, children: node.children?.filter((c) => c.name !== "BO_REFUND_REQUESTS").map(withoutRefunds) }; } export function AdminAuthProvider({ children }: { children: ReactNode }) { const [name, setName] = useState(null); const [roles, setRoles] = useState([]); const [aclMenu, setAclMenu] = useState(null); const [grantedMenu, setGrantedMenu] = useState(null); const [branch, setBranch] = useState(null); const [countryScope, setCountryScope] = useState(null); const [loading, setLoading] = useState(true); const load = useCallback(async () => { try { // Raw fetch (not a client wrapper that redirects on 401) — a legitimate // 401 on a public page (e.g. /login) must not throw or redirect-loop. const res = await fetch("/api/auth/session"); if (!res.ok) { setName(null); setRoles([]); setAclMenu(null); setGrantedMenu(null); setBranch(null); setCountryScope(null); return; } const data = (await res.json()) as { name: string; roles: AdminRole[]; aclMenu: AdminModule; branch?: AdminBranchRef | null; countryScope?: string[] | null; }; setName(data.name); setRoles(data.roles ?? []); setAclMenu(data.aclMenu ? withoutRefunds(data.aclMenu) : null); setGrantedMenu(data.aclMenu ?? null); setBranch(data.branch ?? null); setCountryScope(data.countryScope ?? null); } catch { setName(null); setRoles([]); setAclMenu(null); setGrantedMenu(null); setBranch(null); setCountryScope(null); } finally { setLoading(false); } }, []); useEffect(() => { // eslint-disable-next-line react-hooks/set-state-in-effect -- mount-time session fetch; setState runs in the async callback after the await, not synchronously. void load(); }, [load]); const hasRole = useCallback((roleName: string) => roles.some((r) => r.name === roleName), [roles]); const flatModules = useMemo(() => flattenModules(aclMenu), [aclMenu]); const hasModule = useCallback( (nameOrUrl: string) => flatModules.some((m) => m.name === nameOrUrl || m.url === nameOrUrl), [flatModules], ); const flatGranted = useMemo(() => flattenModules(grantedMenu), [grantedMenu]); const hasGrantedModule = useCallback( (nameOrUrl: string) => flatGranted.some((m) => m.name === nameOrUrl || m.url === nameOrUrl), [flatGranted], ); return ( {children} ); } export const useAdminAuth = () => useContext(AdminAuthContext);