Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(settings): leave a person's hidden sections off the left menu (menu access, part 2) (#1703)

Cihana62b2c5636a7
diff --git a/web/src/app/[locale]/(dashboard)/layout.tsx b/web/src/app/[locale]/(dashboard)/layout.tsx
index 94a28b6e7..1e327b4f9 100644
--- a/web/src/app/[locale]/(dashboard)/layout.tsx
+++ b/web/src/app/[locale]/(dashboard)/layout.tsx
@@ -7,10 +7,12 @@ import { AuthProvider } from '@/components/providers/auth-provider';
import { PlanProvider } from '@/components/providers/plan-provider';
import { AiUsageProvider } from '@/components/providers/ai-usage-provider';
import { RoleProvider, type TeamRole } from '@/components/providers/role-provider';
+import { MenuAccessProvider } from '@/components/providers/menu-access-provider';
import { BrandLoader } from '@/components/providers/brand-loader';
import { BrandGuard } from '@/components/providers/brand-guard';
import { GettingStartedPageOpened } from '@/components/getting-started/page-opened';
import { getBrands } from '@/lib/actions/brand';
+import { menuOfProfile, readRoleHidden } from '@/lib/menu-access';
import { getPlan, isCloud, type PlanId } from '@/config/plans';
import { evaluateSubscriptionAccess } from '@/lib/billing/subscription-access';
import { SubscriptionExpiredNotice } from '@/components/billing/subscription-expired-notice';
@@ -28,7 +30,9 @@ export default async function DashboardLayout({ children }: { children: React.Re
const { data: profile } = await supabase
.from('profiles')
- .select('organization_id, onboarding_completed, role')
+ .select(
+ 'organization_id, onboarding_completed, role, work_areas, work_areas_asked_at, menu_shown, menu_hidden, can_manage_menus',
+ )
.eq('id', user.id)
.single();
@@ -38,14 +42,17 @@ export default async function DashboardLayout({ children }: { children: React.Re
const role = (profile.role ?? 'analyst') as TeamRole;
- const [{ data: org }, brands] = await Promise.all([
+ const [{ data: org }, brands, roleHidden] = await Promise.all([
supabase
.from('organizations')
.select('plan, subscription_status, plan_overrides')
.eq('id', profile.organization_id)
.single(),
getBrands(profile.organization_id),
+ // The sections the viewer's role leaves out (menu access); no read for admins.
+ readRoleHidden(supabase, profile.organization_id, role),
]);
+ const menu = menuOfProfile({ ...profile, role }, roleHidden);
// Cloud mode: gate access when the subscription isn't active/trialing.
// Admins (incl. the owner) are routed to the renew/payment flow; everyone
@@ -89,27 +96,29 @@ export default async function DashboardLayout({ children }: { children: React.Re
<GettingStartedPageOpened />
<PlanProvider planId={planId} allowedModelIds={allowedModelIds}>
<RoleProvider role={role}>
- <AiUsageProvider>
- <div className="flex h-screen overflow-hidden">
- {/* Desktop sidebar */}
- <div className="relative hidden md:flex md:flex-shrink-0">
- <SidebarErrorBoundary>
- <Sidebar />
- </SidebarErrorBoundary>
- </div>
+ <MenuAccessProvider hidden={menu.hidden}>
+ <AiUsageProvider>
+ <div className="flex h-screen overflow-hidden">
+ {/* Desktop sidebar */}
+ <div className="relative hidden md:flex md:flex-shrink-0">
+ <SidebarErrorBoundary>
+ <Sidebar />
+ </SidebarErrorBoundary>
+ </div>
- {/* Main area */}
- <div className="flex flex-1 flex-col overflow-hidden">
- <div className="flex h-16 items-center border-b bg-card px-4 gap-3 md:hidden">
- <MobileNav />
+ {/* Main area */}
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <div className="flex h-16 items-center border-b bg-card px-4 gap-3 md:hidden">
+ <MobileNav />
+ </div>
+ <main className="flex-1 overflow-y-auto bg-background p-6">
+ <BrandGuard>{children}</BrandGuard>
+ </main>
+ <TrackingJobHandoff />
</div>
- <main className="flex-1 overflow-y-auto bg-background p-6">
- <BrandGuard>{children}</BrandGuard>
- </main>
- <TrackingJobHandoff />
</div>
- </div>
- </AiUsageProvider>
+ </AiUsageProvider>
+ </MenuAccessProvider>
</RoleProvider>
</PlanProvider>
</>
diff --git a/web/src/components/layout/mobile-nav.test.tsx b/web/src/components/layout/mobile-nav.test.tsx
new file mode 100644
index 000000000..bf7c97de2
--- /dev/null
+++ b/web/src/components/layout/mobile-nav.test.tsx
@@ -0,0 +1,108 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../messages/en.json';
+
+vi.mock('next/image', () => ({
+ default: ({ alt }: { alt: string }) => <span data-image={alt} />,
+}));
+vi.mock('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'light' }) }));
+vi.mock('@/i18n/navigation', () => ({
+ usePathname: () => '/dashboard/action-center',
+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...rest}>
+ {children}
+ </a>
+ ),
+}));
+vi.mock('@/hooks/use-feature-gate', () => ({
+ useFeatureGate: () => ({ canUse: () => true, requiredPlanFor: () => null, isCloud: false }),
+}));
+vi.mock('@/hooks/use-agent-key-status', () => ({ useAgentKeyStatus: () => 'configured' }));
+vi.mock('@/components/layout/brand-switcher', () => ({ BrandSwitcher: () => null }));
+vi.mock('@/components/layout/user-profile-nav-item', () => ({ UserProfileNavItem: () => null }));
+vi.mock('@/components/layout/theme-toggle', () => ({ ThemeToggle: () => null }));
+vi.mock('@/config/dashboard', () => {
+ const Icon = () => <svg />;
+ return {
+ dashboardNav: [
+ {
+ title: 'Analytics',
+ items: [
+ { title: 'Action Center', href: '/dashboard/action-center', icon: Icon },
+ { title: 'Prompts', href: '/dashboard/prompts', icon: Icon },
+ { title: 'Mentions', href: '/dashboard/mentions', icon: Icon },
+ ],
+ },
+ ],
+ };
+});
+
+// The brand store keeps its state in localStorage, which this jsdom lacks.
+const stored = new Map<string, string>();
+vi.stubGlobal('localStorage', {
+ getItem: (key: string) => stored.get(key) ?? null,
+ setItem: (key: string, value: string) => void stored.set(key, value),
+ removeItem: (key: string) => void stored.delete(key),
+});
+
+const { MobileNav } = await import('./mobile-nav');
+const { MenuAccessProvider } = await import('@/components/providers/menu-access-provider');
+const { useBrandStore } = await import('@/stores/use-brand-store');
+
+/**
+ * The mobile menu leaves the viewer's hidden sections off, the active brand's
+ * Prompts link with the Prompts section.
+ */
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ useBrandStore.setState({ activeBrandId: 'brand-1', brands: [] });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ document.body.innerHTML = '';
+});
+
+async function open(hidden: string[]) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <MenuAccessProvider hidden={hidden}>
+ <MobileNav />
+ </MenuAccessProvider>
+ </NextIntlClientProvider>,
+ );
+ });
+ const toggle = document.querySelector('button[aria-label="Toggle navigation menu"]');
+ await act(async () => (toggle as HTMLButtonElement).click());
+}
+
+const link = (href: string) => document.querySelector(`a[href="${href}"]`);
+
+describe('MobileNav', () => {
+ it('shows every section, and the brand’s prompts, when nothing is hidden', async () => {
+ await open([]);
+ expect(link('/dashboard/prompts')).not.toBeNull();
+ expect(link('/dashboard/mentions')).not.toBeNull();
+ expect(link('/dashboard/brands/brand-1/prompts')).not.toBeNull();
+ });
+
+ it('leaves hidden sections off, the brand’s prompts with Prompts', async () => {
+ await open(['prompts', 'mentions']);
+ expect(link('/dashboard/action-center')).not.toBeNull();
+ expect(link('/dashboard/prompts')).toBeNull();
+ expect(link('/dashboard/mentions')).toBeNull();
+ expect(link('/dashboard/brands/brand-1/prompts')).toBeNull();
+ });
+});
diff --git a/web/src/components/layout/mobile-nav.tsx b/web/src/components/layout/mobile-nav.tsx
index 5d8111a7a..b9a403d4e 100644
--- a/web/src/components/layout/mobile-nav.tsx
+++ b/web/src/components/layout/mobile-nav.tsx
@@ -20,6 +20,7 @@ import { Badge } from '@/components/ui/badge';
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
import { UserProfileNavItem } from '@/components/layout/user-profile-nav-item';
import { ThemeToggle } from '@/components/layout/theme-toggle';
+import { useHiddenMenuSections } from '@/components/providers/menu-access-provider';
import { useBrandStore } from '@/stores/use-brand-store';
import { Crown, ExternalLink, Menu, MessageSquareHeart, MessageSquareText } from 'lucide-react';
import Image from 'next/image';
@@ -37,6 +38,7 @@ export function MobileNav() {
const activeBrandId = useBrandStore((s) => s.activeBrandId);
const activeBrand = useBrandStore((s) => s.brands.find((b) => b.id === s.activeBrandId) ?? null);
const brandPrefs = { shoppingModeEnabled: !!activeBrand?.shoppingModeEnabled };
+ const hiddenSections = useHiddenMenuSections();
const { resolvedTheme } = useTheme();
const [mounted, setMounted] = useState(false);
// Hydration guard — see sidebar.tsx for the rationale; the two
@@ -80,7 +82,8 @@ export function MobileNav() {
</div>
<div className="min-h-0 flex-1 overflow-y-auto">
<nav className="space-y-0.5 p-3">
- {activeBrandId && (
+ {/* The brand's prompts: the Prompts section, off the menu with it. */}
+ {activeBrandId && !hiddenSections.has('prompts') && (
<Link
href={`/dashboard/brands/${activeBrandId}/prompts`}
onClick={() => setOpen(false)}
@@ -100,7 +103,7 @@ export function MobileNav() {
)}
{dashboardNav.flatMap((group) =>
group.items.map((item) => {
- if (!shouldShowDashboardNavItem(item, brandPrefs)) {
+ if (!shouldShowDashboardNavItem(item, brandPrefs, hiddenSections)) {
return null;
}
diff --git a/web/src/components/layout/sidebar.test.tsx b/web/src/components/layout/sidebar.test.tsx
index 4816e6745..69ca40eed 100644
--- a/web/src/components/layout/sidebar.test.tsx
+++ b/web/src/components/layout/sidebar.test.tsx
@@ -17,7 +17,8 @@ vi.mock('@/i18n/navigation', () => ({
</a>
),
}));
-vi.mock('@/lib/actions/prompt', () => ({ getTrackedPromptCount: async () => 0 }));
+const getTrackedPromptCount = vi.hoisted(() => vi.fn(async () => 0));
+vi.mock('@/lib/actions/prompt', () => ({ getTrackedPromptCount }));
vi.mock('@/hooks/use-feature-gate', () => ({
useFeatureGate: () => ({ canUse: () => true, requiredPlanFor: () => null, isCloud: false }),
}));
@@ -47,6 +48,18 @@ vi.mock('@/config/dashboard', () => {
},
],
},
+ {
+ title: 'Analytics',
+ items: [
+ {
+ title: 'Prompts',
+ href: '/dashboard/prompts',
+ icon: Icon,
+ children: [{ title: 'Tracked Prompts', href: '/dashboard/prompts/tracked' }],
+ },
+ { title: 'Mentions', href: '/dashboard/mentions', icon: Icon },
+ ],
+ },
],
};
});
@@ -61,6 +74,8 @@ vi.stubGlobal('localStorage', {
const { Sidebar } = await import('./sidebar');
const { useSidebarStore } = await import('@/stores/use-sidebar-store');
+const { useBrandStore } = await import('@/stores/use-brand-store');
+const { MenuAccessProvider } = await import('@/components/providers/menu-access-provider');
/** The dashboard sidebar, expanded (it opens collapsed). */
@@ -75,6 +90,8 @@ beforeEach(() => {
Element.prototype.scrollIntoView = vi.fn();
// Expanded: a collapsed sidebar shows icons alone.
useSidebarStore.setState({ isCollapsed: false });
+ useBrandStore.setState({ activeBrandId: null });
+ getTrackedPromptCount.mockClear();
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
@@ -100,4 +117,68 @@ describe('Sidebar', () => {
const actions = container.querySelector('a[href="/dashboard/action-center"]');
expect(actions!.querySelector('[data-slot="badge"]')?.textContent).toBe('New');
});
+
+ it('leaves the viewer’s hidden sections off', async () => {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <MenuAccessProvider hidden={['content']}>
+ <Sidebar />
+ </MenuAccessProvider>
+ </NextIntlClientProvider>,
+ );
+ });
+ expect(container.querySelector('[data-submenu="/dashboard/content"]')).toBeNull();
+ expect(container.querySelector('a[href="/dashboard/action-center"]')).not.toBeNull();
+ });
+
+ it('drops a group whose sections are all off the menu, title and all', async () => {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <MenuAccessProvider hidden={['prompts', 'mentions']}>
+ <Sidebar />
+ </MenuAccessProvider>
+ </NextIntlClientProvider>,
+ );
+ });
+ expect(container.textContent).toContain('Execution');
+ expect(container.textContent).not.toContain('Analytics');
+ expect(container.querySelector('a[href="/dashboard/mentions"]')).toBeNull();
+ });
+
+ it('shows the whole menu without a menu to go by', async () => {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <Sidebar />
+ </NextIntlClientProvider>,
+ );
+ });
+ expect(container.querySelector('[data-submenu="/dashboard/content"]')).not.toBeNull();
+ expect(container.querySelector('a[href="/dashboard/mentions"]')).not.toBeNull();
+ });
+
+ it('reads the tracked prompts’ count only while Prompts is on the menu', async () => {
+ useBrandStore.setState({ activeBrandId: 'brand-1' });
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <MenuAccessProvider hidden={['prompts']}>
+ <Sidebar />
+ </MenuAccessProvider>
+ </NextIntlClientProvider>,
+ );
+ });
+ expect(getTrackedPromptCount).not.toHaveBeenCalled();
+
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <Sidebar />
+ </NextIntlClientProvider>,
+ );
+ });
+ expect(getTrackedPromptCount).toHaveBeenCalledWith('brand-1');
+ });
});
diff --git a/web/src/components/layout/sidebar.tsx b/web/src/components/layout/sidebar.tsx
index e0e4f2c9d..0caf13922 100644
--- a/web/src/components/layout/sidebar.tsx
+++ b/web/src/components/layout/sidebar.tsx
@@ -30,6 +30,7 @@ import { Separator } from '@/components/ui/separator';
import { BrandSwitcher } from '@/components/layout/brand-switcher';
import { UserProfileNavItem } from '@/components/layout/user-profile-nav-item';
import { ThemeToggle } from '@/components/layout/theme-toggle';
+import { useHiddenMenuSections } from '@/components/providers/menu-access-provider';
import {
ChevronDown,
ChevronsLeft,
@@ -151,6 +152,17 @@ export function Sidebar() {
// Sidebar hides the item entirely when this returns false — see #155/#170
// for why Shopping uses this on top of the existing plan-feature gate.
const brandPrefs = { shoppingModeEnabled: !!activeBrand?.shoppingModeEnabled };
+ // The items the viewer sees, and the groups that keep one: a group whose
+ // sections are all off their menu goes, title and all.
+ const hiddenSections = useHiddenMenuSections();
+ const visibleNav = dashboardNav
+ .map((group) => ({
+ ...group,
+ items: group.items.filter((item) =>
+ shouldShowDashboardNavItem(item, brandPrefs, hiddenSections),
+ ),
+ }))
+ .filter((group) => group.items.length > 0);
const { resolvedTheme } = useTheme();
const [mounted, setMounted] = useState(false);
// Hydration guard: SSR can't know the resolved theme, so we render the
@@ -202,9 +214,11 @@ export function Sidebar() {
}, [underMenu]);
// The count beside Tracked Prompts, refreshed on brand switch and on every
- // page change so adding or deleting prompts shows up.
+ // page change so adding or deleting prompts shows up. Not read while
+ // Prompts is off the viewer's menu.
+ const promptsOnMenu = !hiddenSections.has('prompts');
useEffect(() => {
- if (!activeBrandId) return;
+ if (!activeBrandId || !promptsOnMenu) return;
let cancelled = false;
getTrackedPromptCount(activeBrandId)
.then((n) => !cancelled && setTrackedCount(n))
@@ -212,7 +226,7 @@ export function Sidebar() {
return () => {
cancelled = true;
};
- }, [activeBrandId, pathname]);
+ }, [activeBrandId, pathname, promptsOnMenu]);
const setSubmenuOpen = (href: string, open: boolean) => {
setOpenMenus((prev) => ({ ...prev, [href]: open }));
@@ -333,7 +347,7 @@ export function Sidebar() {
}
}}
>
- {dashboardNav.map((group, i) => (
+ {visibleNav.map((group, i) => (
<div key={i} className="mb-4">
{group.title && !compact && (
<p className="mb-1 px-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">
@@ -348,10 +362,6 @@ export function Sidebar() {
{group.title && compact && i > 0 && <Separator className="my-2" />}
<nav className="space-y-0.5">
{group.items.map((item) => {
- if (!shouldShowDashboardNavItem(item, brandPrefs)) {
- return null;
- }
-
const isActive =
item.href === '/dashboard'
? pathname === '/dashboard'
diff --git a/web/src/components/providers/menu-access-provider.tsx b/web/src/components/providers/menu-access-provider.tsx
new file mode 100644
index 000000000..fdf732031
--- /dev/null
+++ b/web/src/components/providers/menu-access-provider.tsx
@@ -0,0 +1,25 @@
+'use client';
+
+import { createContext, useContext, useMemo, type ReactNode } from 'react';
+
+/**
+ * The left-menu sections the viewer's menu leaves out (menu access, 00374),
+ * read once by the dashboard layout. Empty by default, so a tree without the
+ * provider shows the whole menu.
+ */
+const MenuAccessContext = createContext<ReadonlySet<string>>(new Set());
+
+export function MenuAccessProvider({
+ hidden,
+ children,
+}: {
+ hidden: string[];
+ children: ReactNode;
+}) {
+ const value = useMemo(() => new Set(hidden), [hidden]);
+ return <MenuAccessContext.Provider value={value}>{children}</MenuAccessContext.Provider>;
+}
+
+export function useHiddenMenuSections(): ReadonlySet<string> {
+ return useContext(MenuAccessContext);
+}
diff --git a/web/src/lib/actions/menu-access.ts b/web/src/lib/actions/menu-access.ts
index ad06d8a1e..a3d602f39 100644
--- a/web/src/lib/actions/menu-access.ts
+++ b/web/src/lib/actions/menu-access.ts
@@ -7,9 +7,13 @@ import { supabaseAdmin } from '@/lib/supabase/admin';
import { readMemberEmails } from '@/lib/member-emails';
import {
WORK_AREA_IDS,
+ canManageMenus,
cleanMenuSections,
- hiddenMenuSections,
- isWorkAreaId,
+ menuOfProfile,
+ readRoleHidden,
+ workAreasOf,
+ type MenuProfile,
+ type MyMenu,
type WorkAreaId,
} from '@/lib/menu-access';
import type { UserRole } from '@/types';
@@ -29,15 +33,7 @@ const MENU_ROLES: MenuRole[] = ['manager', 'analyst', 'agency_partner'];
const userId = z.guid();
const sections = z.array(z.string().max(64)).max(64);
-export interface MyMenu {
- /** Sections off this person's left menu. */
- hidden: string[];
- workAreas: WorkAreaId[];
- /** Whether they answered (or skipped) "What do you work on?". */
- workAreasAsked: boolean;
- /** Admin, or a manager an admin let change menus. */
- canManageMenus: boolean;
-}
+export type { MyMenu } from '@/lib/menu-access';
export interface MenuMember {
userId: string;
@@ -60,15 +56,9 @@ export interface MenuAccessSettings {
viewerIsAdmin: boolean;
}
-interface Profile {
+interface Profile extends MenuProfile {
id: string;
- role: UserRole;
organization_id: string;
- work_areas: string[] | null;
- work_areas_asked_at: string | null;
- menu_shown: string[] | null;
- menu_hidden: string[] | null;
- can_manage_menus: boolean | null;
}
async function currentProfile(): Promise<Profile> {
@@ -89,20 +79,12 @@ async function currentProfile(): Promise<Profile> {
return profile as Profile;
}
-function canManage(profile: Pick<Profile, 'role' | 'can_manage_menus'>): boolean {
- return profile.role === 'admin' || (profile.role === 'manager' && !!profile.can_manage_menus);
-}
-
async function requireMenuManager(): Promise<Profile> {
const profile = await currentProfile();
- if (!canManage(profile)) throw new Error('Only admins and menu managers can change menus');
+ if (!canManageMenus(profile)) throw new Error('Only admins and menu managers can change menus');
return profile;
}
-function workAreasOf(values: string[] | null): WorkAreaId[] {
- return (values ?? []).filter(isWorkAreaId);
-}
-
/** The sections each role of the organization doesn't see. */
async function readRoles(organizationId: string): Promise<Record<MenuRole, string[]>> {
const { data, error } = await supabaseAdmin
@@ -122,33 +104,11 @@ async function readRoles(organizationId: string): Promise<Record<MenuRole, strin
/** The viewer's left menu: what it leaves out, and their work areas. */
export async function getMyMenu(): Promise<MyMenu> {
const profile = await currentProfile();
- const workAreas = workAreasOf(profile.work_areas);
- let roleHidden: string[] = [];
- if (profile.role !== 'admin') {
- // Their role's row, as RLS lets members of the organization read it.
- const supabase = await createClient();
- const { data } = await supabase
- .from('organization_menu_roles')
- .select('hidden_sections')
- .eq('organization_id', profile.organization_id)
- .eq('role', profile.role)
- .maybeSingle();
- roleHidden = data?.hidden_sections ?? [];
- }
-
- const hidden = hiddenMenuSections({
- role: profile.role,
- roleHidden,
- shown: profile.menu_shown ?? [],
- hidden: profile.menu_hidden ?? [],
- workAreas,
- });
- return {
- hidden: [...hidden],
- workAreas,
- workAreasAsked: profile.work_areas_asked_at !== null,
- canManageMenus: canManage(profile),
- };
+ const supabase = await createClient();
+ return menuOfProfile(
+ profile,
+ await readRoleHidden(supabase, profile.organization_id, profile.role),
+ );
}
/** Settings › Menu access: the role table and every member's menu. */
@@ -181,7 +141,7 @@ export async function getMenuAccessSettings(): Promise<MenuAccessSettings> {
workAreas: workAreasOf(row.work_areas as string[] | null),
shown: cleanMenuSections((row.menu_shown as string[] | null) ?? []),
hidden: cleanMenuSections((row.menu_hidden as string[] | null) ?? []),
- canManageMenus: canManage({
+ canManageMenus: canManageMenus({
role: row.role as UserRole,
can_manage_menus: row.can_manage_menus as boolean | null,
}),
diff --git a/web/src/lib/dashboard-navigation.test.ts b/web/src/lib/dashboard-navigation.test.ts
index 4934f5f25..9d8af4069 100644
--- a/web/src/lib/dashboard-navigation.test.ts
+++ b/web/src/lib/dashboard-navigation.test.ts
@@ -76,6 +76,17 @@ describe('shouldShowDashboardNavItem', () => {
it('shows Shopping when the active brand enables shopping mode', () => {
expect(shouldShowDashboardNavItem(shopping, { shoppingModeEnabled: true })).toBe(true);
});
+
+ it('hides a section off the viewer’s menu, by its route', () => {
+ const content = dashboardNav
+ .flatMap((group) => group.items)
+ .find((item) => item.href === '/dashboard/content')!;
+ const prefs = { shoppingModeEnabled: true };
+
+ expect(shouldShowDashboardNavItem(content, prefs, new Set(['content']))).toBe(false);
+ expect(shouldShowDashboardNavItem(content, prefs, new Set(['audit']))).toBe(true);
+ expect(shouldShowDashboardNavItem(shopping, prefs, new Set(['shopping']))).toBe(false);
+ });
});
describe('the Mentions item', () => {
diff --git a/web/src/lib/dashboard-navigation.ts b/web/src/lib/dashboard-navigation.ts
index a343d03e5..482c66695 100644
--- a/web/src/lib/dashboard-navigation.ts
+++ b/web/src/lib/dashboard-navigation.ts
@@ -1,4 +1,5 @@
import type { BrandPrefKey, NavChild, NavItem } from '@/config/dashboard';
+import { menuSectionOf } from '@/lib/menu-access';
type Translator = (key: string) => string;
@@ -75,10 +76,15 @@ export function childLinkHref(child: NavChild, pathname: string): string {
}
/** Brand preferences hide a navigation item entirely; they are intentionally
- * separate from plan gates, which render a visible but disabled item. */
+ * separate from plan gates, which render a visible but disabled item. So do
+ * the sections the viewer's menu leaves out (menu access): off the menu, the
+ * page still opens from a link. */
export function shouldShowDashboardNavItem(
item: NavItem,
brandPrefs: Record<BrandPrefKey, boolean>,
+ hiddenSections: ReadonlySet<string> = new Set(),
): boolean {
+ const section = menuSectionOf(item.href);
+ if (section && hiddenSections.has(section)) return false;
return !item.requiresBrandPref || brandPrefs[item.requiresBrandPref];
}
diff --git a/web/src/lib/menu-access.test.ts b/web/src/lib/menu-access.test.ts
index 13880fd6b..175ffadb8 100644
--- a/web/src/lib/menu-access.test.ts
+++ b/web/src/lib/menu-access.test.ts
@@ -1,6 +1,6 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
ALWAYS_ON_SECTION,
MENU_SECTIONS,
@@ -8,7 +8,9 @@ import {
WORK_AREA_IDS,
cleanMenuSections,
hiddenMenuSections,
+ menuOfProfile,
menuSectionOf,
+ readRoleHidden,
workAreaSections,
type MenuAccess,
} from './menu-access';
@@ -114,6 +116,67 @@ describe('workAreaSections', () => {
});
});
+describe('menuOfProfile', () => {
+ const profile = {
+ role: 'manager' as const,
+ work_areas: ['brand', 'retired'],
+ work_areas_asked_at: null,
+ menu_shown: ['prompts'],
+ menu_hidden: [],
+ can_manage_menus: true,
+ };
+
+ it('builds the menu from the profile and the role’s row', () => {
+ expect(menuOfProfile(profile, ['citations'])).toEqual({
+ hidden: ['content', 'audit', 'prompts', 'citations', 'shopping', 'traffic'],
+ workAreas: ['brand'],
+ workAreasAsked: false,
+ canManageMenus: true,
+ });
+ });
+
+ it('lets only managers and admins change menus', () => {
+ expect(menuOfProfile({ ...profile, role: 'analyst' }, []).canManageMenus).toBe(false);
+ expect(
+ menuOfProfile({ ...profile, role: 'admin', can_manage_menus: false }, []).canManageMenus,
+ ).toBe(true);
+ });
+});
+
+describe('readRoleHidden', () => {
+ function client(answer: { data: unknown; error: unknown }) {
+ const from = vi.fn(() => {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ maybeSingle: async () => answer,
+ };
+ return chain;
+ });
+ return { from };
+ }
+
+ it('reads the role’s row', async () => {
+ const supabase = client({ data: { hidden_sections: ['content'] }, error: null });
+ expect(await readRoleHidden(supabase as never, 'org', 'analyst')).toEqual(['content']);
+ expect(supabase.from).toHaveBeenCalledWith('organization_menu_roles');
+ });
+
+ it('reads nothing for admins', async () => {
+ const supabase = client({ data: null, error: null });
+ expect(await readRoleHidden(supabase as never, 'org', 'admin')).toEqual([]);
+ expect(supabase.from).not.toHaveBeenCalled();
+ });
+
+ it('shows the whole menu, and logs, when the row can’t be read', async () => {
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const supabase = client({ data: null, error: { message: 'down' } });
+ expect(await readRoleHidden(supabase as never, 'org', 'manager')).toEqual([]);
+ expect(log).toHaveBeenCalled();
+ log.mockRestore();
+ });
+});
+
describe('cleanMenuSections', () => {
it('keeps known sections once, in the menu’s order, without Action Center', () => {
expect(cleanMenuSections(['reports', 'nope', 'content', 'reports', ALWAYS_ON_SECTION])).toEqual(
diff --git a/web/src/lib/menu-access.ts b/web/src/lib/menu-access.ts
index f8459d08a..8052dd574 100644
--- a/web/src/lib/menu-access.ts
+++ b/web/src/lib/menu-access.ts
@@ -1,3 +1,4 @@
+import type { SupabaseClient } from '@supabase/supabase-js';
import { dashboardNav } from '@/config/dashboard';
import type { UserRole } from '@/types';
@@ -135,6 +136,77 @@ export function hiddenMenuSections(
return left;
}
+/** A person's menu, as the dashboard and Settings read it. */
+export interface MyMenu {
+ /** Sections off this person's left menu. */
+ hidden: string[];
+ workAreas: WorkAreaId[];
+ /** Whether they answered (or skipped) "What do you work on?". */
+ workAreasAsked: boolean;
+ /** Admin, or a manager an admin let change menus. */
+ canManageMenus: boolean;
+}
+
+/** The profile's menu columns (00374), read with the rest of the profile. */
+export interface MenuProfile {
+ role: UserRole;
+ work_areas: string[] | null;
+ work_areas_asked_at: string | null;
+ menu_shown: string[] | null;
+ menu_hidden: string[] | null;
+ can_manage_menus: boolean | null;
+}
+
+export function canManageMenus(profile: Pick<MenuProfile, 'role' | 'can_manage_menus'>): boolean {
+ return profile.role === 'admin' || (profile.role === 'manager' && !!profile.can_manage_menus);
+}
+
+export function workAreasOf(values: readonly string[] | null): WorkAreaId[] {
+ return (values ?? []).filter(isWorkAreaId);
+}
+
+/** A person's menu from their profile and their role's hidden sections. */
+export function menuOfProfile(profile: MenuProfile, roleHidden: readonly string[]): MyMenu {
+ const workAreas = workAreasOf(profile.work_areas);
+ const hidden = hiddenMenuSections({
+ role: profile.role,
+ roleHidden,
+ shown: profile.menu_shown ?? [],
+ hidden: profile.menu_hidden ?? [],
+ workAreas,
+ });
+ return {
+ hidden: [...hidden],
+ workAreas,
+ workAreasAsked: profile.work_areas_asked_at !== null,
+ canManageMenus: canManageMenus(profile),
+ };
+}
+
+/**
+ * The sections a role's row hides, as RLS lets members of the organization
+ * read it. None for admins, without a read; none, logged, when it can't be
+ * read, so the menu shows whole rather than not at all.
+ */
+export async function readRoleHidden(
+ supabase: Pick<SupabaseClient, 'from'>,
+ organizationId: string,
+ role: UserRole,
+): Promise<string[]> {
+ if (role === 'admin') return [];
+ const { data, error } = await supabase
+ .from('organization_menu_roles')
+ .select('hidden_sections')
+ .eq('organization_id', organizationId)
+ .eq('role', role)
+ .maybeSingle();
+ if (error) {
+ console.error('[menu-access] the role menu could not be read; showing the whole menu', error);
+ return [];
+ }
+ return (data?.hidden_sections as string[] | null) ?? [];
+}
+
/** Known sections only, once each, in the menu's order; never Action Center. */
export function cleanMenuSections(values: readonly string[]): string[] {
return MENU_SECTIONS.filter(