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(webhooks): honour per-webhook event subscriptions (#1239)
Sanjeev Kumarbbbbd1a5860a
diff --git a/docs/api-reference/webhooks.mdx b/docs/api-reference/webhooks.mdxindex 67ca55159..601c27f68 100644--- a/docs/api-reference/webhooks.mdx+++ b/docs/api-reference/webhooks.mdx@@ -11,7 +11,7 @@ Each brand has one webhook, set up in **Content → Configure Webhook**:- **Secret key** (optional) — sent back to you in a header on every request, so your endpoint can tell that the call came from Ansvisor.- **Active** — pause delivery without deleting the webhook.-The webhook receives every event below. Check the `event` field to tell them apart.+Choose the events a webhook should receive in **Content → Configure Webhook**. Migration 00198 keeps existing webhooks subscribed to all three supported events until a user saves a new selection. **Test Webhook** always sends `webhook.test`, regardless of the saved selection.## Events@@ -19,7 +19,8 @@ The webhook receives every event below. Check the `event` field to tell them apa|---|---|| `opportunity.sent` | A user sends a content opportunity to the workflow — from the opportunity page, or several at once from the opportunities list || `daily_pulse.created` | A brand's Daily Pulse is generated (on cloud and self-host alike) |-| `webhook.test` | **Test Webhook** is pressed in the webhook settings |+| `action_task.sent` | A user sends an Action Center task to the configured webhook |+| `webhook.test` | **Test Webhook** is pressed in the webhook settings (always sent, independent of subscriptions) |## Verifying requests@@ -147,6 +148,41 @@ Warning types and their fields:Every highlight and warning also has a `key` that identifies its subject.+### `action_task.sent`++```json+{+ "event": "action_task.sent",+ "task": {+ "id": "uuid",+ "title": "Update the shipping guide",+ "status": "todo",+ "type": "content",+ "where": "acme.example/guides/shipping",+ "why": "The page is missing useful details.",+ "how": ["Add a comparison table."],+ "done_when": "The updated page is live.",+ "effort": "~2h",+ "role": "Content writer"+ },+ "action": {+ "id": "uuid",+ "action_no": 12,+ "kind": "recover_lost_citations",+ "category": "recover",+ "impact": "high",+ "priority_score": 84,+ "priority_level": "high",+ "link": "https://app.example.com/dashboard/action-center/actions?action=<action id>"+ },+ "brand": {+ "name": "Acme",+ "domain": "acme.example",+ "industry": "Software"+ }+}+```+### `webhook.test````jsondiff --git a/docs/guides/daily-pulse.mdx b/docs/guides/daily-pulse.mdxindex 05156939f..12cf0cfbb 100644--- a/docs/guides/daily-pulse.mdx+++ b/docs/guides/daily-pulse.mdx@@ -102,7 +102,7 @@ Highlights other than first citations and new engines compare the last 7 days wi## Webhook delivery-Every generated pulse is also sent as a `daily_pulse.created` event to the brand's active webhook, configured under **Content → Configure Webhook**. This works on self-hosted instances too, where it is the only delivery channel.+Every generated pulse is also sent as a `daily_pulse.created` event to the brand's active webhook, if it is subscribed to that event, configured under **Content → Configure Webhook**. This works on self-hosted instances too, where it is the only delivery channel.The webhook payload contains the same KPIs, highlights and warnings as the email, plus the pulse date, the frequency and a link to Insights. The frequency setting applies to the webhook as well: **Off** sends nothing, **Weekly** sends on Mondays only. The recipient list does not.diff --git a/server/src/lib/action-center/task-send.js b/server/src/lib/action-center/task-send.jsindex aa069b144..bd503d5c5 100644--- a/server/src/lib/action-center/task-send.js+++ b/server/src/lib/action-center/task-send.js@@ -10,6 +10,8 @@** Send to webhook posts the task to the brand's active webhooks, in the shape* Content's opportunity.sent uses, for a workflow outside Ansvisor to pick up.+ * A webhook must have `action_task.sent` selected; an active but unsubscribed+ * webhook is reported separately from a missing webhook.** Either way the task records where it went (details.sent), the action's* History says so, and a task that has been sent survives "Regenerate tasks".@@ -261,13 +263,30 @@ export async function sendTaskToWebhook({ taskId, title, userId, loaded }) {const name = text(task.title) || text(title);if (!name) throw new TaskSendError('no_title', 'The task has no text to send.');- const [{ data: brand }, { data: domains }] = await Promise.all([- supabaseAdmin.from('brands').select('name, industry').eq('id', action.brand_id).single(),- supabaseAdmin- .from('brand_domains')- .select('domain, is_primary')- .eq('brand_id', action.brand_id),- ]);+ const [{ data: brand }, { data: domains }, { data: webhookConfigs, error: webhookConfigError }] =+ await Promise.all([+ supabaseAdmin.from('brands').select('name, industry').eq('id', action.brand_id).single(),+ supabaseAdmin+ .from('brand_domains')+ .select('domain, is_primary')+ .eq('brand_id', action.brand_id),+ supabaseAdmin+ .from('webhook_configs')+ .select('id, events')+ .eq('brand_id', action.brand_id)+ .eq('is_active', true),+ ]);+ if (webhookConfigError) throw new Error(webhookConfigError.message);+ if (!webhookConfigs?.length) {+ throw new TaskSendError('no_webhook', 'This brand has no active webhook.', 409);+ }+ if (!webhookConfigs.some((config) => config.events?.includes('action_task.sent'))) {+ throw new TaskSendError(+ 'webhook_not_subscribed',+ 'The active webhook is not subscribed to Action Center tasks.',+ 409,+ );+ }const primary = (domains ?? []).find((d) => d.is_primary) ?? (domains ?? [])[0];const d = task.details ?? {};diff --git a/server/src/lib/action-center/task-send.test.js b/server/src/lib/action-center/task-send.test.jsindex 741231a87..6ad510afa 100644--- a/server/src/lib/action-center/task-send.test.js+++ b/server/src/lib/action-center/task-send.test.js@@ -111,6 +111,7 @@ beforeEach(() => {],brands: [{ id: 'b1', name: 'Acme Coffee', industry: 'Coffee' }],brand_domains: [{ brand_id: 'b1', domain: 'acme.example', is_primary: true }],+ webhook_configs: [{ id: 'w1', brand_id: 'b1', is_active: true, events: ['action_task.sent'] }],content_opportunities: [],};});@@ -213,12 +214,24 @@ describe('sendTaskToWebhook', () => {expect(db.action_tasks[0].details.sent.webhook).toMatchObject({ delivered: 1 });});- it('says when there is no webhook, or it refused the task, and records nothing', async () => {- dispatchBrandWebhook.mockResolvedValueOnce({ sent: 0, failed: 0 });+ it('distinguishes no active webhook from an active webhook without the task subscription', async () => {+ db.webhook_configs = [];await expect(sendTaskToWebhook({ taskId: 't1', title: '' })).rejects.toMatchObject({code: 'no_webhook',status: 409,});++ db.webhook_configs = [+ { id: 'w1', brand_id: 'b1', is_active: true, events: ['opportunity.sent'] },+ ];+ await expect(sendTaskToWebhook({ taskId: 't1', title: '' })).rejects.toMatchObject({+ code: 'webhook_not_subscribed',+ status: 409,+ });++ db.webhook_configs = [+ { id: 'w1', brand_id: 'b1', is_active: true, events: ['action_task.sent'] },+ ];dispatchBrandWebhook.mockResolvedValueOnce({ sent: 0, failed: 1 });await expect(sendTaskToWebhook({ taskId: 't1', title: '' })).rejects.toMatchObject({code: 'webhook_failed',diff --git a/server/src/lib/webhook-dispatch.js b/server/src/lib/webhook-dispatch.jsindex f8137d575..f8961e08c 100644--- a/server/src/lib/webhook-dispatch.js+++ b/server/src/lib/webhook-dispatch.js@@ -14,9 +14,10 @@ import { logger } from './logger.js';export async function dispatchBrandWebhook(brandId, payload) {const { data: configs } = await supabaseAdmin.from('webhook_configs')- .select('id, webhook_url, webhook_secret')+ .select('id, webhook_url, webhook_secret, events').eq('brand_id', brandId)- .eq('is_active', true);+ .eq('is_active', true)+ .contains('events', [payload.event]);if (!configs?.length) return { sent: 0, failed: 0 };diff --git a/server/src/lib/webhook-dispatch.test.js b/server/src/lib/webhook-dispatch.test.jsnew file mode 100644index 000000000..d1fe3b909--- /dev/null+++ b/server/src/lib/webhook-dispatch.test.js@@ -0,0 +1,156 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { mockFrom, mockFetch, state } = vi.hoisted(() => ({+ mockFrom: vi.fn(),+ mockFetch: vi.fn(),+ state: { configs: [] },+}));++vi.mock('../config/supabase.js', () => ({+ default: { from: mockFrom },+}));+vi.mock('./logger.js', () => ({+ logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },+}));++const { dispatchBrandWebhook } = await import('./webhook-dispatch.js');++function queryForConfigs() {+ const filters = [];+ const query = {+ select: vi.fn(() => query),+ eq: vi.fn((column, value) => {+ filters.push((config) => config[column] === value);+ return query;+ }),+ contains: vi.fn((column, values) => {+ filters.push(+ (config) =>+ Array.isArray(config[column]) && values.every((value) => config[column].includes(value)),+ );+ return query;+ }),+ then: (resolve, reject) =>+ Promise.resolve({+ data: state.configs.filter((config) => filters.every((matches) => matches(config))),+ error: null,+ }).then(resolve, reject),+ };+ return query;+}++beforeEach(() => {+ state.configs = [];+ mockFrom.mockReset();+ mockFrom.mockImplementation((table) => {+ expect(table).toBe('webhook_configs');+ return queryForConfigs();+ });+ mockFetch.mockReset();+ mockFetch.mockResolvedValue({ ok: true, status: 204 });+ vi.stubGlobal('fetch', mockFetch);+});++describe('dispatchBrandWebhook', () => {+ it('delivers an event only to active configs subscribed to that event', async () => {+ state.configs = [+ {+ id: 'opportunity-only',+ brand_id: 'brand-1',+ webhook_url: 'https://opportunity.example/hook',+ webhook_secret: null,+ is_active: true,+ events: ['opportunity.sent'],+ },+ {+ id: 'pulse',+ brand_id: 'brand-1',+ webhook_url: 'https://pulse.example/hook',+ webhook_secret: 'pulse-secret',+ is_active: true,+ events: ['daily_pulse.created'],+ },+ {+ id: 'inactive',+ brand_id: 'brand-1',+ webhook_url: 'https://inactive.example/hook',+ webhook_secret: null,+ is_active: false,+ events: ['daily_pulse.created'],+ },+ {+ id: 'other-brand',+ brand_id: 'brand-2',+ webhook_url: 'https://other.example/hook',+ webhook_secret: null,+ is_active: true,+ events: ['daily_pulse.created'],+ },+ ];++ const result = await dispatchBrandWebhook('brand-1', {+ event: 'daily_pulse.created',+ pulse: { date: '2026-10-20' },+ });++ expect(result).toEqual({ sent: 1, failed: 0 });+ expect(mockFetch).toHaveBeenCalledTimes(1);+ expect(mockFetch).toHaveBeenCalledWith(+ 'https://pulse.example/hook',+ expect.objectContaining({+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-Webhook-Secret': 'pulse-secret',+ },+ }),+ );+ });++ it('counts delivery failures without throwing', async () => {+ state.configs = [+ {+ id: 'non-2xx',+ brand_id: 'brand-1',+ webhook_url: 'https://reject.example/hook',+ webhook_secret: null,+ is_active: true,+ events: ['opportunity.sent'],+ },+ {+ id: 'network-error',+ brand_id: 'brand-1',+ webhook_url: 'https://network.example/hook',+ webhook_secret: null,+ is_active: true,+ events: ['opportunity.sent'],+ },+ ];+ mockFetch+ .mockResolvedValueOnce({ ok: false, status: 503 })+ .mockRejectedValueOnce(new Error('connection refused'));++ await expect(dispatchBrandWebhook('brand-1', { event: 'opportunity.sent' })).resolves.toEqual({+ sent: 0,+ failed: 2,+ });+ });++ it('does not attempt delivery when no config subscribes to the event', async () => {+ state.configs = [+ {+ id: 'opportunity-only',+ brand_id: 'brand-1',+ webhook_url: 'https://opportunity.example/hook',+ webhook_secret: null,+ is_active: true,+ events: ['opportunity.sent'],+ },+ ];++ await expect(+ dispatchBrandWebhook('brand-1', { event: 'daily_pulse.created' }),+ ).resolves.toEqual({ sent: 0, failed: 0 });+ expect(mockFetch).not.toHaveBeenCalled();+ });+});diff --git a/server/src/routes/content.js b/server/src/routes/content.jsindex 722834ef9..16c08534d 100644--- a/server/src/routes/content.js+++ b/server/src/routes/content.js@@ -849,10 +849,16 @@ router.post('/bulk/send-webhook', async (req, res) => {.eq('brand_id', brandId).eq('is_active', true).limit(1)- .single();+ .maybeSingle();if (!webhookConfig) {- return res.status(400).json({ error: 'No workflow connected' });+ return res.status(400).json({ error: 'No workflow connected', code: 'no_webhook' });+ }+ if (!webhookConfig.events?.includes('opportunity.sent')) {+ return res.status(409).json({+ error: 'Webhook is not subscribed to Opportunity sent events.',+ code: 'webhook_not_subscribed',+ });}const { data: brand } = await supabaseAdmin@@ -1031,10 +1037,16 @@ router.post('/:id/send-webhook', async (req, res) => {.eq('brand_id', opportunity.brand_id).eq('is_active', true).limit(1)- .single();+ .maybeSingle();if (!webhookConfig) {- return res.status(400).json({ error: 'No workflow connected' });+ return res.status(400).json({ error: 'No workflow connected', code: 'no_webhook' });+ }+ if (!webhookConfig.events?.includes('opportunity.sent')) {+ return res.status(409).json({+ error: 'Webhook is not subscribed to Opportunity sent events.',+ code: 'webhook_not_subscribed',+ });}const { data: brand } = await supabaseAdmindiff --git a/supabase/migrations/00198_webhook_event_subscriptions.sql b/supabase/migrations/00198_webhook_event_subscriptions.sqlnew file mode 100644index 000000000..4826925ff--- /dev/null+++ b/supabase/migrations/00198_webhook_event_subscriptions.sql@@ -0,0 +1,38 @@+-- ============================================================================+-- 00198: per-webhook event subscriptions+-- ============================================================================+-- Keep existing integrations receiving the events they already receive. Event+-- subscription controls are now available in Content → Configure Webhook.+-- Test deliveries use webhook.test directly and are not stored subscriptions.++alter table public.webhook_configs+ alter column events set default+ array['opportunity.sent', 'daily_pulse.created', 'action_task.sent']::text[];++update public.webhook_configs as config+set events = (+ select array_agg(subscription.event order by subscription.event)+ from (+ select distinct event+ from unnest(+ coalesce(config.events, array[]::text[])+ || array['opportunity.sent', 'daily_pulse.created', 'action_task.sent']::text[]+ ) as existing(event)+ where event = any(array['opportunity.sent', 'daily_pulse.created', 'action_task.sent']::text[])+ ) as subscription+);++alter table public.webhook_configs+ alter column events set not null;++alter table public.webhook_configs+ drop constraint if exists webhook_configs_events_allowed;++alter table public.webhook_configs+ add constraint webhook_configs_events_allowed+ check (events <@ array['opportunity.sent', 'daily_pulse.created', 'action_task.sent']::text[]);++comment on column public.webhook_configs.events is+ 'Event types subscribed to by this webhook (opportunity.sent, daily_pulse.created, action_task.sent). webhook.test is always sent by the test action and is not stored here.';++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 810a9a369..9fefe9c8f 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -26624,3 +26624,45 @@ comment on function public.ai_traffic_platforms_seen(uuid, timestamptz, text[])notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00198_webhook_event_subscriptions.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00198: per-webhook event subscriptions+-- ============================================================================+-- Keep existing integrations receiving the events they already receive. Event+-- subscription controls are now available in Content → Configure Webhook.+-- Test deliveries use webhook.test directly and are not stored subscriptions.++alter table public.webhook_configs+ alter column events set default+ array['opportunity.sent', 'daily_pulse.created', 'action_task.sent']::text[];++update public.webhook_configs as config+set events = (+ select array_agg(subscription.event order by subscription.event)+ from (+ select distinct event+ from unnest(+ coalesce(config.events, array[]::text[])+ || array['opportunity.sent', 'daily_pulse.created', 'action_task.sent']::text[]+ ) as existing(event)+ where event = any(array['opportunity.sent', 'daily_pulse.created', 'action_task.sent']::text[])+ ) as subscription+);++alter table public.webhook_configs+ alter column events set not null;++alter table public.webhook_configs+ drop constraint if exists webhook_configs_events_allowed;++alter table public.webhook_configs+ add constraint webhook_configs_events_allowed+ check (events <@ array['opportunity.sent', 'daily_pulse.created', 'action_task.sent']::text[]);++comment on column public.webhook_configs.events is+ 'Event types subscribed to by this webhook (opportunity.sent, daily_pulse.created, action_task.sent). webhook.test is always sent by the test action and is not stored here.';++notify pgrst, 'reload schema';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex cfeb00026..384e636fe 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3033,7 +3033,13 @@},"webhook": {"title": "Webhook Settings",- "description": "Connect your workflow automation tool (n8n, Make, Zapier) to receive opportunities.",+ "description": "Connect your workflow automation tool (n8n, Make, Zapier) and choose which events it receives.",+ "eventsTitle": "Events to send",+ "eventsDescription": "Only selected events are sent. Test Webhook always sends a test event, regardless of these selections.",+ "eventRequired": "Select at least one event for this webhook.",+ "eventOpportunitySent": "Opportunity sent",+ "eventDailyPulseCreated": "Daily Pulse created",+ "eventActionTaskSent": "Action Center task sent","url": "Webhook URL","urlPlaceholder": "https://your-n8n-instance.com/webhook/...","secret": "Secret Key (optional)",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsxindex 550e3cfb7..59ebf0ce9 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx@@ -10,12 +10,21 @@ import {DialogDescription,} from '@/components/ui/dialog';import { Button } from '@/components/ui/button';+import { Checkbox } from '@/components/ui/checkbox';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';import { Loader2, CheckCircle2, XCircle } from 'lucide-react';import { getWebhookConfig, saveWebhookConfig, testWebhook } from '@/lib/actions/content';import { toast } from 'sonner';+const WEBHOOK_EVENTS = [+ { value: 'opportunity.sent', label: 'eventOpportunitySent' },+ { value: 'daily_pulse.created', label: 'eventDailyPulseCreated' },+ { value: 'action_task.sent', label: 'eventActionTaskSent' },+] as const;++const DEFAULT_WEBHOOK_EVENTS = WEBHOOK_EVENTS.map(({ value }) => value);+interface WebhookSettingsDialogProps {open: boolean;onOpenChange: (open: boolean) => void;@@ -28,6 +37,7 @@ export function WebhookSettingsDialog({ open, onOpenChange, brandId }: WebhookSeconst [url, setUrl] = useState('');const [secret, setSecret] = useState('');const [isActive, setIsActive] = useState(true);+ const [events, setEvents] = useState<string[]>([...DEFAULT_WEBHOOK_EVENTS]);const [loading, setLoading] = useState(false);const [saving, setSaving] = useState(false);const [testing, setTesting] = useState(false);@@ -46,6 +56,12 @@ export function WebhookSettingsDialog({ open, onOpenChange, brandId }: WebhookSesetUrl(config.webhookUrl);setSecret(config.webhookSecret || '');setIsActive(config.isActive);+ setEvents(config.events ?? [...DEFAULT_WEBHOOK_EVENTS]);+ } else {+ setUrl('');+ setSecret('');+ setIsActive(true);+ setEvents([...DEFAULT_WEBHOOK_EVENTS]);}}).catch(console.error)@@ -58,11 +74,16 @@ export function WebhookSettingsDialog({ open, onOpenChange, brandId }: WebhookSetoast.error(t('urlRequired'));return;}+ if (events.length === 0) {+ toast.error(t('eventRequired'));+ return;+ }setSaving(true);try {await saveWebhookConfig(brandId, {webhookUrl: url.trim(),webhookSecret: secret.trim() || undefined,+ events,isActive,});toast.success(t('saved'));@@ -134,6 +155,39 @@ export function WebhookSettingsDialog({ open, onOpenChange, brandId }: WebhookSe/></div>+ <fieldset className="space-y-2">+ <legend className="text-sm font-medium">{t('eventsTitle')}</legend>+ <p className="text-xs text-muted-foreground">{t('eventsDescription')}</p>+ <div className="space-y-2 rounded-md border p-3">+ {WEBHOOK_EVENTS.map((eventOption) => (+ <div key={eventOption.value} className="flex items-center gap-2">+ <Checkbox+ id={`webhook-event-${eventOption.value}`}+ checked={events.includes(eventOption.value)}+ onCheckedChange={(checked) =>+ setEvents((current) =>+ checked === true+ ? Array.from(new Set([...current, eventOption.value]))+ : current.filter((value) => value !== eventOption.value),+ )+ }+ />+ <Label+ htmlFor={`webhook-event-${eventOption.value}`}+ className="cursor-pointer font-normal"+ >+ {t(eventOption.label)}+ </Label>+ </div>+ ))}+ </div>+ {events.length === 0 && (+ <p className="text-xs text-destructive" role="alert">+ {t('eventRequired')}+ </p>+ )}+ </fieldset>+<div className="flex items-center gap-2"><buttontype="button"diff --git a/web/src/lib/actions/action-task-send.test.ts b/web/src/lib/actions/action-task-send.test.tsindex efa637bd0..de689acc4 100644--- a/web/src/lib/actions/action-task-send.test.ts+++ b/web/src/lib/actions/action-task-send.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, it, vi } from 'vitest';-let configs: { id: string }[] = [];+let configs: { id: string; events?: string[] }[] = [];let filters: [string, unknown][] = [];let selected = '';vi.mock('@/lib/supabase/server', () => ({@@ -28,13 +28,15 @@ afterEach(() => {describe('hasActiveWebhook', () => {it('asks only whether an active one exists, never for its secret', async () => {- configs = [{ id: 'w1' }];+ configs = [{ id: 'w1', events: ['action_task.sent'] }];expect(await hasActiveWebhook('b1')).toBe(true);- expect(selected).toBe('id');+ expect(selected).toBe('id, events');expect(filters).toEqual([['brand_id', 'b1'],['is_active', true],]);+ configs = [{ id: 'w1', events: ['opportunity.sent'] }];+ expect(await hasActiveWebhook('b1')).toBe(false);configs = [];expect(await hasActiveWebhook('b1')).toBe(false);});diff --git a/web/src/lib/actions/action-task-send.ts b/web/src/lib/actions/action-task-send.tsindex 6430d438a..3ad3de6d2 100644--- a/web/src/lib/actions/action-task-send.ts+++ b/web/src/lib/actions/action-task-send.ts@@ -11,12 +11,12 @@ export async function hasActiveWebhook(brandId: string): Promise<boolean> {const supabase = await createClient();const { data, error } = await supabase.from('webhook_configs')- .select('id')+ .select('id, events').eq('brand_id', brandId).eq('is_active', true).limit(1);if (error) return false;- return (data ?? []).length > 0;+ return (data ?? []).some((config) => config.events?.includes('action_task.sent'));}/**diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.tsindex 9d569326b..6b58482d1 100644--- a/web/src/lib/actions/content.ts+++ b/web/src/lib/actions/content.ts@@ -575,9 +575,19 @@ export async function getWebhookConfig(brandId: string): Promise<WebhookConfig |export async function saveWebhookConfig(brandId: string,- config: { webhookUrl: string; webhookSecret?: string; isActive?: boolean },+ config: {+ webhookUrl: string;+ webhookSecret?: string;+ events: string[];+ isActive?: boolean;+ },): Promise<WebhookConfig> {const supabase = await createClient();+ const allowedEvents = ['opportunity.sent', 'daily_pulse.created', 'action_task.sent'];+ const events = Array.from(new Set(config.events)).filter((event) =>+ allowedEvents.includes(event),+ );+ if (events.length === 0) throw new Error('Select at least one webhook event.');const { data, error } = await supabase.from('webhook_configs')@@ -587,6 +597,7 @@ export async function saveWebhookConfig(name: 'Default',webhook_url: config.webhookUrl,webhook_secret: config.webhookSecret || null,+ events,is_active: config.isActive ?? true,updated_at: new Date().toISOString(),},