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
fix(server): check the caller's role on opportunity and suggestion changes (#1763)
Cihanaaf831f14ebf
diff --git a/server/src/lib/access.js b/server/src/lib/access.jsindex 66d7e67ac..8f06ccb42 100644--- a/server/src/lib/access.js+++ b/server/src/lib/access.js@@ -34,6 +34,33 @@ function accessError(message, status, code) {export const NOT_IN_WORKSPACE = "This brand isn't in your workspace";const notInWorkspace = () => accessError(NOT_IN_WORKSPACE, 403, 'not_in_workspace');+/**+ * The roles that may add prompts and topics, change settings and delete for+ * good — the admin-or-manager rule the database keeps on those tables.+ */+export const MANAGER_ROLES = Object.freeze(['admin', 'manager']);++/**+ * Assert that the caller's role is one of `roles`. The writes here bypass Row+ * Level Security, so a route the database keeps to some roles checks them+ * itself; run it after the resource's own access check, so another+ * organization's resource still reads as not found or not in the workspace.+ * @param {string} userId+ * @param {readonly string[]} roles+ * @param {string} message what the caller reads when refused (403 `forbidden`)+ * @returns {Promise<string>} the caller's role+ */+export async function assertRole(userId, roles, message) {+ const { data: profile, error } = await supabaseAdmin+ .from('profiles')+ .select('role')+ .eq('id', userId)+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!roles.includes(profile?.role)) throw accessError(message, 403, 'forbidden');+ return profile.role;+}+/*** Assert that `brandId` belongs to the caller's organization.* @returns {Promise<{ brand: object, orgId: string|null }>}diff --git a/server/src/lib/access.test.js b/server/src/lib/access.test.jsindex dafacb659..36311c8f4 100644--- a/server/src/lib/access.test.js+++ b/server/src/lib/access.test.js@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-// The brand and the caller's organization, as the database answers them.-const state = vi.hoisted(() => ({ brand: null, orgId: null }));+// The brand, the caller's organization and profile, as the database answers them.+const state = vi.hoisted(() => ({ brand: null, orgId: null, profile: null, profileError: null }));vi.mock('../config/supabase.js', () => ({default: {@@ -10,6 +10,7 @@ vi.mock('../config/supabase.js', () => ({select: () => chain,eq: () => chain,single: async () => ({ data: state.brand, error: null }),+ maybeSingle: async () => ({ data: state.profile, error: state.profileError }),};return chain;},@@ -17,11 +18,14 @@ vi.mock('../config/supabase.js', () => ({}));vi.mock('./plan-guard.js', () => ({ getOrgIdForUser: async () => state.orgId }));-const { assertBrandAccess, NOT_IN_WORKSPACE } = await import('./access.js');+const { assertBrandAccess, assertRole, MANAGER_ROLES, NOT_IN_WORKSPACE } =+ await import('./access.js');beforeEach(() => {state.brand = { id: 'b1', organization_id: 'org-1' };state.orgId = 'org-1';+ state.profile = { role: 'manager' };+ state.profileError = null;});describe('assertBrandAccess', () => {@@ -44,3 +48,30 @@ describe('assertBrandAccess', () => {await expect(assertBrandAccess('b1', 'u1')).rejects.toMatchObject({ status: 404 });});});++describe('assertRole', () => {+ it('lets a role on the list through, and says which it is', async () => {+ await expect(assertRole('u1', MANAGER_ROLES, 'No.')).resolves.toBe('manager');+ });++ it('refuses any other role with the message, as a 403', async () => {+ state.profile = { role: 'analyst' };+ await expect(+ assertRole('u1', MANAGER_ROLES, 'Only admins and managers can delete opportunities.'),+ ).rejects.toMatchObject({+ message: 'Only admins and managers can delete opportunities.',+ status: 403,+ code: 'forbidden',+ });+ });++ it('refuses a caller without a profile', async () => {+ state.profile = null;+ await expect(assertRole('u1', MANAGER_ROLES, 'No.')).rejects.toMatchObject({ status: 403 });+ });++ it('fails, not refuses, when the profile cannot be read', async () => {+ state.profileError = { message: 'connection reset' };+ await expect(assertRole('u1', MANAGER_ROLES, 'No.')).rejects.toThrow('connection reset');+ });+});diff --git a/server/src/routes/content-roles.test.js b/server/src/routes/content-roles.test.jsnew file mode 100644index 000000000..c86073a05--- /dev/null+++ b/server/src/routes/content-roles.test.js@@ -0,0 +1,201 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * Who may change Content Opportunities (2026-10-29): any member records an+ * opportunity's progress; dismissing one, bringing a dismissed one back, any+ * bulk change and deleting are for admins and managers, as the database's+ * rules on content_opportunities. A refused call writes nothing.+ */++const assertOpportunityAccess = vi.fn();+const assertOpportunitiesAccess = vi.fn();+let rows;+let writes;+let server;+let baseUrl;++/** A query on `table`: every filter returns it, and it reads as the table's rows. */+function query(table) {+ const answer = () => ({ data: rows[table] ?? null, error: null });+ const chain = new Proxy(+ {},+ {+ get: (_t, op) => {+ if (op === 'then')+ return (resolve, reject) => Promise.resolve(answer()).then(resolve, reject);+ if (op === 'maybeSingle' || op === 'single') return async () => answer();+ if (op === 'update' || op === 'delete') {+ return (values) => {+ writes.push({ table, op, values });+ return chain;+ };+ }+ return () => chain;+ },+ },+ );+ return chain;+}++async function startApp() {+ vi.resetModules();+ // As the other content route tests: the jobs and workers aren't loaded.+ vi.doMock('../lib/plan-guard.js', () => ({+ PlanLimitError: class PlanLimitError extends Error {},+ requireFeature: () => (req, res, next) => next(),+ enforceBriefQuota: vi.fn(),+ getBriefQuotaStatus: vi.fn(),+ getContentUsage: vi.fn(),+ getOpportunityRequestAllowance: vi.fn(),+ getOrgIdForUser: vi.fn(),+ }));+ vi.doMock('../lib/job-manager.js', () => ({ createJob: vi.fn(), getJob: vi.fn() }));+ vi.doMock('../lib/job-runner.js', () => ({ runContentJob: vi.fn() }));+ // The real role check, on the profile below; the organization checks pass.+ vi.doMock('../lib/access.js', async (importOriginal) => ({+ ...(await importOriginal()),+ assertOpportunityAccess,+ assertOpportunitiesAccess,+ }));+ vi.doMock('../config/supabase.js', () => ({ default: { from: (table) => query(table) } }));+ vi.doMock('../lib/prompt-clusters.js', () => ({ loadClusters: vi.fn() }));+ vi.doMock('../lib/action-center/from-opportunity.js', () => ({+ OPPORTUNITY_ACTION_KIND: 'content_opportunity',+ sendToActionCenter: vi.fn(),+ }));+ vi.doMock('../lib/ai-provider.js', () => ({ resolveModel: vi.fn() }));+ vi.doMock('../lib/logger.js', () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), fatal: vi.fn() };+ return { default: logger, logger };+ });++ const { default: router } = await import('./content.js');+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ req.log = { error: vi.fn(), info: vi.fn() };+ next();+ });+ app.use('/api/content', router);+ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/content`;+}++const send = (method, path, body) =>+ fetch(`${baseUrl}${path}`, {+ method,+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++const OPPORTUNITY = {+ id: 'o1',+ brand_id: 'b1',+ prompt_id: null,+ title: 'Pricing comparison',+ description: 'Compare the plans.',+ type: 'comparison',+ impact: 'high',+ opportunity_score: '0.8',+ source_data: {},+ brief: null,+ status: 'new',+ updated_at: '2026-10-27T08:00:00Z',+};++/** The caller is `role`; the opportunity has `status` now. */+function given(role, status = 'new') {+ rows.profiles = { role };+ assertOpportunityAccess.mockResolvedValue({ ...OPPORTUNITY, status });+ rows.content_opportunities = { ...OPPORTUNITY, status };+}++const changed = () => writes.filter((w) => w.table === 'content_opportunities');++beforeEach(async () => {+ vi.clearAllMocks();+ rows = { competitors: [] };+ writes = [];+ assertOpportunitiesAccess.mockResolvedValue([{ id: 'o1', brand_id: 'b1' }]);+ await startApp();+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('PATCH /api/content/:id/status', () => {+ it("records an analyst's progress", async () => {+ given('analyst');+ const res = await send('PATCH', '/o1/status', { status: 'in_progress' });+ expect(res.status).toBe(200);+ expect(changed()).toHaveLength(1);+ });++ it('refuses an analyst a dismissal, without a write', async () => {+ given('analyst');+ const res = await send('PATCH', '/o1/status', { status: 'dismissed', reason: 'not_relevant' });+ expect(res.status).toBe(403);+ expect(await res.json()).toMatchObject({+ details: 'Only admins and managers can dismiss an opportunity or bring one back.',+ });+ expect(changed()).toEqual([]);+ });++ it('refuses an agency partner bringing a dismissed one back', async () => {+ given('agency_partner', 'dismissed');+ const res = await send('PATCH', '/o1/status', { status: 'new' });+ expect(res.status).toBe(403);+ expect(changed()).toEqual([]);+ });++ it('lets a manager dismiss one', async () => {+ given('manager');+ const res = await send('PATCH', '/o1/status', { status: 'dismissed' });+ expect(res.status).toBe(200);+ expect(changed()[0].values).toMatchObject({ status: 'dismissed' });+ });+});++describe('POST /api/content/bulk/status and /bulk/delete', () => {+ it('refuses an analyst a bulk change, even to done', async () => {+ given('analyst');+ const res = await send('POST', '/bulk/status', { ids: ['o1'], status: 'done' });+ expect(res.status).toBe(403);+ expect(await res.json()).toMatchObject({+ details: 'Only admins and managers can change opportunities in bulk.',+ });+ expect(changed()).toEqual([]);+ });++ it('refuses an analyst deleting, without a write', async () => {+ given('analyst');+ const res = await send('POST', '/bulk/delete', { ids: ['o1'] });+ expect(res.status).toBe(403);+ expect(await res.json()).toMatchObject({+ details: 'Only admins and managers can delete opportunities.',+ });+ expect(changed()).toEqual([]);+ });++ it('lets an admin change and delete in bulk', async () => {+ given('admin');+ rows.content_opportunities = [{ id: 'o1' }];+ expect((await send('POST', '/bulk/status', { ids: ['o1'], status: 'done' })).status).toBe(200);+ expect((await send('POST', '/bulk/delete', { ids: ['o1'] })).status).toBe(200);+ expect(changed().map((w) => w.op)).toEqual(['update', 'delete']);+ });++ it('says another organization’s opportunities aren’t in the workspace before the role', async () => {+ given('analyst');+ assertOpportunitiesAccess.mockRejectedValue(+ Object.assign(new Error("This brand isn't in your workspace"), { status: 403 }),+ );+ const res = await send('POST', '/bulk/delete', { ids: ['o1'] });+ expect(await res.json()).toMatchObject({ details: "This brand isn't in your workspace" });+ });+});diff --git a/server/src/routes/content.js b/server/src/routes/content.jsindex cdacc0885..8b9601eaa 100644--- a/server/src/routes/content.js+++ b/server/src/routes/content.js@@ -20,10 +20,12 @@ import { selectInChunks } from '../lib/chunked-in.js';import { isRedirect, postJson } from '../lib/safe-post.js';import { webhookTestLimiter } from '../middleware/rate-limiter.js';import {+ MANAGER_ROLES,assertBrandAccess,assertOpportunitiesAccess,assertOpportunityAccess,assertPromptAccess,+ assertRole,NOT_IN_WORKSPACE,} from '../lib/access.js';import { loadClusters } from '../lib/prompt-clusters.js';@@ -756,7 +758,8 @@ router.get('/brand/:brandId/topics', async (req, res) => {/*** POST /api/content/bulk/status- * Update the status of multiple opportunities at once.+ * Update the status of multiple opportunities at once: admins and managers,+ * as the database's update rule on content_opportunities.*/router.post('/bulk/status', async (req, res) => {try {@@ -774,6 +777,11 @@ router.post('/bulk/status', async (req, res) => {}await assertOpportunitiesAccess(ids, req.user.id);+ await assertRole(+ req.user.id,+ MANAGER_ROLES,+ 'Only admins and managers can change opportunities in bulk.',+ );const { data, error } = await supabaseAdmin.from('content_opportunities')@@ -803,7 +811,8 @@ router.post('/bulk/status', async (req, res) => {* The generated brief lives on the opportunity row, so deleting takes it with* it. `brief_usage.opportunity_id` is ON DELETE SET NULL, so the metered usage* record survives and quota already spent stays spent — deleting must not hand- * back a brief allowance.+ * back a brief allowance. Admins and managers only, as the database's delete+ * rule.*/router.post('/bulk/delete', async (req, res) => {try {@@ -814,6 +823,11 @@ router.post('/bulk/delete', async (req, res) => {}await assertOpportunitiesAccess(ids, req.user.id);+ await assertRole(+ req.user.id,+ MANAGER_ROLES,+ 'Only admins and managers can delete opportunities.',+ );const { data, error } = await supabaseAdmin.from('content_opportunities')@@ -988,7 +1002,8 @@ router.post('/bulk/send-webhook', async (req, res) => {/*** PATCH /api/content/:id/status- * Update the status of an opportunity.+ * Update the status of an opportunity. Any member records progress;+ * dismissing one, or moving a dismissed one back, is for admins and managers.*/router.patch('/:id/status', async (req, res) => {try {@@ -1003,6 +1018,13 @@ router.patch('/:id/status', async (req, res) => {}let current = await assertOpportunityAccess(id, req.user.id);+ if (status === 'dismissed' || current.status === 'dismissed') {+ await assertRole(+ req.user.id,+ MANAGER_ROLES,+ 'Only admins and managers can dismiss an opportunity or bring one back.',+ );+ }// Why it was dismissed (CONTENT-006) rides in source_data, which other// writers touch too (an Action Center send, a duplicate merge). The rowdiff --git a/server/src/routes/prompts.js b/server/src/routes/prompts.jsindex d4ea0f8f8..5cd92b10e 100644--- a/server/src/routes/prompts.js+++ b/server/src/routes/prompts.js@@ -2,6 +2,7 @@ import { Router } from 'express';import { NoObjectGeneratedError, generateObject } from 'ai';import { z } from 'zod';import supabaseAdmin from '../config/supabase.js';+import { MANAGER_ROLES, assertRole } from '../lib/access.js';import { resolveModel } from '../lib/ai-provider.js';import { decide, isDeciderConfigured } from '../lib/decider.js';import { classifyQueryIntents } from '../lib/intent-extraction.js';@@ -678,6 +679,9 @@ router.get('/untracked-queries/:brandId', async (req, res) => {}});+/** Who may dismiss a prompt suggestion: every role but agency partners, as the table's update rule. */+const DISMISS_SUGGESTION_ROLES = ['admin', 'manager', 'analyst'];+router.post('/suggestions/:id/dismiss', async (req, res) => {try {const { data: suggestion } = await supabaseAdmin@@ -687,6 +691,11 @@ router.post('/suggestions/:id/dismiss', async (req, res) => {.single();if (!suggestion) return res.status(404).json({ error: 'Not found' });await assertBrandAccess(suggestion.brand_id, req.user.id);+ await assertRole(+ req.user.id,+ DISMISS_SUGGESTION_ROLES,+ 'Only admins, managers and analysts can dismiss prompt suggestions.',+ );const { error } = await supabaseAdmin.from('prompt_suggestions')@@ -714,6 +723,8 @@ router.post('/suggestions/:id/accept', async (req, res) => {.single();if (!suggestion) return res.status(404).json({ error: 'Not found' });await assertBrandAccess(suggestion.brand_id, req.user.id);+ // The prompt itself is added by admins and managers only (the prompts table's rule).+ await assertRole(req.user.id, MANAGER_ROLES, 'Only admins and managers can add prompts.');const { error } = await supabaseAdmin.from('prompt_suggestions')diff --git a/server/src/routes/suggestions-roles.test.js b/server/src/routes/suggestions-roles.test.jsnew file mode 100644index 000000000..ad4d5e737--- /dev/null+++ b/server/src/routes/suggestions-roles.test.js@@ -0,0 +1,171 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * Who may decide on a suggestion (2026-10-29): a prompt suggestion is+ * dismissed by anyone but an agency partner (the table's update rule) and+ * accepted only by those who may add prompts, admins and managers; a topic+ * suggestion is accepted or dismissed by admins and managers, as the Topics+ * page offers it. A refused call writes nothing.+ */++let role;+let writes;+let server;+let baseUrl;++/** The brand is the caller's; the suggestion is the brand's; the caller is `role`. */+function query(table) {+ const answer = () => {+ if (table === 'profiles') return { data: { organization_id: 'o1', role }, error: null };+ if (table === 'brands') return { data: { id: 'b1', organization_id: 'o1' }, error: null };+ if (table.endsWith('_suggestions')) return { data: { brand_id: 'b1' }, error: null };+ return { data: null, error: null };+ };+ const chain = new Proxy(+ {},+ {+ get: (_t, op) => {+ if (op === 'then')+ return (resolve, reject) => Promise.resolve(answer()).then(resolve, reject);+ if (op === 'maybeSingle' || op === 'single') return async () => answer();+ if (op === 'update') {+ return (values) => {+ writes.push({ table, values });+ return chain;+ };+ }+ return () => chain;+ },+ },+ );+ return chain;+}++async function startApp() {+ vi.resetModules();+ vi.doMock('../config/supabase.js', () => ({ default: { from: (table) => query(table) } }));+ vi.doMock('../lib/plan-guard.js', () => ({+ PlanLimitError: class extends Error {},+ enforceFeature: vi.fn(),+ reserveAiBudget: vi.fn(),+ getImproveQuotaStatus: vi.fn(),+ requireFeature: () => (req, res, next) => next(),+ reserveRelevanceAllowance: vi.fn(),+ settleRelevanceUsage: vi.fn(),+ getOrgIdForUser: async () => 'o1',+ }));+ vi.doMock('ai', () => ({+ generateObject: vi.fn(),+ NoObjectGeneratedError: class extends Error {},+ }));+ vi.doMock('../lib/ai-provider.js', () => ({ resolveModel: vi.fn() }));+ vi.doMock('../lib/gsc-suggestions.js', () => ({ getGscSuggestionCandidates: vi.fn() }));+ vi.doMock('../lib/ga-suggestions.js', () => ({ getGaSuggestionCandidates: vi.fn() }));+ vi.doMock('../lib/catalog-suggestions.js', () => ({ getCatalogSuggestionCandidates: vi.fn() }));+ vi.doMock('../lib/web-research.js', () => ({ webResearch: vi.fn() }));+ vi.doMock('../lib/action-center/from-topic-opportunity.js', () => ({+ sendTopicOpportunityToActionCenter: vi.fn(),+ }));+ vi.doMock('../lib/action-center/from-topic-gap.js', () => ({+ sendTopicGapToActionCenter: vi.fn(),+ }));+ vi.doMock('../lib/logger.js', () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), fatal: vi.fn() };+ return { default: logger, logger };+ });++ const { default: prompts } = await import('./prompts.js');+ const { default: topics } = await import('./topics.js');+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ req.log = { error: vi.fn(), info: vi.fn() };+ next();+ });+ app.use('/api/prompts', prompts);+ app.use('/api/topics', topics);+ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api`;+}++const post = (path, body = {}) =>+ fetch(`${baseUrl}${path}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++beforeEach(async () => {+ writes = [];+ await startApp();+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('POST /api/prompts/suggestions/:id/dismiss', () => {+ it('refuses an agency partner, without a write', async () => {+ role = 'agency_partner';+ const res = await post('/prompts/suggestions/s1/dismiss');+ expect(res.status).toBe(403);+ expect(await res.json()).toEqual({+ error: 'Only admins, managers and analysts can dismiss prompt suggestions.',+ });+ expect(writes).toEqual([]);+ });++ it('lets an analyst dismiss one', async () => {+ role = 'analyst';+ const res = await post('/prompts/suggestions/s1/dismiss');+ expect(res.status).toBe(200);+ expect(writes).toEqual([+ { table: 'prompt_suggestions', values: expect.objectContaining({ status: 'dismissed' }) },+ ]);+ });+});++describe('POST /api/prompts/suggestions/:id/accept', () => {+ it('refuses an analyst, who cannot add prompts', async () => {+ role = 'analyst';+ const res = await post('/prompts/suggestions/s1/accept', { promptId: 'p1' });+ expect(res.status).toBe(403);+ expect(await res.json()).toEqual({ error: 'Only admins and managers can add prompts.' });+ expect(writes).toEqual([]);+ });++ it('records a manager’s accept', async () => {+ role = 'manager';+ const res = await post('/prompts/suggestions/s1/accept', { promptId: 'p1' });+ expect(res.status).toBe(200);+ expect(writes[0].values).toMatchObject({ status: 'added', added_prompt_id: 'p1' });+ });+});++describe('POST /api/topics/suggestions/:id/accept and /dismiss', () => {+ it('refuses an analyst both, without a write', async () => {+ role = 'analyst';+ for (const [path, body] of [+ ['/topics/suggestions/s1/accept', { topicId: 't1' }],+ ['/topics/suggestions/s1/dismiss', {}],+ ]) {+ const res = await post(path, body);+ expect(res.status, path).toBe(403);+ expect(await res.json(), path).toEqual({+ error: 'Only admins and managers can accept or dismiss topic suggestions.',+ });+ }+ expect(writes).toEqual([]);+ });++ it('lets an admin accept and dismiss', async () => {+ role = 'admin';+ expect((await post('/topics/suggestions/s1/accept', { topicId: 't1' })).status).toBe(200);+ expect((await post('/topics/suggestions/s1/dismiss')).status).toBe(200);+ expect(writes.map((w) => w.values.status)).toEqual(['added', 'dismissed']);+ });+});diff --git a/server/src/routes/topics.js b/server/src/routes/topics.jsindex a96fda97c..926e4b430 100644--- a/server/src/routes/topics.js+++ b/server/src/routes/topics.js@@ -2,7 +2,7 @@ import { Router } from 'express';import { generateObject } from 'ai';import { z } from 'zod';import supabaseAdmin from '../config/supabase.js';-import { assertBrandAccess } from '../lib/access.js';+import { MANAGER_ROLES, assertBrandAccess, assertRole } from '../lib/access.js';import { requireFeature } from '../lib/plan-guard.js';import { boundedBrandSetup, boundedTopicName, brandSetupSchema } from '../lib/brand-setup-input.js';import { resolveModel } from '../lib/ai-provider.js';@@ -360,9 +360,14 @@ router.post(},);+/** What a member without the role for a topic suggestion reads. */+const TOPIC_SUGGESTION_ROLE_MESSAGE =+ 'Only admins and managers can accept or dismiss topic suggestions.';+/*** POST /api/topics/suggestions/:id/dismiss* Marks a suggestion dismissed; its name is excluded from future refreshes.+ * Admins and managers only, as the Topics page offers it.*/router.post('/suggestions/:id/dismiss', async (req, res) => {try {@@ -373,6 +378,7 @@ router.post('/suggestions/:id/dismiss', async (req, res) => {.single();if (!suggestion) return res.status(404).json({ error: 'Not found' });await assertBrandAccess(suggestion.brand_id, req.user.id);+ await assertRole(req.user.id, MANAGER_ROLES, TOPIC_SUGGESTION_ROLE_MESSAGE);const { error } = await supabaseAdmin.from('topic_suggestions')@@ -391,7 +397,8 @@ router.post('/suggestions/:id/dismiss', async (req, res) => {* POST /api/topics/suggestions/:id/accept* Body: { topicId } — the topic the web app just created via the singular* createTopic action. This only records the outcome; topic creation itself- * happens RLS-checked in the web app.+ * happens RLS-checked in the web app. Admins and managers only, as the+ * Topics page offers it.*/router.post('/suggestions/:id/accept', async (req, res) => {try {@@ -406,6 +413,7 @@ router.post('/suggestions/:id/accept', async (req, res) => {.single();if (!suggestion) return res.status(404).json({ error: 'Not found' });await assertBrandAccess(suggestion.brand_id, req.user.id);+ await assertRole(req.user.id, MANAGER_ROLES, TOPIC_SUGGESTION_ROLE_MESSAGE);const { error } = await supabaseAdmin.from('topic_suggestions')diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsxindex f8dfde8fb..3f070be71 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.test.tsx@@ -37,7 +37,11 @@ const plan = vi.hoisted(() => ({setPlanRowPriority: vi.fn(async () => undefined),}));vi.mock('@/lib/actions/content-plan', () => plan);-vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => ({ canManage: true }) }));+// An admin or a manager unless a test says otherwise.+const viewer = vi.hoisted(() => ({ canManage: true }));+vi.mock('@/hooks/use-user-role', () => ({+ useUserRole: () => ({ canManage: viewer.canManage }),+}));const brandState = vi.hoisted(() => ({activeBrandId: 'b1',brands: [{ id: 'b1', name: 'Acme', slug: 'acme', siteType: 'b2b' }],@@ -134,6 +138,7 @@ const rowItem = async (item: string) => {beforeEach(() => {vi.clearAllMocks();+ viewer.canManage = true;opened.newOpportunities = false;opened.newContent = false;window.history.replaceState(null, '', '/dashboard/content');@@ -290,3 +295,31 @@ describe('Content Opportunities on an active plan', () => {expect(openUpgrade).not.toHaveBeenCalled();});});++describe('Content Opportunities for an analyst or an agency partner', () => {+ const labels = () =>+ [...document.body.querySelectorAll('button, [role="menuitem"]')].map((el) =>+ el.textContent?.trim(),+ );++ it('keeps Send All in the bulk bar, without Done, Dismiss All or Delete', async () => {+ viewer.canManage = false;+ await render(false);+ await pickRow();+ expect(labels()).toContain('Send All');+ for (const label of ['Done', 'Dismiss All', 'Delete']) {+ expect(labels(), label).not.toContain(label);+ }+ });++ it("leaves Dismiss out of the row's menu", async () => {+ viewer.canManage = false;+ await render(false);+ const trigger = container.querySelector<HTMLElement>(+ '[aria-label="Actions for Office coffee subscriptions"]',+ )!;+ await act(async () => trigger.click());+ expect(labels()).toContain('Send to Workflow');+ expect(labels()).not.toContain('Dismiss');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsxindex 3d8f715e8..4aec7058d 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/page.tsx@@ -1431,91 +1431,99 @@ export default function ContentPage() {{t('bulk.sendAll')}</Button>- <Button- variant="outline"- size="sm"- className="h-7 text-xs gap-1.5"- onClick={guard(handleBulkDone, { action: tActions('markOpportunitiesDone') })}- disabled={bulkSending}- >- <Check className="h-3 w-3" />- {t('status.done')}- </Button>-- <Dialog onOpenChange={confirmUnlessLocked(tActions('dismissOpportunities'))}>- <DialogTrigger- render={- <Button- variant="outline"- size="sm"- className="h-7 text-xs gap-1.5 text-muted-foreground"- disabled={bulkSending}- />- }- >- <X className="h-3 w-3" />- {t('bulk.dismissAll')}- </DialogTrigger>- <DialogContent className="sm:max-w-sm">- <DialogHeader>- <DialogTitle>{t('bulk.dismissAllTitle')}</DialogTitle>- <DialogDescription>- {t('bulk.dismissAllConfirm', { count: selectedIds.size })}- </DialogDescription>- </DialogHeader>- <DialogFooter>- <DialogClose render={<Button variant="outline" />}>- {t('cancel')}- </DialogClose>- <DialogClose- render={<Button variant="destructive" onClick={handleBulkDismiss} />}+ {/* Bulk changes, dismissing and deleting are for admins and+ managers, as the server and the database allow them. */}+ {canManage && (+ <>+ <Button+ variant="outline"+ size="sm"+ className="h-7 text-xs gap-1.5"+ onClick={guard(handleBulkDone, {+ action: tActions('markOpportunitiesDone'),+ })}+ disabled={bulkSending}+ >+ <Check className="h-3 w-3" />+ {t('status.done')}+ </Button>++ <Dialog onOpenChange={confirmUnlessLocked(tActions('dismissOpportunities'))}>+ <DialogTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="h-7 text-xs gap-1.5 text-muted-foreground"+ disabled={bulkSending}+ />+ }>+ <X className="h-3 w-3" />{t('bulk.dismissAll')}- </DialogClose>- </DialogFooter>- </DialogContent>- </Dialog>-- {/* Last in the row, and the only destructive-styled trigger:- this one does not move a row, it removes it. */}- <Dialog onOpenChange={confirmUnlessLocked(tActions('deleteOpportunities'))}>- <DialogTrigger- render={- <Button- variant="outline"- size="sm"- className="h-7 text-xs gap-1.5 text-destructive hover:text-destructive"- disabled={bulkSending}- />- }- >- <Trash2 className="h-3 w-3" />- {t('bulk.deleteAll')}- </DialogTrigger>- <DialogContent className="sm:max-w-sm">- <DialogHeader>- <DialogTitle>{t('bulk.deleteAllTitle')}</DialogTitle>- <DialogDescription>- {t('bulk.deleteAllConfirm', { count: selectedIds.size })}- {selectedWithBrief > 0 && (- <span className="mt-2 block font-medium text-foreground">- {t('bulk.deleteAllBriefWarning', { count: selectedWithBrief })}- </span>- )}- </DialogDescription>- </DialogHeader>- <DialogFooter>- <DialogClose render={<Button variant="outline" />}>- {t('cancel')}- </DialogClose>- <DialogClose- render={<Button variant="destructive" onClick={handleBulkDelete} />}+ </DialogTrigger>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>{t('bulk.dismissAllTitle')}</DialogTitle>+ <DialogDescription>+ {t('bulk.dismissAllConfirm', { count: selectedIds.size })}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <DialogClose render={<Button variant="outline" />}>+ {t('cancel')}+ </DialogClose>+ <DialogClose+ render={<Button variant="destructive" onClick={handleBulkDismiss} />}+ >+ {t('bulk.dismissAll')}+ </DialogClose>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {/* Last in the row, and the only destructive-styled trigger:+ this one does not move a row, it removes it. */}+ <Dialog onOpenChange={confirmUnlessLocked(tActions('deleteOpportunities'))}>+ <DialogTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="h-7 text-xs gap-1.5 text-destructive hover:text-destructive"+ disabled={bulkSending}+ />+ }>+ <Trash2 className="h-3 w-3" />{t('bulk.deleteAll')}- </DialogClose>- </DialogFooter>- </DialogContent>- </Dialog>+ </DialogTrigger>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>{t('bulk.deleteAllTitle')}</DialogTitle>+ <DialogDescription>+ {t('bulk.deleteAllConfirm', { count: selectedIds.size })}+ {selectedWithBrief > 0 && (+ <span className="mt-2 block font-medium text-foreground">+ {t('bulk.deleteAllBriefWarning', { count: selectedWithBrief })}+ </span>+ )}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <DialogClose render={<Button variant="outline" />}>+ {t('cancel')}+ </DialogClose>+ <DialogClose+ render={<Button variant="destructive" onClick={handleBulkDelete} />}+ >+ {t('bulk.deleteAll')}+ </DialogClose>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ )}</div></div>)}@@ -1738,7 +1746,7 @@ export default function ContentPage() {}pageHref={`/dashboard/content/${opp.id}`}onDismiss={- opp.status === 'new'+ canManage && opp.status === 'new'? guard(() => void handleDismiss(opp.id), {action: tActions('dismissOpportunities'),})diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsxindex dd7b5fced..fdac16984 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx@@ -29,6 +29,16 @@ vi.mock('@/i18n/navigation', () => ({Link: ({ children, ...props }: React.ComponentProps<'a'>) => <a {...props}>{children}</a>,}));+// The viewer's role: an admin unless a test says otherwise.+const viewer = vi.hoisted(() => ({ role: 'admin' as string }));+vi.mock('@/hooks/use-user-role', () => ({+ useUserRole: () => ({+ role: viewer.role,+ canManage: viewer.role === 'admin' || viewer.role === 'manager',+ canAdmin: viewer.role === 'admin',+ }),+}));+const suggestion = (n: number): PromptSuggestion => ({id: `s${n}`,brandId: 'b1',@@ -94,6 +104,7 @@ beforeEach(() => {root = createRoot(container);vi.clearAllMocks();isLocked = false;+ viewer.role = 'admin';});afterEach(() => {@@ -292,6 +303,39 @@ describe('SuggestionsCard on a read-only workspace (plan not active)', () => {});});+describe('SuggestionsCard by role', () => {+ const labels = () =>+ [...container.querySelectorAll('button')].map(+ (b) => b.getAttribute('aria-label') ?? b.textContent,+ );++ it('shows an analyst Dismiss and Clear All, but no way to add a prompt', async () => {+ viewer.role = 'analyst';+ await render(2);+ expect(labels()).not.toContain('Add All');+ expect(labels()).not.toContain('Add to tracked prompts');+ expect(labels()).toContain('Clear All');+ expect(labels().filter((l) => l === 'Dismiss suggestion')).toHaveLength(2);+ });++ it('leaves an agency partner the list to read, without adding or dismissing', async () => {+ viewer.role = 'agency_partner';+ await render(2);+ expect(rows()).toHaveLength(2);+ for (const label of ['Add All', 'Clear All', 'Add to tracked prompts', 'Dismiss suggestion']) {+ expect(labels(), label).not.toContain(label);+ }+ });++ it('shows a manager every action', async () => {+ viewer.role = 'manager';+ await render(1);+ for (const label of ['Add All', 'Clear All', 'Add to tracked prompts', 'Dismiss suggestion']) {+ expect(labels(), label).toContain(label);+ }+ });+});+describe('SuggestionsCard — shopping questions from the catalog (ECOM-003)', () => {const fromCatalog: PromptSuggestion = {...suggestion(2),diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsxindex f45fac421..64362f18f 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx@@ -65,6 +65,7 @@ import {} from '@/lib/prompt-suggestion-source';import type { SuggestionSourceStates } from '@/lib/actions/integrations';import { useUpgradeGate } from '@/components/providers/upgrade-gate';+import { useUserRole } from '@/hooks/use-user-role';/*** Analytics evidence, in the customer's own numbers (#705). A blind spot is@@ -317,6 +318,10 @@ export function SuggestionsCard({// dismissing open the upgrade dialog instead.const { guard } = useUpgradeGate();const tActions = useTranslations('readOnly.actions');+ // Adding a prompt is for admins and managers; dismissing a suggestion is+ // open to analysts too, as the server and the table's update rule allow.+ const { role, canManage } = useUserRole();+ const canDismiss = canManage || role === 'analyst';// One method note for the list's volume ranges (PROMPT-013).const volumeNote = useMemo(() => createEstimateNoteHandle(), []);const [suggestions, setSuggestions] = useState<PromptSuggestion[]>([]);@@ -586,37 +591,41 @@ export function SuggestionsCard({{refreshing ? 'Generating…' : 'New'}</Button>- <Button- onClick={guard(handleAddAll, { action: tActions('addPrompts') })}- disabled={adding || clearing || visible.length === 0}- size="sm"- variant="outline"- className="gap-2"- title={t('addAllTitle')}- >- {adding ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <ListPlus className="h-3.5 w-3.5" />- )}- {adding ? t('addingAll') : t('addAll')}- </Button>+ {canManage && (+ <Button+ onClick={guard(handleAddAll, { action: tActions('addPrompts') })}+ disabled={adding || clearing || visible.length === 0}+ size="sm"+ variant="outline"+ className="gap-2"+ title={t('addAllTitle')}+ >+ {adding ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <ListPlus className="h-3.5 w-3.5" />+ )}+ {adding ? t('addingAll') : t('addAll')}+ </Button>+ )}- <Button- onClick={guard(handleClearAll, { action: tActions('dismissSuggestions') })}- disabled={clearing || adding || visible.length === 0}- size="sm"- variant="outline"- className="gap-2 text-muted-foreground"- title="Dismiss every suggestion listed below"- >- {clearing ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <Trash2 className="h-3.5 w-3.5" />- )}- Clear All- </Button>+ {canDismiss && (+ <Button+ onClick={guard(handleClearAll, { action: tActions('dismissSuggestions') })}+ disabled={clearing || adding || visible.length === 0}+ size="sm"+ variant="outline"+ className="gap-2 text-muted-foreground"+ title="Dismiss every suggestion listed below"+ >+ {clearing ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Trash2 className="h-3.5 w-3.5" />+ )}+ Clear All+ </Button>+ )}</div>)}</div>@@ -830,36 +839,40 @@ export function SuggestionsCard({<SourceBadges suggestion={s} /><div className="flex items-center justify-end gap-1">- <Button- size="icon"- variant="outline"- className="h-8 w-8"- onClick={guard(() => handleAccept(s), {- action: tActions('addPrompts'),- })}- disabled={busy}- title="Add to tracked prompts"- aria-label="Add to tracked prompts"- >- {busy ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <Plus className="h-3.5 w-3.5" />- )}- </Button>- <Button- size="icon"- variant="ghost"- className="h-8 w-8 text-muted-foreground"- onClick={guard(() => handleDismiss(s), {- action: tActions('dismissSuggestions'),- })}- disabled={busy}- title="Dismiss suggestion"- aria-label="Dismiss suggestion"- >- <X className="h-3.5 w-3.5" />- </Button>+ {canManage && (+ <Button+ size="icon"+ variant="outline"+ className="h-8 w-8"+ onClick={guard(() => handleAccept(s), {+ action: tActions('addPrompts'),+ })}+ disabled={busy}+ title="Add to tracked prompts"+ aria-label="Add to tracked prompts"+ >+ {busy ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Plus className="h-3.5 w-3.5" />+ )}+ </Button>+ )}+ {canDismiss && (+ <Button+ size="icon"+ variant="ghost"+ className="h-8 w-8 text-muted-foreground"+ onClick={guard(() => handleDismiss(s), {+ action: tActions('dismissSuggestions'),+ })}+ disabled={busy}+ title="Dismiss suggestion"+ aria-label="Dismiss suggestion"+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ )}</div></li>);diff --git a/web/src/components/content/opportunity-detail.test.tsx b/web/src/components/content/opportunity-detail.test.tsxindex 78945e886..f7ec214bf 100644--- a/web/src/components/content/opportunity-detail.test.tsx+++ b/web/src/components/content/opportunity-detail.test.tsx@@ -36,7 +36,11 @@ vi.mock('@/lib/actions/content-plan', () => plan);vi.mock('@/hooks/use-opportunity-volume', () => ({useOpportunityVolume: () => ({ basket: null, basketFailed: false, volume: null }),}));-vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => ({ canManage: true }) }));+// An admin or a manager unless a test says otherwise.+const viewer = vi.hoisted(() => ({ canManage: true }));+vi.mock('@/hooks/use-user-role', () => ({+ useUserRole: () => ({ canManage: viewer.canManage }),+}));const brandState = vi.hoisted(() => ({activeBrandId: 'b1',brands: [{ id: 'b1', name: 'Acme', siteType: 'b2b' }],@@ -119,6 +123,7 @@ const moreItem = async (item: string) => {beforeEach(() => {vi.clearAllMocks();+ viewer.canManage = true;newContent.open = false;content.getOpportunity.mockResolvedValue(OPPORTUNITY);content.getBriefQuota.mockResolvedValue({ limit: -1, remaining: -1 });@@ -197,3 +202,25 @@ describe('the brief quota without an active plan', () => {expect(buttonNamed('Generate Brief').disabled).toBe(true);});});++describe("the opportunity panel's Dismiss", () => {+ const menuItems = async () => {+ await act(async () =>+ container.querySelector<HTMLElement>('[aria-label="More actions"]')!.click(),+ );+ return [...document.body.querySelectorAll('[role="menuitem"]')].map((el) => el.textContent);+ };++ it('is offered to an admin or a manager', async () => {+ await render(false);+ expect(await menuItems()).toContain('Dismiss');+ });++ it('is left out for an analyst or an agency partner, who keep Mark as reviewed', async () => {+ viewer.canManage = false;+ await render(false);+ const items = await menuItems();+ expect(items).toContain('Mark as reviewed');+ expect(items).not.toContain('Dismiss');+ });+});diff --git a/web/src/components/content/opportunity-detail.tsx b/web/src/components/content/opportunity-detail.tsxindex 65e117b0c..aa948b7d2 100644--- a/web/src/components/content/opportunity-detail.tsx+++ b/web/src/components/content/opportunity-detail.tsx@@ -638,8 +638,9 @@ export function OpportunityDetail({? guard(() => void handleRestore(), { action: tActions('restoreOpportunities') }): undefined}+ // Dismissing is for admins and managers, as the server allows it.onDismiss={- opportunity.status === 'new'+ canManage && opportunity.status === 'new'? guard(() => setDismissOpen(true), { action: tActions('dismissOpportunities') }): undefined}