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): store who sees which menu sections, by role, person and work area (menu access, part 1) (#1702)

Cihan8f27956ab68c
diff --git a/supabase/migrations/00374_menu_access.sql b/supabase/migrations/00374_menu_access.sql
new file mode 100644
index 000000000..41baf4b80
--- /dev/null
+++ b/supabase/migrations/00374_menu_access.sql
@@ -0,0 +1,164 @@
+-- ============================================================================
+-- 00374: menu access — which left-menu sections each role and person sees
+-- ============================================================================
+-- Admins pick which sections of the left menu each role sees, and can let
+-- chosen managers do it too (Settings › Menu access). People pick what they
+-- work on or lead, which narrows their own menu (the "What do you work on?"
+-- step and Settings › Account). Hide only: a hidden section is off the menu,
+-- its pages still open from a link, and roles and data access don't change.
+-- Nobody takes a section off an admin's menu (only their own work areas
+-- narrow it), and Action Center is on everyone's menu (the app applies both).
+--
+-- Sections are named by their route under /dashboard ('content', 'audit',
+-- 'insights'…), so a section added later is on everyone's menu until someone
+-- hides it.
+--
+-- * organization_menu_roles: per organization and role (not admin), the
+-- sections that role doesn't see. No row = the role sees every section.
+-- Members of the organization read it (their menu needs their role's
+-- row); the server writes it (service role), for an admin or a manager
+-- who can change menus.
+-- * profiles.menu_shown / menu_hidden: a person's exception to their role:
+-- a section shown that the role hides, or hidden that it shows.
+-- profiles.can_manage_menus: a manager an admin let change menus. All
+-- three are set by the server (the guard below), like role, and belong
+-- to the organization and role they were given for: moving organization
+-- (removed, then invited elsewhere) clears all three, and a new role
+-- clears can_manage_menus (the reset below).
+-- * profiles.work_areas: what the person works on or leads, theirs to set.
+-- work_areas_asked_at: when they answered (or skipped) the step, so it
+-- is asked once.
+
+create table if not exists public.organization_menu_roles (
+ organization_id uuid not null references public.organizations(id) on delete cascade,
+ role public.user_role not null check (role <> 'admin'),
+ hidden_sections text[] not null default '{}',
+ updated_by uuid references auth.users(id) on delete set null,
+ updated_at timestamptz not null default now(),
+ primary key (organization_id, role)
+);
+
+-- Read by members of the organization (the policy below); written by the server.
+alter table public.organization_menu_roles enable row level security;
+revoke all on table public.organization_menu_roles from anon, authenticated;
+grant select on table public.organization_menu_roles to authenticated;
+grant all on table public.organization_menu_roles to service_role;
+
+drop policy if exists "organization_menu_roles: member select" on public.organization_menu_roles;
+create policy "organization_menu_roles: member select"
+ on public.organization_menu_roles
+ for select
+ using (
+ organization_id in (
+ select p.organization_id from public.profiles p where p.id = auth.uid()
+ )
+ );
+
+drop trigger if exists trg_organization_menu_roles_updated_at on public.organization_menu_roles;
+create trigger trg_organization_menu_roles_updated_at
+ before update on public.organization_menu_roles
+ for each row execute function public.handle_updated_at();
+
+comment on table public.organization_menu_roles is
+ 'Menu access: the left-menu sections (routes under /dashboard) a role of the organization doesn''t see. Hide only: the pages still open. No row = every section. Never for admins; the server writes it.';
+
+alter table public.profiles
+ add column if not exists work_areas text[] not null default '{}'
+ check (
+ work_areas <@ array[
+ 'leaders', 'aeo', 'content', 'brand', 'growth',
+ 'product', 'bizdev', 'developers', 'analytics'
+ ]::text[]
+ ),
+ add column if not exists work_areas_asked_at timestamptz,
+ add column if not exists menu_shown text[] not null default '{}',
+ add column if not exists menu_hidden text[] not null default '{}',
+ add column if not exists can_manage_menus boolean not null default false;
+
+comment on column public.profiles.work_areas is
+ 'Menu access: what the person works on or leads; narrows their left menu to those areas'' sections. Empty = every section.';
+comment on column public.profiles.work_areas_asked_at is
+ 'Menu access: when the person answered or skipped "What do you work on?"; null = not asked yet.';
+comment on column public.profiles.menu_shown is
+ 'Menu access: sections shown for this person although their role hides them. Set by the server.';
+comment on column public.profiles.menu_hidden is
+ 'Menu access: sections hidden for this person although their role shows them. Set by the server.';
+comment on column public.profiles.can_manage_menus is
+ 'Menu access: a manager an admin let change menus (the role table and every non-admin''s exceptions). Set by the server.';
+
+-- 00228's guard, plus the menu columns: a person's own update can't give
+-- them a menu exception or the right to change menus.
+create or replace function public.guard_profile_server_columns()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ if (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user) then
+ return new;
+ end if;
+ if new.role is distinct from old.role then
+ raise exception 'profile role is managed server-side' using errcode = '42501';
+ end if;
+ if new.organization_id is distinct from old.organization_id
+ and (
+ old.organization_id is not null
+ or new.organization_id is null
+ or public.organization_has_other_members(new.organization_id, new.id)
+ )
+ then
+ raise exception 'profile organization is managed server-side' using errcode = '42501';
+ end if;
+ if new.menu_shown is distinct from old.menu_shown
+ or new.menu_hidden is distinct from old.menu_hidden
+ or new.can_manage_menus is distinct from old.can_manage_menus
+ then
+ raise exception 'profile menu access is managed server-side' using errcode = '42501';
+ end if;
+ return new;
+end;
+$$;
+
+-- A removed member keeps their profile (organization_id goes null) and an
+-- invitation moves it to the next organization, so a menu manager of one
+-- organization would arrive in another still able to change its menus.
+-- Whoever makes the change, a new organization clears the menu columns and
+-- a new role clears the right to change menus (an admin gives it again);
+-- a value the same update sets stays, only one carried over goes. Fires
+-- after the guard (triggers run in name order), so the guard checks what
+-- the person asked for, not this reset.
+create or replace function public.reset_profile_menu_access()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ if (new.organization_id is distinct from old.organization_id
+ or new.role is distinct from old.role)
+ and new.can_manage_menus is not distinct from old.can_manage_menus
+ then
+ new.can_manage_menus := false;
+ end if;
+ if new.organization_id is distinct from old.organization_id then
+ if new.menu_shown is not distinct from old.menu_shown then
+ new.menu_shown := '{}';
+ end if;
+ if new.menu_hidden is not distinct from old.menu_hidden then
+ new.menu_hidden := '{}';
+ end if;
+ end if;
+ return new;
+end;
+$$;
+
+drop trigger if exists profiles_reset_menu_access on public.profiles;
+create trigger profiles_reset_menu_access
+ before update of organization_id, role on public.profiles
+ for each row execute function public.reset_profile_menu_access();
+
+-- Everyone here before menu access counts as asked: "What do you work on?"
+-- is for new sign-ups and people joining from an invite, once. Existing
+-- people pick their work areas in Settings › Account if they want to.
+update public.profiles set work_areas_asked_at = now() where work_areas_asked_at is null;
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 081ee94a7..9b4b53da6 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -42267,3 +42267,171 @@ comment on function public.prompt_demand_brand_updates() is
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00374_menu_access.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00374: menu access — which left-menu sections each role and person sees
+-- ============================================================================
+-- Admins pick which sections of the left menu each role sees, and can let
+-- chosen managers do it too (Settings › Menu access). People pick what they
+-- work on or lead, which narrows their own menu (the "What do you work on?"
+-- step and Settings › Account). Hide only: a hidden section is off the menu,
+-- its pages still open from a link, and roles and data access don't change.
+-- Nobody takes a section off an admin's menu (only their own work areas
+-- narrow it), and Action Center is on everyone's menu (the app applies both).
+--
+-- Sections are named by their route under /dashboard ('content', 'audit',
+-- 'insights'…), so a section added later is on everyone's menu until someone
+-- hides it.
+--
+-- * organization_menu_roles: per organization and role (not admin), the
+-- sections that role doesn't see. No row = the role sees every section.
+-- Members of the organization read it (their menu needs their role's
+-- row); the server writes it (service role), for an admin or a manager
+-- who can change menus.
+-- * profiles.menu_shown / menu_hidden: a person's exception to their role:
+-- a section shown that the role hides, or hidden that it shows.
+-- profiles.can_manage_menus: a manager an admin let change menus. All
+-- three are set by the server (the guard below), like role, and belong
+-- to the organization and role they were given for: moving organization
+-- (removed, then invited elsewhere) clears all three, and a new role
+-- clears can_manage_menus (the reset below).
+-- * profiles.work_areas: what the person works on or leads, theirs to set.
+-- work_areas_asked_at: when they answered (or skipped) the step, so it
+-- is asked once.
+
+create table if not exists public.organization_menu_roles (
+ organization_id uuid not null references public.organizations(id) on delete cascade,
+ role public.user_role not null check (role <> 'admin'),
+ hidden_sections text[] not null default '{}',
+ updated_by uuid references auth.users(id) on delete set null,
+ updated_at timestamptz not null default now(),
+ primary key (organization_id, role)
+);
+
+-- Read by members of the organization (the policy below); written by the server.
+alter table public.organization_menu_roles enable row level security;
+revoke all on table public.organization_menu_roles from anon, authenticated;
+grant select on table public.organization_menu_roles to authenticated;
+grant all on table public.organization_menu_roles to service_role;
+
+drop policy if exists "organization_menu_roles: member select" on public.organization_menu_roles;
+create policy "organization_menu_roles: member select"
+ on public.organization_menu_roles
+ for select
+ using (
+ organization_id in (
+ select p.organization_id from public.profiles p where p.id = auth.uid()
+ )
+ );
+
+drop trigger if exists trg_organization_menu_roles_updated_at on public.organization_menu_roles;
+create trigger trg_organization_menu_roles_updated_at
+ before update on public.organization_menu_roles
+ for each row execute function public.handle_updated_at();
+
+comment on table public.organization_menu_roles is
+ 'Menu access: the left-menu sections (routes under /dashboard) a role of the organization doesn''t see. Hide only: the pages still open. No row = every section. Never for admins; the server writes it.';
+
+alter table public.profiles
+ add column if not exists work_areas text[] not null default '{}'
+ check (
+ work_areas <@ array[
+ 'leaders', 'aeo', 'content', 'brand', 'growth',
+ 'product', 'bizdev', 'developers', 'analytics'
+ ]::text[]
+ ),
+ add column if not exists work_areas_asked_at timestamptz,
+ add column if not exists menu_shown text[] not null default '{}',
+ add column if not exists menu_hidden text[] not null default '{}',
+ add column if not exists can_manage_menus boolean not null default false;
+
+comment on column public.profiles.work_areas is
+ 'Menu access: what the person works on or leads; narrows their left menu to those areas'' sections. Empty = every section.';
+comment on column public.profiles.work_areas_asked_at is
+ 'Menu access: when the person answered or skipped "What do you work on?"; null = not asked yet.';
+comment on column public.profiles.menu_shown is
+ 'Menu access: sections shown for this person although their role hides them. Set by the server.';
+comment on column public.profiles.menu_hidden is
+ 'Menu access: sections hidden for this person although their role shows them. Set by the server.';
+comment on column public.profiles.can_manage_menus is
+ 'Menu access: a manager an admin let change menus (the role table and every non-admin''s exceptions). Set by the server.';
+
+-- 00228's guard, plus the menu columns: a person's own update can't give
+-- them a menu exception or the right to change menus.
+create or replace function public.guard_profile_server_columns()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ if (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user) then
+ return new;
+ end if;
+ if new.role is distinct from old.role then
+ raise exception 'profile role is managed server-side' using errcode = '42501';
+ end if;
+ if new.organization_id is distinct from old.organization_id
+ and (
+ old.organization_id is not null
+ or new.organization_id is null
+ or public.organization_has_other_members(new.organization_id, new.id)
+ )
+ then
+ raise exception 'profile organization is managed server-side' using errcode = '42501';
+ end if;
+ if new.menu_shown is distinct from old.menu_shown
+ or new.menu_hidden is distinct from old.menu_hidden
+ or new.can_manage_menus is distinct from old.can_manage_menus
+ then
+ raise exception 'profile menu access is managed server-side' using errcode = '42501';
+ end if;
+ return new;
+end;
+$$;
+
+-- A removed member keeps their profile (organization_id goes null) and an
+-- invitation moves it to the next organization, so a menu manager of one
+-- organization would arrive in another still able to change its menus.
+-- Whoever makes the change, a new organization clears the menu columns and
+-- a new role clears the right to change menus (an admin gives it again);
+-- a value the same update sets stays, only one carried over goes. Fires
+-- after the guard (triggers run in name order), so the guard checks what
+-- the person asked for, not this reset.
+create or replace function public.reset_profile_menu_access()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ if (new.organization_id is distinct from old.organization_id
+ or new.role is distinct from old.role)
+ and new.can_manage_menus is not distinct from old.can_manage_menus
+ then
+ new.can_manage_menus := false;
+ end if;
+ if new.organization_id is distinct from old.organization_id then
+ if new.menu_shown is not distinct from old.menu_shown then
+ new.menu_shown := '{}';
+ end if;
+ if new.menu_hidden is not distinct from old.menu_hidden then
+ new.menu_hidden := '{}';
+ end if;
+ end if;
+ return new;
+end;
+$$;
+
+drop trigger if exists profiles_reset_menu_access on public.profiles;
+create trigger profiles_reset_menu_access
+ before update of organization_id, role on public.profiles
+ for each row execute function public.reset_profile_menu_access();
+
+-- Everyone here before menu access counts as asked: "What do you work on?"
+-- is for new sign-ups and people joining from an invite, once. Existing
+-- people pick their work areas in Settings › Account if they want to.
+update public.profiles set work_areas_asked_at = now() where work_areas_asked_at is null;
+
+notify pgrst, 'reload schema';
+
diff --git a/web/src/lib/actions/menu-access.test.ts b/web/src/lib/actions/menu-access.test.ts
new file mode 100644
index 000000000..b8f3c1304
--- /dev/null
+++ b/web/src/lib/actions/menu-access.test.ts
@@ -0,0 +1,324 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Menu access (00374): who may change menus, and what the server writes.
+ * The person's own client reads their profile and their role's row; the
+ * service client reads members and writes everything but work areas.
+ */
+
+const ME = '11111111-1111-4111-8111-111111111111';
+const ORG = '22222222-2222-4222-8222-222222222222';
+const ADA = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+
+interface Call {
+ client: 'user' | 'admin';
+ table: string;
+ op: string;
+ row?: unknown;
+ options?: unknown;
+ filters: [string, unknown][];
+}
+let calls: Call[] = [];
+/** What a read or write answers, by `${client}.${table}.${op}`. */
+let answers: Record<string, { data: unknown; error: null | { message: string } }> = {};
+
+function builder(client: Call['client']) {
+ return (table: string) => {
+ const call: Call = { client, table, op: 'select', filters: [] };
+ calls.push(call);
+ const answer = () => answers[`${client}.${table}.${call.op}`] ?? { data: null, error: null };
+ const chain = {
+ select: () => chain,
+ update: (row: unknown) => Object.assign(call, { op: 'update', row }) && chain,
+ upsert: (row: unknown, options: unknown) =>
+ Object.assign(call, { op: 'upsert', row, options }) && chain,
+ eq: (column: string, value: unknown) => {
+ call.filters.push([column, value]);
+ return chain;
+ },
+ order: () => chain,
+ single: async () => answer(),
+ maybeSingle: async () => answer(),
+ then: (resolve: (value: unknown) => unknown) => Promise.resolve(answer()).then(resolve),
+ };
+ return chain;
+ };
+}
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ auth: { getUser: async () => ({ data: { user: { id: ME } } }) },
+ from: builder('user'),
+ })),
+}));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: { from: builder('admin') } }));
+vi.mock('@/lib/member-emails', () => ({
+ readMemberEmails: async (ids: string[]) => new Map(ids.map((id) => [id, `${id}@x.example`])),
+}));
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }));
+
+const {
+ getMenuAccessSettings,
+ getMyMenu,
+ setMemberMenu,
+ setMenuManager,
+ setMyWorkAreas,
+ setRoleMenu,
+} = await import('./menu-access');
+
+const writes = () => calls.filter((c) => c.op !== 'select');
+
+function signedInAs(profile: Record<string, unknown>) {
+ answers['user.profiles.select'] = {
+ data: {
+ id: ME,
+ organization_id: ORG,
+ work_areas: [],
+ work_areas_asked_at: null,
+ menu_shown: [],
+ menu_hidden: [],
+ can_manage_menus: false,
+ ...profile,
+ },
+ error: null,
+ };
+}
+
+beforeEach(() => {
+ calls = [];
+ answers = {};
+});
+
+describe('getMyMenu', () => {
+ it('leaves out what the role hides, narrowed to the work areas', async () => {
+ signedInAs({ role: 'analyst', work_areas: ['brand', 'gone'], menu_shown: ['prompts'] });
+ answers['user.organization_menu_roles.select'] = {
+ data: { hidden_sections: ['citations'] },
+ error: null,
+ };
+
+ const menu = await getMyMenu();
+
+ expect(menu.hidden.sort()).toEqual(
+ ['audit', 'citations', 'content', 'prompts', 'shopping', 'traffic'].sort(),
+ );
+ expect(menu.workAreas).toEqual(['brand']);
+ expect(menu.workAreasAsked).toBe(false);
+ expect(menu.canManageMenus).toBe(false);
+ const roleRead = calls.find((c) => c.table === 'organization_menu_roles');
+ expect(roleRead?.client).toBe('user');
+ expect(roleRead?.filters).toEqual([
+ ['organization_id', ORG],
+ ['role', 'analyst'],
+ ]);
+ });
+
+ it('narrows an admin’s menu to their work areas only, without reading a role row', async () => {
+ signedInAs({ role: 'admin', work_areas: ['brand'], menu_hidden: ['reports'] });
+
+ const menu = await getMyMenu();
+
+ expect(menu.hidden.sort()).toEqual(
+ ['audit', 'content', 'prompts', 'shopping', 'traffic'].sort(),
+ );
+ expect(menu.canManageMenus).toBe(true);
+ expect(calls.some((c) => c.table === 'organization_menu_roles')).toBe(false);
+ });
+
+ it('counts a manager an admin let change menus', async () => {
+ signedInAs({ role: 'manager', can_manage_menus: true, work_areas_asked_at: '2026-10-28' });
+ expect(await getMyMenu()).toMatchObject({ canManageMenus: true, workAreasAsked: true });
+ });
+});
+
+describe('setRoleMenu', () => {
+ it('refuses people who can’t change menus', async () => {
+ signedInAs({ role: 'analyst' });
+ await expect(setRoleMenu('analyst', ['content'])).rejects.toThrow(/menu managers/);
+ signedInAs({ role: 'manager', can_manage_menus: false });
+ await expect(setRoleMenu('analyst', ['content'])).rejects.toThrow(/menu managers/);
+ signedInAs({ role: 'analyst', can_manage_menus: true });
+ await expect(setRoleMenu('analyst', ['content'])).rejects.toThrow(/menu managers/);
+ expect(writes()).toEqual([]);
+ });
+
+ it('never sets the admins’ menu', async () => {
+ signedInAs({ role: 'admin' });
+ await expect(setRoleMenu('admin' as never, ['content'])).rejects.toThrow(/Nobody sets/);
+ expect(writes()).toEqual([]);
+ });
+
+ it('keeps the role’s known sections, without Action Center', async () => {
+ signedInAs({ role: 'manager', can_manage_menus: true });
+
+ await setRoleMenu('analyst', ['reports', 'action-center', 'nope', 'content']);
+
+ expect(writes()).toEqual([
+ expect.objectContaining({
+ client: 'admin',
+ table: 'organization_menu_roles',
+ op: 'upsert',
+ row: {
+ organization_id: ORG,
+ role: 'analyst',
+ hidden_sections: ['content', 'reports'],
+ updated_by: ME,
+ },
+ options: { onConflict: 'organization_id,role' },
+ }),
+ ]);
+ });
+});
+
+describe('setMemberMenu', () => {
+ it('never changes an admin’s menu', async () => {
+ signedInAs({ role: 'manager', can_manage_menus: true });
+ answers['admin.profiles.select'] = { data: { role: 'admin' }, error: null };
+
+ await expect(setMemberMenu(ADA, { shown: [], hidden: ['content'] })).rejects.toThrow(
+ /Nobody sets/,
+ );
+ expect(writes()).toEqual([]);
+ });
+
+ it('refuses someone outside the organization', async () => {
+ signedInAs({ role: 'admin' });
+ await expect(setMemberMenu(ADA, { shown: [], hidden: [] })).rejects.toThrow(/Not a member/);
+ expect(calls.find((c) => c.client === 'admin')?.filters).toEqual([
+ ['id', ADA],
+ ['organization_id', ORG],
+ ]);
+ });
+
+ it('writes the exceptions, a section shown winning over hidden', async () => {
+ signedInAs({ role: 'admin' });
+ answers['admin.profiles.select'] = { data: { role: 'analyst' }, error: null };
+
+ await setMemberMenu(ADA, { shown: ['audit', 'audit'], hidden: ['audit', 'content', 'x'] });
+
+ expect(writes()).toEqual([
+ expect.objectContaining({
+ client: 'admin',
+ table: 'profiles',
+ op: 'update',
+ row: { menu_shown: ['audit'], menu_hidden: ['content'] },
+ filters: [
+ ['id', ADA],
+ ['organization_id', ORG],
+ ],
+ }),
+ ]);
+ });
+});
+
+describe('setMenuManager', () => {
+ it('is for admins only', async () => {
+ signedInAs({ role: 'manager', can_manage_menus: true });
+ await expect(setMenuManager(ADA, true)).rejects.toThrow(/Only admins/);
+ expect(writes()).toEqual([]);
+ });
+
+ it('only gives it to managers', async () => {
+ signedInAs({ role: 'admin' });
+ answers['admin.profiles.select'] = { data: { role: 'analyst' }, error: null };
+ await expect(setMenuManager(ADA, true)).rejects.toThrow(/Only managers/);
+ expect(writes()).toEqual([]);
+ });
+
+ it('takes only true or false', async () => {
+ signedInAs({ role: 'admin' });
+ answers['admin.profiles.select'] = { data: { role: 'manager' }, error: null };
+ await expect(setMenuManager(ADA, 'yes' as never)).rejects.toThrow();
+ expect(writes()).toEqual([]);
+ });
+
+ it('lets a manager change menus', async () => {
+ signedInAs({ role: 'admin' });
+ answers['admin.profiles.select'] = { data: { role: 'manager' }, error: null };
+
+ await setMenuManager(ADA, true);
+
+ expect(writes()).toEqual([
+ expect.objectContaining({
+ table: 'profiles',
+ op: 'update',
+ row: { can_manage_menus: true },
+ }),
+ ]);
+ });
+});
+
+describe('setMyWorkAreas', () => {
+ it('refuses an area it doesn’t know', async () => {
+ await expect(setMyWorkAreas(['brand', 'sales'])).rejects.toThrow();
+ expect(writes()).toEqual([]);
+ });
+
+ it('writes the person’s own areas, in the list’s order, and marks them asked', async () => {
+ await setMyWorkAreas(['analytics', 'brand', 'leaders']);
+
+ const [write] = writes();
+ expect(write).toMatchObject({
+ client: 'user',
+ table: 'profiles',
+ op: 'update',
+ filters: [['id', ME]],
+ });
+ expect(write.row).toMatchObject({ work_areas: ['leaders', 'brand', 'analytics'] });
+ expect((write.row as { work_areas_asked_at: string }).work_areas_asked_at).toEqual(
+ expect.any(String),
+ );
+ });
+
+ it('takes none: every section, and the step answered', async () => {
+ await setMyWorkAreas([]);
+ expect(writes()[0].row).toMatchObject({ work_areas: [] });
+ });
+});
+
+describe('getMenuAccessSettings', () => {
+ it('is for admins and menu managers', async () => {
+ signedInAs({ role: 'manager' });
+ await expect(getMenuAccessSettings()).rejects.toThrow(/menu managers/);
+ });
+
+ it('reads the role table and the members', async () => {
+ signedInAs({ role: 'manager', can_manage_menus: true });
+ answers['admin.organization_menu_roles.select'] = {
+ data: [
+ { role: 'analyst', hidden_sections: ['content', 'action-center'] },
+ { role: 'agency_partner', hidden_sections: ['nope'] },
+ ],
+ error: null,
+ };
+ answers['admin.profiles.select'] = {
+ data: [
+ { id: ME, role: 'manager', full_name: 'Me', can_manage_menus: true, work_areas: ['brand'] },
+ {
+ id: ADA,
+ role: 'analyst',
+ full_name: null,
+ can_manage_menus: true,
+ menu_hidden: ['audit'],
+ },
+ ],
+ error: null,
+ };
+
+ const settings = await getMenuAccessSettings();
+
+ expect(settings.roles).toEqual({ manager: [], analyst: ['content'], agency_partner: [] });
+ expect(settings.viewerIsAdmin).toBe(false);
+ expect(settings.members).toEqual([
+ expect.objectContaining({
+ userId: ME,
+ email: `${ME}@x.example`,
+ workAreas: ['brand'],
+ canManageMenus: true,
+ isCurrentUser: true,
+ }),
+ // A flag left from when they were a manager counts for nothing.
+ expect.objectContaining({ userId: ADA, hidden: ['audit'], canManageMenus: false }),
+ ]);
+ });
+});
diff --git a/web/src/lib/actions/menu-access.ts b/web/src/lib/actions/menu-access.ts
new file mode 100644
index 000000000..ad06d8a1e
--- /dev/null
+++ b/web/src/lib/actions/menu-access.ts
@@ -0,0 +1,289 @@
+'use server';
+
+import { revalidatePath } from 'next/cache';
+import { z } from 'zod';
+import { createClient } from '@/lib/supabase/server';
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import { readMemberEmails } from '@/lib/member-emails';
+import {
+ WORK_AREA_IDS,
+ cleanMenuSections,
+ hiddenMenuSections,
+ isWorkAreaId,
+ type WorkAreaId,
+} from '@/lib/menu-access';
+import type { UserRole } from '@/types';
+
+/**
+ * Menu access (00374): who sees which left-menu sections. Admins, and the
+ * managers they let change menus, set what each role sees and each
+ * non-admin's exceptions; the server writes them. A person sets their own
+ * work areas. Hide only: nothing here changes what anyone can open or do.
+ */
+
+/** The roles whose menu can be set: nobody takes a section off an admin's menu. */
+export type MenuRole = Exclude<UserRole, 'admin'>;
+
+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 interface MenuMember {
+ userId: string;
+ email: string;
+ fullName: string | null;
+ avatarUrl: string | null;
+ role: UserRole;
+ workAreas: WorkAreaId[];
+ shown: string[];
+ hidden: string[];
+ canManageMenus: boolean;
+ isCurrentUser: boolean;
+}
+
+export interface MenuAccessSettings {
+ /** The sections each role doesn't see. */
+ roles: Record<MenuRole, string[]>;
+ members: MenuMember[];
+ /** The viewer is an admin: only they let managers change menus. */
+ viewerIsAdmin: boolean;
+}
+
+interface Profile {
+ 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> {
+ const supabase = await createClient();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+ if (!user) throw new Error('Unauthorized');
+
+ const { data: profile } = await supabase
+ .from('profiles')
+ .select(
+ 'id, role, organization_id, work_areas, work_areas_asked_at, menu_shown, menu_hidden, can_manage_menus',
+ )
+ .eq('id', user.id)
+ .single();
+ if (!profile?.organization_id) throw new Error('No organization');
+ 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');
+ 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
+ .from('organization_menu_roles')
+ .select('role, hidden_sections')
+ .eq('organization_id', organizationId);
+ if (error) throw new Error(error.message);
+
+ const roles = { manager: [], analyst: [], agency_partner: [] } as Record<MenuRole, string[]>;
+ for (const row of data ?? []) {
+ const role = row.role as UserRole;
+ if (role !== 'admin') roles[role] = cleanMenuSections(row.hidden_sections ?? []);
+ }
+ return roles;
+}
+
+/** 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),
+ };
+}
+
+/** Settings › Menu access: the role table and every member's menu. */
+export async function getMenuAccessSettings(): Promise<MenuAccessSettings> {
+ const profile = await requireMenuManager();
+
+ const [roles, { data, error }] = await Promise.all([
+ readRoles(profile.organization_id),
+ supabaseAdmin
+ .from('profiles')
+ .select(
+ 'id, full_name, avatar_url, role, work_areas, menu_shown, menu_hidden, can_manage_menus, created_at',
+ )
+ .eq('organization_id', profile.organization_id)
+ .order('created_at', { ascending: true }),
+ ]);
+ if (error) throw new Error(error.message);
+
+ const rows = data ?? [];
+ const emails = await readMemberEmails(rows.map((row) => row.id as string));
+ return {
+ roles,
+ viewerIsAdmin: profile.role === 'admin',
+ members: rows.map((row) => ({
+ userId: row.id as string,
+ email: emails.get(row.id as string) ?? '',
+ fullName: (row.full_name as string | null) ?? null,
+ avatarUrl: (row.avatar_url as string | null) ?? null,
+ role: row.role as UserRole,
+ 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({
+ role: row.role as UserRole,
+ can_manage_menus: row.can_manage_menus as boolean | null,
+ }),
+ isCurrentUser: row.id === profile.id,
+ })),
+ };
+}
+
+/** The sections a role doesn't see. */
+export async function setRoleMenu(role: MenuRole, hidden: string[]) {
+ const profile = await requireMenuManager();
+ if (!MENU_ROLES.includes(role)) throw new Error('Nobody sets the admins’ menu');
+ const parsed = sections.parse(hidden);
+
+ const { error } = await supabaseAdmin.from('organization_menu_roles').upsert(
+ {
+ organization_id: profile.organization_id,
+ role,
+ hidden_sections: cleanMenuSections(parsed),
+ updated_by: profile.id,
+ },
+ { onConflict: 'organization_id,role' },
+ );
+ if (error) throw new Error(error.message);
+ revalidatePath('/dashboard', 'layout');
+}
+
+/**
+ * A non-admin's exceptions to their role: sections shown although the role
+ * hides them, and hidden although it shows them. Empty both = the role's menu.
+ */
+export async function setMemberMenu(memberId: string, menu: { shown: string[]; hidden: string[] }) {
+ const profile = await requireMenuManager();
+ const id = userId.parse(memberId);
+ const shown = cleanMenuSections(sections.parse(menu.shown));
+ const hidden = cleanMenuSections(sections.parse(menu.hidden)).filter(
+ (section) => !shown.includes(section),
+ );
+
+ const { data: member } = await supabaseAdmin
+ .from('profiles')
+ .select('role')
+ .eq('id', id)
+ .eq('organization_id', profile.organization_id)
+ .maybeSingle();
+ if (!member) throw new Error('Not a member of your organization');
+ if (member.role === 'admin') throw new Error('Nobody sets an admin’s menu');
+
+ const { error } = await supabaseAdmin
+ .from('profiles')
+ .update({ menu_shown: shown, menu_hidden: hidden })
+ .eq('id', id)
+ .eq('organization_id', profile.organization_id);
+ if (error) throw new Error(error.message);
+ revalidatePath('/dashboard', 'layout');
+}
+
+/** Lets a manager change menus, or takes it back. Admins only. */
+export async function setMenuManager(memberId: string, allowed: boolean) {
+ const profile = await currentProfile();
+ if (profile.role !== 'admin') throw new Error('Only admins can choose who changes menus');
+ const id = userId.parse(memberId);
+ const canChange = z.boolean().parse(allowed);
+
+ const { data: member } = await supabaseAdmin
+ .from('profiles')
+ .select('role')
+ .eq('id', id)
+ .eq('organization_id', profile.organization_id)
+ .maybeSingle();
+ if (!member) throw new Error('Not a member of your organization');
+ if (member.role !== 'manager') throw new Error('Only managers can be given this');
+
+ const { error } = await supabaseAdmin
+ .from('profiles')
+ .update({ can_manage_menus: canChange })
+ .eq('id', id)
+ .eq('organization_id', profile.organization_id);
+ if (error) throw new Error(error.message);
+ revalidatePath('/dashboard/settings');
+}
+
+/**
+ * What the viewer works on or leads; none = every section. Answers "What do
+ * you work on?" too, so it isn't asked again.
+ */
+export async function setMyWorkAreas(areas: string[]) {
+ const parsed = z.array(z.enum(WORK_AREA_IDS as [WorkAreaId, ...WorkAreaId[]])).parse(areas);
+ const supabase = await createClient();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+ if (!user) throw new Error('Unauthorized');
+
+ // Their own row, as RLS and 00374's guard let a person change it.
+ const { error } = await supabase
+ .from('profiles')
+ .update({
+ work_areas: WORK_AREA_IDS.filter((area) => parsed.includes(area)),
+ work_areas_asked_at: new Date().toISOString(),
+ })
+ .eq('id', user.id);
+ if (error) throw new Error(error.message);
+ revalidatePath('/dashboard', 'layout');
+}
diff --git a/web/src/lib/menu-access.test.ts b/web/src/lib/menu-access.test.ts
new file mode 100644
index 000000000..13880fd6b
--- /dev/null
+++ b/web/src/lib/menu-access.test.ts
@@ -0,0 +1,167 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { describe, expect, it } from 'vitest';
+import {
+ ALWAYS_ON_SECTION,
+ MENU_SECTIONS,
+ WORK_AREAS,
+ WORK_AREA_IDS,
+ cleanMenuSections,
+ hiddenMenuSections,
+ menuSectionOf,
+ workAreaSections,
+ type MenuAccess,
+} from './menu-access';
+
+const analyst: MenuAccess = {
+ role: 'analyst',
+ roleHidden: [],
+ shown: [],
+ hidden: [],
+ workAreas: [],
+};
+
+const hidden = (access: Partial<MenuAccess>) => [...hiddenMenuSections({ ...analyst, ...access })];
+
+describe('menuSectionOf', () => {
+ it('names a route by its first part under /dashboard', () => {
+ expect(menuSectionOf('/dashboard/content/plan')).toBe('content');
+ expect(menuSectionOf('/dashboard/agent')).toBe('agent');
+ expect(menuSectionOf('/dashboard')).toBeNull();
+ expect(menuSectionOf('/pricing')).toBeNull();
+ });
+});
+
+describe('MENU_SECTIONS', () => {
+ it('lists the left menu, Action Center first', () => {
+ expect(MENU_SECTIONS[0]).toBe(ALWAYS_ON_SECTION);
+ expect(MENU_SECTIONS).toEqual(
+ expect.arrayContaining(['agent', 'content', 'audit', 'insights', 'shopping', 'reports']),
+ );
+ });
+
+ it('knows every section a work area names', () => {
+ for (const area of WORK_AREAS) {
+ for (const section of area.sections) expect(MENU_SECTIONS).toContain(section);
+ }
+ });
+});
+
+describe('hiddenMenuSections', () => {
+ it('shows everything when nothing is hidden', () => {
+ expect(hidden({})).toEqual([]);
+ });
+
+ it('leaves out what the role hides', () => {
+ expect(hidden({ roleHidden: ['content', 'audit'] })).toEqual(['content', 'audit']);
+ });
+
+ it('shows a section for a person although the role hides it, and hides one it shows', () => {
+ expect(
+ hidden({ roleHidden: ['content', 'audit'], shown: ['audit'], hidden: ['reports'] }),
+ ).toEqual(['content', 'reports']);
+ });
+
+ it('narrows the menu to the work areas', () => {
+ expect(hidden({ workAreas: ['brand'] }).sort()).toEqual(
+ ['audit', 'content', 'prompts', 'shopping', 'traffic'].sort(),
+ );
+ });
+
+ it('keeps a section shown for the person to their work areas', () => {
+ expect(hidden({ workAreas: ['brand'], shown: ['content'] })).toContain('content');
+ });
+
+ it('ignores work areas it does not know', () => {
+ expect(hidden({ workAreas: ['retired-area'] })).toEqual([]);
+ });
+
+ it('keeps a section no work area names', () => {
+ const sections = [...MENU_SECTIONS, 'new-section'];
+ expect([...hiddenMenuSections({ ...analyst, workAreas: ['brand'] }, sections)]).not.toContain(
+ 'new-section',
+ );
+ });
+
+ it('never hides Action Center', () => {
+ expect(
+ hidden({
+ roleHidden: [ALWAYS_ON_SECTION],
+ hidden: [ALWAYS_ON_SECTION],
+ workAreas: ['brand'],
+ }),
+ ).not.toContain(ALWAYS_ON_SECTION);
+ });
+
+ it('takes nothing off an admin’s menu but their own work areas', () => {
+ expect(hidden({ role: 'admin', roleHidden: ['content'], hidden: ['reports'] })).toEqual([]);
+ expect(
+ hidden({ role: 'admin', roleHidden: ['mentions'], workAreas: ['brand'] }).sort(),
+ ).toEqual(['audit', 'content', 'prompts', 'shopping', 'traffic'].sort());
+ });
+});
+
+describe('workAreaSections', () => {
+ it('joins the areas’ sections', () => {
+ const sections = workAreaSections(['developers', 'brand']);
+ expect(sections?.has('audit')).toBe(true);
+ expect(sections?.has('mentions')).toBe(true);
+ expect(sections?.has('shopping')).toBe(false);
+ });
+
+ it('is null for no known area', () => {
+ expect(workAreaSections([])).toBeNull();
+ });
+});
+
+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(
+ ['content', 'reports'],
+ );
+ });
+});
+
+describe('the database (00374)', () => {
+ const migration = (name: string) =>
+ readFileSync(join(__dirname, `../../../supabase/migrations/${name}.sql`), 'utf8');
+ const sql = migration('00374_menu_access');
+ const triggerName = (text: string, fn: string) =>
+ text.match(
+ new RegExp(`create trigger (\\w+)\\s+before update[^;]*?function public\\.${fn}`),
+ )?.[1];
+
+ it('accepts exactly the work areas the app knows', () => {
+ const check = sql.match(/work_areas <@ array\[([^\]]*)\]/)?.[1] ?? '';
+ expect([...check.matchAll(/'([a-z]+)'/g)].map((m) => m[1])).toEqual(WORK_AREA_IDS);
+ });
+
+ it('clears menu access when the person moves organization, the right to change menus on a new role', () => {
+ const body = sql.match(
+ /function public\.reset_profile_menu_access\(\)[\s\S]*?\$\$([\s\S]*?)\$\$/,
+ )?.[1];
+ const flat = body?.replace(/\s+/g, ' ');
+ // A new organization or role clears the right to change menus…
+ expect(flat).toContain(
+ '(new.organization_id is distinct from old.organization_id or new.role is distinct from old.role) and new.can_manage_menus is not distinct from old.can_manage_menus then new.can_manage_menus := false;',
+ );
+ // …and a new organization the person's exceptions, unless the same
+ // update sets them.
+ expect(flat).toContain(
+ "if new.organization_id is distinct from old.organization_id then if new.menu_shown is not distinct from old.menu_shown then new.menu_shown := '{}'; end if; if new.menu_hidden is not distinct from old.menu_hidden then new.menu_hidden := '{}'; end if;",
+ );
+ // Before-update triggers run in name order: the guard sees what the
+ // person asked for, then the reset clears.
+ expect(sql).toMatch(
+ /create trigger profiles_reset_menu_access\s+before update of organization_id, role on public\.profiles/,
+ );
+ const guard = triggerName(
+ migration('00228_profiles_server_columns'),
+ 'guard_profile_server_columns',
+ );
+ const reset = triggerName(sql, 'reset_profile_menu_access');
+ expect(guard).toBeTruthy();
+ expect(reset).toBeTruthy();
+ expect(guard! < reset!).toBe(true);
+ });
+});
diff --git a/web/src/lib/menu-access.ts b/web/src/lib/menu-access.ts
new file mode 100644
index 000000000..f8459d08a
--- /dev/null
+++ b/web/src/lib/menu-access.ts
@@ -0,0 +1,143 @@
+import { dashboardNav } from '@/config/dashboard';
+import type { UserRole } from '@/types';
+
+/**
+ * Menu access: which left-menu sections a person sees. Hide only: a hidden
+ * section is off the menu, its pages still open from a link, and what the
+ * person can do there doesn't change.
+ *
+ * A section is named by its route under /dashboard ('content', 'audit',
+ * 'insights'…), the name the database keeps (00374).
+ */
+
+/** On everyone's menu, always: where the work is. */
+export const ALWAYS_ON_SECTION = 'action-center';
+
+/** The section a route belongs to: '/dashboard/content/plan' → 'content'. */
+export function menuSectionOf(href: string): string | null {
+ const [, root, section] = href.split('/');
+ return root === 'dashboard' && section ? section : null;
+}
+
+/** Every section of the left menu, in its order. */
+export const MENU_SECTIONS: string[] = dashboardNav
+ .flatMap((group) => group.items)
+ .map((item) => menuSectionOf(item.href))
+ .filter((section): section is string => section !== null);
+
+/**
+ * What a person works on or leads, with the sections that work needs. They
+ * follow the audiences on ansvisor.com › Solutions.
+ */
+export const WORK_AREAS = [
+ {
+ id: 'leaders',
+ sections: ['action-center', 'agent', 'insights', 'mentions', 'traffic', 'reports'],
+ },
+ {
+ id: 'aeo',
+ sections: ['action-center', 'content', 'audit', 'citations', 'traffic', 'reports'],
+ },
+ {
+ id: 'content',
+ sections: ['action-center', 'agent', 'content', 'prompts', 'citations', 'reports'],
+ },
+ {
+ id: 'brand',
+ sections: ['action-center', 'agent', 'insights', 'mentions', 'citations', 'reports'],
+ },
+ {
+ id: 'growth',
+ sections: ['action-center', 'agent', 'insights', 'prompts', 'citations', 'traffic', 'reports'],
+ },
+ {
+ id: 'product',
+ sections: ['action-center', 'agent', 'insights', 'prompts', 'mentions', 'shopping', 'reports'],
+ },
+ {
+ id: 'bizdev',
+ sections: ['action-center', 'agent', 'insights', 'prompts', 'mentions', 'citations', 'reports'],
+ },
+ {
+ id: 'developers',
+ sections: ['action-center', 'audit', 'prompts', 'citations', 'traffic', 'reports'],
+ },
+ {
+ id: 'analytics',
+ sections: [
+ 'action-center',
+ 'insights',
+ 'prompts',
+ 'mentions',
+ 'citations',
+ 'shopping',
+ 'traffic',
+ 'reports',
+ ],
+ },
+] as const;
+
+export type WorkAreaId = (typeof WORK_AREAS)[number]['id'];
+
+export const WORK_AREA_IDS: WorkAreaId[] = WORK_AREAS.map((area) => area.id);
+
+/** Sections some work area names: work areas narrow only these. */
+const AREA_SECTIONS = new Set<string>(WORK_AREAS.flatMap((area) => area.sections));
+
+export function isWorkAreaId(value: string): value is WorkAreaId {
+ return (WORK_AREA_IDS as string[]).includes(value);
+}
+
+/** The sections a set of work areas needs; every section for none. */
+export function workAreaSections(areas: readonly string[]): Set<string> | null {
+ const known = WORK_AREAS.filter((area) => areas.includes(area.id));
+ if (!known.length) return null;
+ return new Set(known.flatMap((area) => area.sections));
+}
+
+/** What decides a person's menu. */
+export interface MenuAccess {
+ role: UserRole;
+ /** The sections the person's role doesn't see (organization_menu_roles). */
+ roleHidden: readonly string[];
+ /** Sections shown for the person although the role hides them. */
+ shown: readonly string[];
+ /** Sections hidden for the person although the role shows them. */
+ hidden: readonly string[];
+ workAreas: readonly string[];
+}
+
+/**
+ * The sections of `sections` a person's menu leaves out: their role's,
+ * changed by their own exceptions, then narrowed to their work areas. A
+ * section no work area names (one added later) stays. Nobody takes a
+ * section off an admin's menu, only their own work areas narrow it; Action
+ * Center is never left out.
+ */
+export function hiddenMenuSections(
+ access: MenuAccess,
+ sections: readonly string[] = MENU_SECTIONS,
+): Set<string> {
+ const left = new Set<string>();
+ const areaSections = workAreaSections(access.workAreas);
+ for (const section of sections) {
+ if (section === ALWAYS_ON_SECTION) continue;
+ const byPerson =
+ access.role === 'admin' ||
+ (access.shown.includes(section)
+ ? true
+ : access.hidden.includes(section)
+ ? false
+ : !access.roleHidden.includes(section));
+ const byArea = !areaSections || !AREA_SECTIONS.has(section) || areaSections.has(section);
+ if (!byPerson || !byArea) left.add(section);
+ }
+ return left;
+}
+
+/** Known sections only, once each, in the menu's order; never Action Center. */
+export function cleanMenuSections(values: readonly string[]): string[] {
+ return MENU_SECTIONS.filter(
+ (section) => section !== ALWAYS_ON_SECTION && values.includes(section),
+ );
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index b9589ae2c..7af3610ca 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -3077,6 +3077,38 @@ export type Database = {
},
]
}
+ organization_menu_roles: {
+ Row: {
+ hidden_sections: string[]
+ organization_id: string
+ role: Database["public"]["Enums"]["user_role"]
+ updated_at: string
+ updated_by: string | null
+ }
+ Insert: {
+ hidden_sections?: string[]
+ organization_id: string
+ role: Database["public"]["Enums"]["user_role"]
+ updated_at?: string
+ updated_by?: string | null
+ }
+ Update: {
+ hidden_sections?: string[]
+ organization_id?: string
+ role?: Database["public"]["Enums"]["user_role"]
+ updated_at?: string
+ updated_by?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "organization_menu_roles_organization_id_fkey"
+ columns: ["organization_id"]
+ isOneToOne: false
+ referencedRelation: "organizations"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
organizations: {
Row: {
anthropic_api_key_encrypted: string | null
@@ -3228,33 +3260,48 @@ export type Database = {
profiles: {
Row: {
avatar_url: string | null
+ can_manage_menus: boolean
created_at: string
full_name: string | null
id: string
+ menu_hidden: string[]
+ menu_shown: string[]
onboarding_completed: boolean | null
organization_id: string | null
role: Database["public"]["Enums"]["user_role"]
updated_at: string
+ work_areas: string[]
+ work_areas_asked_at: string | null
}
Insert: {
avatar_url?: string | null
+ can_manage_menus?: boolean
created_at?: string
full_name?: string | null
id: string
+ menu_hidden?: string[]
+ menu_shown?: string[]
onboarding_completed?: boolean | null
organization_id?: string | null
role?: Database["public"]["Enums"]["user_role"]
updated_at?: string
+ work_areas?: string[]
+ work_areas_asked_at?: string | null
}
Update: {
avatar_url?: string | null
+ can_manage_menus?: boolean
created_at?: string
full_name?: string | null
id?: string
+ menu_hidden?: string[]
+ menu_shown?: string[]
onboarding_completed?: boolean | null
organization_id?: string | null
role?: Database["public"]["Enums"]["user_role"]
updated_at?: string
+ work_areas?: string[]
+ work_areas_asked_at?: string | null
}
Relationships: [
{