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(brands): open the workspace's settings from the brand pages (#1341)
Cihanf65acf3172f1
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 3e44fc8d3..cc38fcb45 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -6127,6 +6127,7 @@"addBrand": "Add Brand","showAllBrands": "Show My All Brands","visitBrandSettings": "Visit Brand Setting",+ "workspaceSettings": "Workspace Settings","editBrand": "Edit Brand","deleteBrand": "Delete Brand","noBrands": "No brands yet",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.test.tsxindex d185c5e6f..69a0be42f 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.test.tsx@@ -3,6 +3,7 @@ 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 { RoleProvider, type TeamRole } from '@/components/providers/role-provider';import BrandDetailLayout from './layout';const push = vi.fn();@@ -40,15 +41,17 @@ let root: Root;const params = (id: string) =>Object.assign(Promise.resolve({ id }), { status: 'fulfilled', value: { id } });-async function render(id = 'b1') {+async function render(id = 'b1', role: TeamRole = 'analyst') {await act(async () =>root.render(<NextIntlClientProvider locale="en" messages={messages}>- <Suspense>- <BrandDetailLayout params={params(id)}>- <p>page</p>- </BrandDetailLayout>- </Suspense>+ <RoleProvider role={role}>+ <Suspense>+ <BrandDetailLayout params={params(id)}>+ <p>page</p>+ </BrandDetailLayout>+ </Suspense>+ </RoleProvider></NextIntlClientProvider>,),);@@ -97,6 +100,15 @@ describe('the brand header', () => {expect(push).toHaveBeenCalledWith('/dashboard/brands/b2/prompts');});+ it('has Workspace Settings for admins and managers, not for others', async () => {+ const workspace = () =>+ [...container.querySelectorAll('button')].find((b) => b.textContent === 'Workspace Settings');+ await render('b1', 'manager');+ expect(workspace()).toBeDefined();+ await render('b1', 'analyst');+ expect(workspace()).toBeUndefined();+ });+it('stays put when the same brand is picked', async () => {await render();const items = await openSwitch();diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsxindex a24c5c393..233fdfad1 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsx@@ -7,6 +7,7 @@ import { useBrandStore } from '@/stores/use-brand-store';import { Button } from '@/components/ui/button';import { BrandAvatar } from '@/components/brand-avatar';import { BrandSwitchItems } from '@/components/layout/brand-switcher';+import { WorkspaceSettingsMenu } from '@/components/layout/workspace-settings-menu';import {DropdownMenu,DropdownMenuContent,@@ -49,8 +50,8 @@ export default function BrandDetailLayout({return (<div className="space-y-6">- {/* Brand header + back */}- <div className="flex items-center gap-4">+ {/* Brand header + back; Workspace Settings wraps below it on a phone. */}+ <div className="flex flex-wrap items-center gap-4"><Link href="/dashboard/brands"><Button variant="ghost" size="icon" aria-label="Back to brands list"><ArrowLeft className="h-4 w-4" />@@ -93,6 +94,9 @@ export default function BrandDetailLayout({</div></div>)}+ <div className="ml-auto">+ <WorkspaceSettingsMenu />+ </div></div>{/* Sub-nav */}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/_brands-client.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/_brands-client.tsxindex edf849675..a39d6a3fd 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/_brands-client.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/_brands-client.tsx@@ -4,6 +4,7 @@ import { useEffect } from 'react';import { useTranslations } from 'next-intl';import { Link } from '@/i18n/navigation';import { useBrandStore } from '@/stores/use-brand-store';+import { useUserRole } from '@/hooks/use-user-role';import { BrandCard } from '@/components/dashboard/brand-card';import { Button } from '@/components/ui/button';import type { Brand } from '@/types';@@ -35,6 +36,8 @@ export function BrandsClient({ brands }: BrandsClientProps) {function EmptyState() {const t = useTranslations('brands');+ // Only admins and managers add a brand (brands: admin/manager insert).+ const { canManage } = useUserRole();return (<div className="flex flex-col items-center justify-center rounded-xl border border-dashed py-20 text-center"><div className="mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-muted">@@ -42,12 +45,14 @@ function EmptyState() {</div><h2 className="text-lg font-semibold">{t('noBrands')}</h2><p className="mt-1 max-w-sm text-sm text-muted-foreground">{t('noBrandsDescription')}</p>- <Link href="/dashboard/brands/new" className="mt-6">- <Button className="gap-2">- <Plus className="h-4 w-4" />- {t('addBrand')}- </Button>- </Link>+ {canManage && (+ <Link href="/dashboard/brands/new" className="mt-6">+ <Button className="gap-2">+ <Plus className="h-4 w-4" />+ {t('addBrand')}+ </Button>+ </Link>+ )}</div>);}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/page.test.tsxnew file mode 100644index 000000000..1c9532301--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/page.test.tsx@@ -0,0 +1,95 @@+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';++const profile = vi.hoisted(() => ({ organization_id: 'org-1', role: 'admin' }));+vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({+ from: () => ({ select: () => ({ single: async () => ({ data: profile }) }) }),+ }),+}));+const brands = vi.hoisted(() => ({ list: [] as { id: string }[] }));+vi.mock('@/lib/actions/brand', () => ({ getBrands: async () => brands.list }));+vi.mock('@/lib/guards/plan-guard', () => ({+ getOrgPlan: async () => ({ limits: { maxBrands: 2 } }),+}));+const cloud = vi.hoisted(() => ({ on: false }));+vi.mock('@/config/plans', () => ({+ getPlan: () => ({ limits: { maxBrands: 2 } }),+ isCloud: () => cloud.on,+}));+vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children }: { href: string; children?: React.ReactNode }) => (+ <a href={href}>{children}</a>+ ),+}));+// The list and the menu beside the button have their own tests.+vi.mock('./_brands-client', () => ({ BrandsClient: () => null }));+vi.mock('@/components/layout/workspace-settings-menu', () => ({+ WorkspaceSettingsMenu: () => null,+}));++import BrandsPage from './page';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;++async function render() {+ const ui = await BrandsPage();+ await act(async () =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ {ui}+ </NextIntlClientProvider>,+ ),+ );+}+const links = () => [...container.querySelectorAll('a')].map((a) => a.getAttribute('href'));++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ profile.role = 'admin';+ brands.list = [];+ cloud.on = false;+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++// brands: admin/manager insert — the others would fail on the wizard's first step.+describe('the brands page', () => {+ it.each(['admin', 'manager'])('offers Add Brand to an %s', async (role) => {+ profile.role = role;+ await render();+ expect(links()).toEqual(['/dashboard/brands/new']);+ });++ it.each(['analyst', 'agency_partner'])('offers no Add Brand to an %s', async (role) => {+ profile.role = role;+ await render();+ expect(links()).toEqual([]);+ });++ it("sends a manager at the plan's limit to the upgrade, and no one else", async () => {+ brands.list = [{ id: 'b1' }, { id: 'b2' }];+ cloud.on = true;+ profile.role = 'manager';+ await render();+ expect(links()).toEqual(['/dashboard/settings?tab=billing']);++ act(() => root.unmount());+ root = createRoot(container);+ profile.role = 'analyst';+ await render();+ expect(links()).toEqual([]);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsxindex 544900e16..154567e53 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsx@@ -5,25 +5,30 @@ import { getBrands } from '@/lib/actions/brand';import { getPlan, isCloud as checkIsCloud } from '@/config/plans';import { getOrgPlan } from '@/lib/guards/plan-guard';import { BrandsClient } from './_brands-client';+import { WorkspaceSettingsMenu } from '@/components/layout/workspace-settings-menu';import { Button } from '@/components/ui/button';import { Crown, Plus } from 'lucide-react';function BrandsHeader({+ canManage,canAddBrand,needsUpgrade,}: {+ /** Admins and managers add brands (brands: admin/manager insert). */+ canManage: boolean;canAddBrand: boolean;needsUpgrade: boolean;}) {const t = useTranslations('brands');return (- <div className="flex items-center justify-between">+ <div className="flex flex-wrap items-center justify-between gap-4"><div><h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1><p className="text-muted-foreground text-sm">{t('description')}</p></div><div className="flex items-center gap-2">- {canAddBrand ? (+ <WorkspaceSettingsMenu />+ {!canManage ? null : canAddBrand ? (<Link href="/dashboard/brands/new"><Button className="gap-2"><Plus className="h-4 w-4" />@@ -46,9 +51,13 @@ function BrandsHeader({export default async function BrandsPage() {const supabase = await createClient();- const { data: profile } = await supabase.from('profiles').select('organization_id').single();+ const { data: profile } = await supabase+ .from('profiles')+ .select('organization_id, role')+ .single();const orgId = profile?.organization_id;+ const canManage = profile?.role === 'admin' || profile?.role === 'manager';// getOrgPlan, not getPlan(org.plan): the limit shown here must be the one// createBrand enforces, Enterprise plan_overrides included. Reading the bare@@ -64,7 +73,7 @@ export default async function BrandsPage() {return (<div className="space-y-6">- <BrandsHeader canAddBrand={canAddBrand} needsUpgrade={needsUpgrade} />+ <BrandsHeader canManage={canManage} canAddBrand={canAddBrand} needsUpgrade={needsUpgrade} /><BrandsClient brands={brands} /></div>);diff --git a/web/src/components/layout/workspace-settings-menu.test.tsx b/web/src/components/layout/workspace-settings-menu.test.tsxnew file mode 100644index 000000000..5dfb4c88e--- /dev/null+++ b/web/src/components/layout/workspace-settings-menu.test.tsx@@ -0,0 +1,80 @@+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 { RoleProvider, type TeamRole } from '@/components/providers/role-provider';+import { WorkspaceSettingsMenu } from './workspace-settings-menu';++const push = vi.fn();+vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push }) }));+const plan = vi.hoisted(() => ({ isCloud: true }));+vi.mock('@/components/providers/plan-provider', () => ({ usePlanContext: () => plan }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;++async function render(role: TeamRole) {+ await act(async () =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <RoleProvider role={role}>+ <WorkspaceSettingsMenu />+ </RoleProvider>+ </NextIntlClientProvider>,+ ),+ );+}+const trigger = () => container.querySelector<HTMLButtonElement>('button');+async function openMenu() {+ await act(async () => {+ trigger()!.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ trigger()!.click();+ });+ return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];+}++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ plan.isCloud = true;+ push.mockReset();+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ document.body.replaceChildren();+});++describe('WorkspaceSettingsMenu', () => {+ it("opens the workspace's settings sections, each at its own address", async () => {+ await render('admin');+ expect(trigger()!.textContent).toBe('Workspace Settings');+ const items = await openMenu();+ expect(items.map((i) => i.textContent)).toEqual(['Account', 'Organization', 'Team', 'Billing']);+ await act(async () => items[2].click());+ expect(push).toHaveBeenCalledWith('/dashboard/settings/team');+ });++ it('shows for managers too', async () => {+ await render('manager');+ expect(trigger()).not.toBeNull();+ });++ it.each(['analyst', 'agency_partner'] as const)('is hidden from an %s', async (role) => {+ await render(role);+ expect(container.innerHTML).toBe('');+ });++ it('leaves Billing out where settings have none (self-host)', async () => {+ plan.isCloud = false;+ await render('admin');+ const items = await openMenu();+ expect(items.map((i) => i.textContent)).toEqual(['Account', 'Organization', 'Team']);+ });+});diff --git a/web/src/components/layout/workspace-settings-menu.tsx b/web/src/components/layout/workspace-settings-menu.tsxnew file mode 100644index 000000000..48f8a12a0--- /dev/null+++ b/web/src/components/layout/workspace-settings-menu.tsx@@ -0,0 +1,60 @@+'use client';++import { useTranslations } from 'next-intl';+import { useRouter } from '@/i18n/navigation';+import { useUserRole } from '@/hooks/use-user-role';+import { usePlanContext } from '@/components/providers/plan-provider';+import {+ hasSettingsSection,+ type SettingsSection,+} from '@/app/[locale]/(dashboard)/dashboard/settings/_sections';+import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { Building2, ChevronDown, CreditCard, Settings, UserRound, Users } from 'lucide-react';++/** The workspace's own sections, in the settings page's order. */+const SECTIONS = [+ { id: 'account', icon: UserRound },+ { id: 'organization', icon: Building2 },+ { id: 'team', icon: Users },+ { id: 'billing', icon: CreditCard },+] satisfies { id: SettingsSection; icon: typeof Settings }[];++/**+ * Workspace Settings, top right of the brands page and a brand's page: the+ * settings that aren't a brand's (account, organization, team, billing), each+ * opening its section of /dashboard/settings. Admins and managers only;+ * Billing only where the settings page has it (Ansvisor Cloud).+ */+export function WorkspaceSettingsMenu() {+ const t = useTranslations('settings');+ const tBrands = useTranslations('brands');+ const router = useRouter();+ const { canManage } = useUserRole();+ const { isCloud } = usePlanContext();++ if (!canManage) return null;++ return (+ <DropdownMenu>+ <DropdownMenuTrigger render={<Button variant="outline" className="gap-2" />}>+ <Settings className="h-4 w-4" />+ {tBrands('workspaceSettings')}+ <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-48">+ {SECTIONS.filter((s) => hasSettingsSection(s.id, { isCloud })).map(({ id, icon: Icon }) => (+ <DropdownMenuItem key={id} onClick={() => router.push(`/dashboard/settings/${id}`)}>+ <Icon className="mr-2 h-4 w-4 text-muted-foreground" />+ {t(id)}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}