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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(settings): let people pick their work areas in Settings › Account (menu access, part 5) (#1706)
Cihana81574de9c66
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 43650c114..a1809a4c8 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -130,7 +130,9 @@"contentLibrary": "Library","contentPlan": "Plan","contentEditor": "Editor",- "toggleSubmenu": "Show or hide {label}"+ "toggleSubmenu": "Show or hide {label}",+ "menuOff": "{count, plural, one {# section} other {# sections}} off your menu.",+ "menuOffChange": "Change"},"actionCenter": {"dismissReason": {@@ -8041,6 +8043,13 @@"useRoleMenu": "Use {role}'s menu","savedAsYouChange": "Saved as you change it.","personSees": "{name} sees {section}",+ "workAreasTitle": "Your work areas",+ "workAreasDescription": "Pick what you work on or lead, and your menu shows only what you need. Pick none to see every section you can.",+ "workAreasDescriptionAdmin": "Pick what you work on or lead, and your menu shows only what you need. Pick none to see every section. Nobody else can take a section off an admin's menu.",+ "yourMenu": "Your menu",+ "hiddenByAdmin": "Hidden by your admin",+ "notInWorkAreas": "Not in your work areas",+ "adminTookOff": "{count, plural, one {Your admin took a section off your menu.} other {Your admin took # sections off your menu.}} Their pages still open from a link; ask an admin if you need one on your menu.","areas": {"leaders": {"title": "Founders & leaders",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.test.tsxindex f0f9a82d5..41af8fa21 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.test.tsx@@ -35,6 +35,7 @@ for (const [path, name] of [['@/components/settings/integrations-section', 'IntegrationsSection'],['@/components/settings/organization-section', 'OrganizationSection'],['@/components/settings/menu-access-section', 'MenuAccessSection'],+ ['@/components/settings/work-areas-card', 'WorkAreasCard'],]) {vi.doMock(path, () => ({ [name]: () => null }));}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsxindex 88ba366a7..a4b0fe52b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx@@ -21,6 +21,7 @@ import { NotificationsSection } from '@/components/settings/notifications-sectioimport { IntegrationsSection } from '@/components/settings/integrations-section';import { OrganizationSection } from '@/components/settings/organization-section';import { MenuAccessSection } from '@/components/settings/menu-access-section';+import { WorkAreasCard } from '@/components/settings/work-areas-card';import { useCanManageMenus } from '@/components/providers/menu-access-provider';import { Badge } from '@/components/ui/badge';import { updateAccountName } from '@/lib/actions/organization';@@ -183,6 +184,13 @@ export function SettingsView({ section }: { section: SettingsSection }) {</Card>)}+ {/* What the person works on or leads: it narrows their own menu. */}+ {active === 'account' && (+ <div className="mt-6">+ <WorkAreasCard />+ </div>+ )}+{/* Organization */}{active === 'organization' && <OrganizationSection />}diff --git a/web/src/components/layout/sidebar.test.tsx b/web/src/components/layout/sidebar.test.tsxindex aa239dd53..ac47b6b7b 100644--- a/web/src/components/layout/sidebar.test.tsx+++ b/web/src/components/layout/sidebar.test.tsx@@ -73,9 +73,9 @@ vi.stubGlobal('localStorage', {});const { Sidebar } = await import('./sidebar');+const { MenuAccessProvider } = await import('@/components/providers/menu-access-provider');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). */@@ -118,7 +118,7 @@ describe('Sidebar', () => {expect(actions!.querySelector('[data-slot="badge"]')?.textContent).toBe('New');});- it('leaves the viewer’s hidden sections off', async () => {+ it('leaves the viewer’s hidden sections off, and says where to change it', async () => {await act(async () => {root.render(<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">@@ -130,6 +130,10 @@ describe('Sidebar', () => {});expect(container.querySelector('[data-submenu="/dashboard/content"]')).toBeNull();expect(container.querySelector('a[href="/dashboard/action-center"]')).not.toBeNull();+ expect(container.textContent).toContain('1 section off your menu. Change');+ expect(container.querySelector('a[href="/dashboard/settings/account"]')?.textContent).toBe(+ 'Change',+ );});it('drops a group whose sections are all off the menu, title and all', async () => {@@ -157,6 +161,7 @@ describe('Sidebar', () => {});expect(container.querySelector('[data-submenu="/dashboard/content"]')).not.toBeNull();expect(container.querySelector('a[href="/dashboard/mentions"]')).not.toBeNull();+ expect(container.textContent).not.toContain('off your menu');});it('reads the tracked prompts’ count only while Prompts is on the menu', async () => {diff --git a/web/src/components/layout/sidebar.tsx b/web/src/components/layout/sidebar.tsxindex 0caf13922..a302fd43b 100644--- a/web/src/components/layout/sidebar.tsx+++ b/web/src/components/layout/sidebar.tsx@@ -543,6 +543,18 @@ export function Sidebar() {</ScrollArea><div className="space-y-1 p-2">+ {/* Menu access: how much is off the viewer's menu, and where they change it. */}+ {!compact && hiddenSections.size > 0 && (+ <p className="px-2 pb-1 text-[11px] text-muted-foreground">+ {t('menuOff', { count: hiddenSections.size })}{' '}+ <Link+ href="/dashboard/settings/account"+ className="underline underline-offset-2 hover:text-foreground"+ >+ {t('menuOffChange')}+ </Link>+ </p>+ )}<ahref={siteConfig.links.feedback}target="_blank"diff --git a/web/src/components/settings/work-areas-card.test.tsx b/web/src/components/settings/work-areas-card.test.tsxnew file mode 100644index 000000000..f07770a68--- /dev/null+++ b/web/src/components/settings/work-areas-card.test.tsx@@ -0,0 +1,124 @@+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';+import type { MyMenu } from '@/lib/actions/menu-access';++/**+ * Settings › Account › Your work areas: the person picks what they work on or+ * lead, saved as it changes; the menu it leaves them says why a section is off.+ */++const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));+vi.mock('sonner', () => ({ toast }));++let canAdmin = false;+vi.mock('@/hooks/use-user-role', () => ({+ useUserRole: () => ({ role: canAdmin ? 'admin' : 'analyst', canManage: canAdmin, canAdmin }),+}));++const actions = vi.hoisted(() => ({ getMyMenu: vi.fn(), setMyWorkAreas: vi.fn() }));+vi.mock('@/lib/actions/menu-access', () => actions);++const { WorkAreasCard, menuWithWorkAreas } = await import('./work-areas-card');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const menu = (over: Partial<MyMenu> = {}): MyMenu => ({+ hidden: [],+ hiddenByAdmin: [],+ workAreas: [],+ workAreasAsked: true,+ canManageMenus: false,+ ...over,+});++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ vi.clearAllMocks();+ canAdmin = false;+ actions.setMyWorkAreas.mockResolvedValue(undefined);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++async function render(start: MyMenu) {+ actions.getMyMenu.mockResolvedValue(start);+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <WorkAreasCard />+ </NextIntlClientProvider>,+ );+ });+}++const chip = (text: string) =>+ [...container.querySelectorAll('button')].find(+ (b) => b.textContent === text,+ ) as HTMLButtonElement;+const section = (id: string) => container.querySelector(`[data-section="${id}"]`) as HTMLElement;++describe('menuWithWorkAreas', () => {+ it('keeps what the admin takes off and narrows the rest to the areas', () => {+ const next = menuWithWorkAreas(menu({ hiddenByAdmin: ['mentions'] }), ['brand']);+ expect(next.workAreas).toEqual(['brand']);+ expect(next.hidden).toEqual(['content', 'audit', 'prompts', 'mentions', 'shopping', 'traffic']);+ expect(menuWithWorkAreas(next, []).hidden).toEqual(['mentions']);+ });+});++describe('WorkAreasCard', () => {+ it('shows the picked areas and why each section is off', async () => {+ await render(+ menu({+ workAreas: ['brand'],+ hiddenByAdmin: ['mentions'],+ hidden: ['content', 'audit', 'prompts', 'mentions', 'shopping', 'traffic'],+ }),+ );+ expect(chip('Brand & PR').getAttribute('aria-pressed')).toBe('true');+ expect(chip('Everything').getAttribute('aria-pressed')).toBe('false');+ expect(container.textContent).toContain('5 of 11 sections');+ expect(section('mentions').textContent).toContain('Hidden by your admin');+ expect(section('content').textContent).toContain('Not in your work areas');+ expect(section('insights').textContent).not.toContain('Not in');+ expect(container.textContent).toContain('Your admin took a section off your menu.');+ });++ it('saves the areas as they change, in the list’s order', async () => {+ await render(menu({ workAreas: ['brand'] }));+ await act(async () => chip('Founders & leaders').click());+ expect(actions.setMyWorkAreas).toHaveBeenCalledWith(['leaders', 'brand']);+ expect(chip('Founders & leaders').getAttribute('aria-pressed')).toBe('true');++ await act(async () => chip('Everything').click());+ expect(actions.setMyWorkAreas).toHaveBeenLastCalledWith([]);+ expect(container.textContent).toContain('11 of 11 sections');+ });++ it('reads the menu again when a save fails', async () => {+ actions.setMyWorkAreas.mockRejectedValueOnce(new Error('nope'));+ await render(menu());+ await act(async () => chip('Growth').click());+ expect(actions.getMyMenu).toHaveBeenCalledTimes(2);+ expect(chip('Growth').getAttribute('aria-pressed')).toBe('false');+ expect(toast.error).toHaveBeenCalledWith("Couldn't save the menu. Try again.");+ });++ it('tells admins nobody else narrows their menu', async () => {+ canAdmin = true;+ await render(menu());+ expect(container.textContent).toContain("Nobody else can take a section off an admin's menu.");+ });+});diff --git a/web/src/components/settings/work-areas-card.tsx b/web/src/components/settings/work-areas-card.tsxnew file mode 100644index 000000000..c430076fb--- /dev/null+++ b/web/src/components/settings/work-areas-card.tsx@@ -0,0 +1,191 @@+'use client';++import { useEffect, useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { Lock } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';+import { Skeleton } from '@/components/ui/skeleton';+import { useUserRole } from '@/hooks/use-user-role';+import { cn } from '@/lib/utils';+import { dashboardNav } from '@/config/dashboard';+import { getDashboardNavLabel } from '@/lib/dashboard-navigation';+import {+ MENU_SECTIONS,+ WORK_AREA_IDS,+ hiddenMenuSections,+ menuSectionOf,+ type WorkAreaId,+} from '@/lib/menu-access';+import { getMyMenu, setMyWorkAreas, type MyMenu } from '@/lib/actions/menu-access';++/** The menu's sections with their icons and nav titles, in its order. */+const SECTIONS = dashboardNav+ .flatMap((group) => group.items)+ .flatMap((item) => {+ const section = menuSectionOf(item.href);+ return section ? [{ section, title: item.title, icon: item.icon }] : [];+ });++/**+ * The menu with other work areas: what the admin takes off stays off, and the+ * areas narrow the rest (as for anyone, admins included).+ */+export function menuWithWorkAreas(menu: MyMenu, workAreas: WorkAreaId[]): MyMenu {+ const byAreas = hiddenMenuSections({+ role: 'admin',+ roleHidden: [],+ shown: [],+ hidden: [],+ workAreas,+ });+ return {+ ...menu,+ workAreas,+ hidden: MENU_SECTIONS.filter((s) => menu.hiddenByAdmin.includes(s) || byAreas.has(s)),+ };+}++/**+ * Settings › Account › Your work areas: what the person works on or leads,+ * which narrows their own left menu (menu access, 00374), and the menu it+ * leaves them, with why a section is off. Saved as it changes.+ */+export function WorkAreasCard() {+ const t = useTranslations('settings.menuAccess');+ const tNav = useTranslations('nav');+ const { canAdmin } = useUserRole();+ const [menu, setMenu] = useState<MyMenu | null>(null);+ const [failed, setFailed] = useState(false);++ useEffect(() => {+ let current = true;+ getMyMenu().then(+ (next) => {+ if (current) setMenu(next);+ },+ () => {+ if (current) setFailed(true);+ },+ );+ return () => {+ current = false;+ };+ }, []);++ // The save's own revalidation brings the left menu up to date+ // (setMyWorkAreas). A failed one reads the menu again, so a pick saved+ // meanwhile stays, which putting back the state before it wouldn't.+ const save = async (workAreas: WorkAreaId[]) => {+ if (!menu) return;+ setMenu(menuWithWorkAreas(menu, workAreas));+ try {+ await setMyWorkAreas(workAreas);+ } catch {+ toast.error(t('saveFailed'));+ getMyMenu().then(setMenu, () => setFailed(true));+ }+ };++ const toggle = (area: WorkAreaId) => {+ if (!menu) return;+ const picked = menu.workAreas.includes(area)+ ? menu.workAreas.filter((a) => a !== area)+ : [...menu.workAreas, area];+ void save(WORK_AREA_IDS.filter((a) => picked.includes(a)));+ };++ return (+ <Card>+ <CardHeader>+ <CardTitle>{t('workAreasTitle')}</CardTitle>+ <CardDescription>+ {canAdmin ? t('workAreasDescriptionAdmin') : t('workAreasDescription')}+ </CardDescription>+ </CardHeader>+ <CardContent>+ {failed ? (+ <p className="text-sm text-muted-foreground">{t('loadFailed')}</p>+ ) : !menu ? (+ <div className="space-y-2">+ <Skeleton className="h-7 w-full" />+ <Skeleton className="h-24 w-full" />+ </div>+ ) : (+ <div className="space-y-4">+ <div className="flex flex-wrap gap-1.5">+ {WORK_AREA_IDS.map((area) => {+ const on = menu.workAreas.includes(area);+ return (+ <Button+ key={area}+ variant={on ? 'default' : 'outline'}+ size="sm"+ aria-pressed={on}+ title={t(`areas.${area}.text`)}+ className="h-7 rounded-full px-3 text-xs"+ onClick={() => toggle(area)}+ >+ {t(`areas.${area}.title`)}+ </Button>+ );+ })}+ <Button+ variant={menu.workAreas.length ? 'outline' : 'default'}+ size="sm"+ aria-pressed={!menu.workAreas.length}+ className="h-7 rounded-full px-3 text-xs"+ onClick={() => void save([])}+ >+ {t('everything')}+ </Button>+ </div>++ <div className="@container">+ <p className="mb-2 flex items-baseline gap-2 text-sm font-medium">+ {t('yourMenu')}+ <span className="text-xs font-normal text-muted-foreground">+ {t('sectionCount', {+ count: MENU_SECTIONS.length - menu.hidden.length,+ total: MENU_SECTIONS.length,+ })}+ </span>+ </p>+ {/* Two columns once a section and why it's off fit side by side. */}+ <ul className="grid grid-cols-1 gap-x-6 gap-y-1.5 @lg:grid-cols-2">+ {SECTIONS.map(({ section, title, icon: Icon }) => {+ const off = menu.hidden.includes(section);+ const byAdmin = menu.hiddenByAdmin.includes(section);+ return (+ <li+ key={section}+ data-section={section}+ className={cn('flex items-center gap-2 text-sm', off && 'opacity-50')}+ >+ <Icon className="h-4 w-4 shrink-0 text-muted-foreground" />+ <span className="min-w-0 truncate">{getDashboardNavLabel(title, tNav)}</span>+ {off && (+ <span className="ml-auto flex shrink-0 items-center gap-1 text-xs text-muted-foreground">+ {byAdmin && <Lock className="h-3 w-3" />}+ {byAdmin ? t('hiddenByAdmin') : t('notInWorkAreas')}+ </span>+ )}+ </li>+ );+ })}+ </ul>+ </div>++ {menu.hiddenByAdmin.length > 0 && (+ <div className="flex gap-2 rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-200">+ <Lock className="mt-0.5 h-4 w-4 shrink-0" />+ <p>{t('adminTookOff', { count: menu.hiddenByAdmin.length })}</p>+ </div>+ )}+ </div>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/web/src/lib/actions/menu-access.test.ts b/web/src/lib/actions/menu-access.test.tsindex b8f3c1304..4feeb25b3 100644--- a/web/src/lib/actions/menu-access.test.ts+++ b/web/src/lib/actions/menu-access.test.ts@@ -102,6 +102,7 @@ describe('getMyMenu', () => {expect(menu.hidden.sort()).toEqual(['audit', 'citations', 'content', 'prompts', 'shopping', 'traffic'].sort(),);+ expect(menu.hiddenByAdmin).toEqual(['citations']);expect(menu.workAreas).toEqual(['brand']);expect(menu.workAreasAsked).toBe(false);expect(menu.canManageMenus).toBe(false);diff --git a/web/src/lib/menu-access.test.ts b/web/src/lib/menu-access.test.tsindex 175ffadb8..362af0a02 100644--- a/web/src/lib/menu-access.test.ts+++ b/web/src/lib/menu-access.test.ts@@ -129,6 +129,7 @@ describe('menuOfProfile', () => {it('builds the menu from the profile and the role’s row', () => {expect(menuOfProfile(profile, ['citations'])).toEqual({hidden: ['content', 'audit', 'prompts', 'citations', 'shopping', 'traffic'],+ hiddenByAdmin: ['citations'],workAreas: ['brand'],workAreasAsked: false,canManageMenus: true,diff --git a/web/src/lib/menu-access.ts b/web/src/lib/menu-access.tsindex 8052dd574..9a6ba9d92 100644--- a/web/src/lib/menu-access.ts+++ b/web/src/lib/menu-access.ts@@ -140,6 +140,8 @@ export function hiddenMenuSections(export interface MyMenu {/** Sections off this person's left menu. */hidden: string[];+ /** Of those, the ones their role or an exception takes off, whatever their work areas. */+ hiddenByAdmin: string[];workAreas: WorkAreaId[];/** Whether they answered (or skipped) "What do you work on?". */workAreasAsked: boolean;@@ -168,15 +170,15 @@ export function workAreasOf(values: readonly string[] | null): WorkAreaId[] {/** 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({+ const access = {role: profile.role,roleHidden,shown: profile.menu_shown ?? [],hidden: profile.menu_hidden ?? [],- workAreas,- });+ };return {- hidden: [...hidden],+ hidden: [...hiddenMenuSections({ ...access, workAreas })],+ hiddenByAdmin: [...hiddenMenuSections({ ...access, workAreas: [] })],workAreas,workAreasAsked: profile.work_areas_asked_at !== null,canManageMenus: canManageMenus(profile),