import { useEffect, useState } from 'react' import { Plus } from 'lucide-react' import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card' import { ProIndicator } from '@/components/pro/pro-indicator' import { DashboardSkeleton } from '@/components/ui/dashboard-skeleton' import { ReportError } from '@/components/ui/reporting' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Switch } from '@/components/ui/switch' import { Checkbox } from '@/components/ui/checkbox' import { Badge } from '@/components/ui/badge' import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog' import { toast, settingsSaved } from '@/components/ui/toast' interface Destination { id: string; name: string; url: string; enabled: boolean; archived: boolean events: string[]; includeEmail: boolean; includeProducts: boolean; includeRecovery: boolean; hasSecret: boolean } interface Registry { revision: string; destinations: Destination[]; legacyRecoverySetup: boolean } interface Draft extends Destination { secret: string } interface Delivery { event_id: string; event_type: string; status: string; attempts: string; response_code: string; outcome: string; created_at: string; available_at: string; history: Array<{ at: string; attempt: number; code: number; outcome: string }> } interface History { items: Delivery[]; total: number; page: number } const events = [['cart_abandoned', 'Cart abandoned'], ['cart_recovered', 'Cart recovered after payment'], ['cart_unsubscribed', 'Customer unsubscribed'], ['unpaid_order_resolved', 'Unpaid order paid, cancelled or refunded']] const emptyDraft = (): Draft => ({ id: '', name: '', url: '', enabled: false, archived: false, events: ['cart_abandoned'], includeEmail: false, includeProducts: false, includeRecovery: false, hasSecret: false, secret: '' }) const validRegistry = (value: Registry) => typeof value?.revision === 'string' && Array.isArray(value.destinations) && value.destinations.every(item => typeof item.id === 'string' && typeof item.name === 'string' && typeof item.url === 'string' && typeof item.enabled === 'boolean' && typeof item.archived === 'boolean' && typeof item.includeEmail === 'boolean' && typeof item.includeProducts === 'boolean' && typeof item.includeRecovery === 'boolean' && Array.isArray(item.events)) const message = (reason: unknown) => reason instanceof Error ? reason.message : 'The webhook request could not be confirmed.' async function api(path: string, data?: unknown, signal?: AbortSignal): Promise { const controller = new AbortController() const abort = () => controller.abort() signal?.addEventListener('abort', abort, { once: true }) if (signal?.aborted) controller.abort() const timer = setTimeout(abort, 30000) try { const response = await fetch(`${window.swiftCommerceData.apiUrl}/abandoned-cart/webhooks${path}`, { method: data === undefined ? 'GET' : 'POST', credentials: 'same-origin', signal: controller.signal, headers: { 'X-WP-Nonce': window.swiftCommerceData.restNonce, 'Content-Type': 'application/json' }, ...(data === undefined ? {} : { body: JSON.stringify(data) }) }) const result = await response.json().catch(() => { throw new Error('The server returned an unreadable response. Reload before continuing.') }) if (!response.ok || !result || typeof result !== 'object' || result.success === false) throw new Error(typeof result?.message === 'string' ? result.message : 'The webhook request failed. Please retry.') return result as T } catch (reason) { if (controller.signal.aborted && !signal?.aborted) throw new Error('The request timed out. Reload before trying again.') throw reason } finally { clearTimeout(timer); signal?.removeEventListener('abort', abort) } } export function WebhookSettings() { const [registry, setRegistry] = useState(null) const [error, setError] = useState('') const [revision, setRevision] = useState(0) const [draft, setDraft] = useState(null) const [baseline, setBaseline] = useState('') const [busy, setBusy] = useState(false) const [showArchived, setShowArchived] = useState(false) const [historyId, setHistoryId] = useState('') const [history, setHistory] = useState(null) const [historyError, setHistoryError] = useState('') const [page, setPage] = useState(1) const [historyRevision, setHistoryRevision] = useState(0) const [confirm, setConfirm] = useState<{ kind: 'save' | 'test' | 'archive' | 'replay'; destination?: Destination; delivery?: Delivery } | null>(null) const dirty = !!draft && JSON.stringify(draft) !== baseline useEffect(() => { const controller = new AbortController() setRegistry(null); setError('') api('/destinations', undefined, controller.signal).then(value => { if (controller.signal.aborted) return if (!validRegistry(value)) throw new Error('Saved webhooks could not be read. Reload before continuing.') setRegistry(value) }).catch(reason => { if (!controller.signal.aborted) setError(message(reason)) }) return () => controller.abort() }, [revision]) useEffect(() => { if (!historyId) return const controller = new AbortController() setHistory(null); setHistoryError('') api(`/deliveries?destination_id=${encodeURIComponent(historyId)}&page=${page}`, undefined, controller.signal).then(value => { if (controller.signal.aborted) return if (!Array.isArray(value.items) || typeof value.total !== 'number') throw new Error('Delivery history could not be read.') setHistory(value) }).catch(reason => { if (!controller.signal.aborted) setHistoryError(message(reason)) }) return () => controller.abort() }, [historyId, page, historyRevision]) useEffect(() => { if (!dirty) return const unload = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = '' } const navigate = (event: Event) => { if (!window.confirm('Discard unsaved webhook changes?')) event.preventDefault() } window.addEventListener('beforeunload', unload); window.addEventListener('swift-commerce:navigate', navigate) return () => { window.removeEventListener('beforeunload', unload); window.removeEventListener('swift-commerce:navigate', navigate) } }, [dirty]) const edit = (destination?: Destination) => { if (dirty && !window.confirm('Discard unsaved webhook changes?')) return const next = destination ? { ...destination, secret: '' } : emptyDraft() setDraft(next); setBaseline(JSON.stringify(next)); setError('') } const change = (updates: Partial) => setDraft(value => value ? { ...value, ...updates } : value) const save = async (destination: Draft) => { if (!registry) return setBusy(true); setError('') try { const value = await api('/destinations', { revision: registry.revision, destination }) if (!validRegistry(value)) throw new Error('The saved webhook could not be confirmed. Reload before continuing.') setRegistry(value); setDraft(null); setBaseline(''); setConfirm(null); settingsSaved() setHistoryRevision(value => value + 1) } catch (reason) { setError(message(reason)); setConfirm(null) } finally { setBusy(false) } } const submit = () => { if (!draft) return const old = registry?.destinations.find(item => item.id === draft.id) const sharing = draft.enabled || draft.includeEmail || draft.includeProducts || draft.includeRecovery const changed = !old || old.url !== draft.url || old.enabled !== draft.enabled || old.includeEmail !== draft.includeEmail || old.includeProducts !== draft.includeProducts || old.includeRecovery !== draft.includeRecovery if (sharing && changed) setConfirm({ kind: 'save' }) else void save(draft) } const perform = async () => { if (!confirm || !registry) return if (confirm.kind === 'save' && draft) { await save(draft); return } if (confirm.kind === 'archive' && confirm.destination) { await save({ ...confirm.destination, secret: '', enabled: false, archived: true }); return } setBusy(true); setError(''); setHistoryError('') try { if (confirm.kind === 'test' && confirm.destination) { const value = await api<{ delivery: Delivery | null }>('/test', { id: confirm.destination.id }) if (!value.delivery || !value.delivery.event_id) throw new Error('The test result could not be confirmed. Check delivery history before retrying.') setHistoryId(confirm.destination.id); setPage(1) if (value.delivery.status === 'delivered') toast.success('Test event accepted', { description: `HTTP ${value.delivery.response_code}. Check your receiving workflow.` }) else setHistoryError(`Test not accepted: ${Number(value.delivery.response_code) ? 'HTTP ' + value.delivery.response_code : value.delivery.outcome}. Check the URL and receiver, then review history.`) } else if (confirm.kind === 'replay' && confirm.delivery) { await api('/replay', { destination_id: historyId, event_id: confirm.delivery.event_id }) toast.success('Webhook replay queued') } setHistoryRevision(value => value + 1); setConfirm(null) } catch (reason) { setError(message(reason)); setConfirm(null) } finally { setBusy(false) } } const cancelEdit = () => { setDraft(null); setBaseline(''); setError('') } const visible = registry?.destinations.filter(item => item.archived === showArchived) || [] const selectedHistory = registry?.destinations.find(item => item.id === historyId) const baseDraft = registry?.destinations.find(item => item.id === draft?.id) const canSave = !!draft && dirty && !!draft.name.trim() && /^https:\/\//i.test(draft.url) && draft.events.length > 0 && (!draft.secret || draft.secret.length >= 16) const preview = { event: 'cart_abandoned', event_id: 'stable-event-id', cart_id: 123, cart_total: '29.00', currency: 'USD', ...(draft?.includeEmail ? { email: 'customer@example.invalid' } : {}), ...(draft?.includeProducts ? { items: [{ product_id: 123, variation_id: 0, quantity: 1, has_addons: false, has_bundle_items: false, purchase_mode: '' }] } : {}), ...(draft?.includeRecovery ? { claim_url: 'https://your-store.example/wp-json/swift-commerce/v1/abandoned-cart/campaign-claim', claim_token: 'private-one-use-token' } : {}) } return <>
Webhooks Send cart events to Zapier, Make, n8n or your own HTTPS endpoint.
{error && { if (draft) submit(); else setRevision(value => value + 1) }} />} {!registry ? !error && : <> {registry.legacyRecoverySetup &&

Your earlier webhook is preserved. Recovery-link access now needs its own opt-in; update older automation before using it. The existing email sending state has not changed.

}

Webhooks do not change recovery email sending. Manage Swift Commerce reminders in the Emails tab.

{registry.destinations.some(item => item.archived) &&
} {!visible.length && !draft &&

{showArchived ? 'No archived webhooks' : 'Connect your first automation'}

{showArchived ? 'Archived connections can be restored here.' : 'Create a webhook trigger in your automation platform, copy its URL, then add it here.'}

}
{visible.map(item =>

{item.name}

{item.archived ? 'Archived' : item.enabled ? 'Enabled' : 'Paused'}

{(() => { try { return new URL(item.url).host } catch { return 'URL needs attention' } })()}

{!item.archived && <>}

{item.events.map(event => events.find(([key]) => key === event)?.[1] || event).join(' · ')}

)}
{draft &&
{ event.preventDefault(); submit() }}>

{draft.id ? 'Edit webhook' : 'New webhook'}

change({ name: event.target.value })} placeholder="Make — Cart recovery" autoFocus />
change({ url: event.target.value })} placeholder="Paste the webhook URL from your automation platform" />

Use a public HTTPS URL. For n8n, use the production URL for live events. Private network addresses and redirects are not supported.

Events to send{events.map(([key, title]) =>
change({ events: checked ? [...draft.events, key] : draft.events.filter(value => value !== key) })} />
)}
Data to include

Cart identifiers, value and currency are included. Choose any additional data this destination may receive.

{([['includeEmail', 'Customer email'], ['includeProducts', 'Product IDs, quantities and feature flags']] as const).map(([key, title]) =>
change(key === 'includeEmail' ? { includeEmail: checked === true, ...(!checked ? { includeRecovery: false } : {}) } : { includeProducts: checked === true })} />
)}

No payment details, uploaded files or entered personalization values are sent.

Advanced: security and recovery links
change({ secret: event.target.value })} placeholder={draft.hasSecret ? 'Leave blank to keep the saved key' : 'Leave blank for an automatically generated key'} />

Requests are signed. Set a known secret here if your receiver will verify signatures; saved keys are encrypted and never shown again.

change({ includeRecovery: checked === true, ...(checked ? { includeEmail: true } : {}) })} />

For workflows that send recovery emails. Requires an HTTPS store and customer email sharing. Pause Swift Commerce recovery emails separately; the receiver must check eligibility immediately before sending.

View sample payload

Illustrative values only. Connection tests use a separate webhook_test event with no customer email or recovery tokens.

{JSON.stringify(preview, null, 2)}
change({ enabled, archived: false })} />
{draft.archived &&

Enable this webhook to restore it, then save.

}
{baseDraft &&

Changing the URL, shared data or signing key cancels older queued payloads. They will not be redirected to the new configuration.

}
}

Saved separately from other Advanced settings. Disabling Cart Recovery pauses all webhook deliveries.

}
{historyId &&
Delivery history{selectedHistory ? ` — ${selectedHistory.name}` : ''}
Up to eight attempts with backoff. Delivered and cancelled records expire after 30 days. All times UTC.
{historyError && setHistoryRevision(value => value + 1)} />} {!history ? !historyError && : !history.items.length ?

No deliveries yet. Send a synthetic test or wait for a selected cart event.

:
{history.items.map(item =>

{item.event_type === 'webhook_test' ? 'Connection test (synthetic)' : events.find(([key]) => key === item.event_type)?.[1] || item.event_type}

{item.status}

{item.event_id}

{item.created_at} UTC · {item.attempts} attempts · {Number(item.response_code) ? `HTTP ${item.response_code}` : item.outcome || 'Awaiting delivery'}

{item.history.length > 0 &&
Attempt history
    {item.history.map((attempt, index) =>
  • {attempt.at} · {attempt.code ? `HTTP ${attempt.code}` : attempt.outcome.replace(/_/g, ' ')}
  • )}
}
)}
} {history && history.total > 20 &&

Page {page} of {Math.ceil(history.total / 20)}

}
} { if (!open && !busy) setConfirm(null) }}>{confirm?.kind === 'save' ? 'Save this webhook connection?' : confirm?.kind === 'test' ? 'Send a synthetic test event?' : confirm?.kind === 'archive' ? 'Archive this webhook?' : 'Replay this delivery?'}{confirm?.kind === 'save' ? `Selected events and data will be shared with ${draft?.url || 'this destination'} when enabled. Email: ${draft?.includeEmail ? 'included' : 'not included'}. Product details: ${draft?.includeProducts ? 'included' : 'not included'}. Recovery-link access: ${draft?.includeRecovery ? 'allowed after eligibility checks' : 'not allowed'}. Swift Commerce email sending will not change.` : confirm?.kind === 'test' ? `A clearly labelled webhook_test event will be sent to ${confirm.destination?.url}. It contains no real customer or cart data, but it may start the receiving workflow. Configure that workflow to ignore test events for customer messaging.` : confirm?.kind === 'archive' ? 'This stops deliveries and cancels old queued payloads. The webhook and history remain available; you can restore the connection from Archived webhooks.' : 'The original event ID, body and destination are retained. Receivers must deduplicate event IDs. Outdated or no-longer-permitted events are cancelled instead.'}Cancel { event.preventDefault(); void perform() }}>{busy ? 'Working…' : confirm?.kind === 'save' ? 'Save webhook' : confirm?.kind === 'test' ? 'Send test event' : confirm?.kind === 'archive' ? 'Archive webhook' : 'Queue replay'} }