whatsapp broadcast

This commit is contained in:
debu-2 2026-10-13 03:14:52 +05:30
parent 63011f7d96
commit 70ccb720aa
9 changed files with 570 additions and 4 deletions

View file

@ -109,8 +109,26 @@ export function CustomerWhatsAppInbox({ account, onBack }: { account: WhatsAppAc
const [reactFor, setReactFor] = useState<string | null>(null)
const [emojiOpen, setEmojiOpen] = useState(false)
const chatEndRef = useRef<HTMLDivElement | null>(null)
const line = account.primary_phone?.display_phone || account.name
const canSend = account.messaging_status === 'active' && account.usable
const [deliveryAccount, setDeliveryAccount] = useState(account)
const [appSecret, setAppSecret] = useState('')
const [deliveryBusy, setDeliveryBusy] = useState(false)
const line = deliveryAccount.primary_phone?.display_phone || deliveryAccount.name
const canSend = deliveryAccount.messaging_status === 'active' && deliveryAccount.usable
const repliesLive = deliveryAccount.webhooks_status === 'active'
async function saveDelivery(event: FormEvent) {
event.preventDefault()
setDeliveryBusy(true)
setError('')
try {
setDeliveryAccount(await whatsappApi.enableDelivery(account.id, appSecret.trim()))
setAppSecret('')
} catch (reason) {
setError(reason instanceof Error ? reason.message : 'Replies could not be turned on')
} finally {
setDeliveryBusy(false)
}
}
async function loadMessages() {
setMessages(await whatsappApi.messages(account.id))
@ -272,7 +290,17 @@ export function CustomerWhatsAppInbox({ account, onBack }: { account: WhatsAppAc
<button type="button" className="wa-ghost" onClick={() => void loadMessages()}><RefreshCw size={14} /> Refresh</button>
</div>
</div>
{!canSend && <p className="wa-biz-notice">{account.last_error || 'You can read messages already delivered here. Sending stays off until Meta connects this number.'}</p>}
{!canSend && <p className="wa-biz-notice">{deliveryAccount.last_error || 'You can read messages already delivered here. Sending stays off until Meta connects this number.'}</p>}
{canSend && !repliesLive && (
<form className="wa-biz-notice" onSubmit={(event) => void saveDelivery(event)}>
<p>WhatsApp accepted messages from this number, but delivery updates and replies are still going to the Meta app that created the token. Paste that app’s App secret so they arrive here. In Meta: the app → App settings → Basic → App secret.</p>
<label className="explorer-input">
<strong>App secret</strong>
<input type="password" value={appSecret} onChange={(event) => setAppSecret(event.target.value)} autoComplete="off" required />
</label>
<button className="primary-button" type="submit" disabled={deliveryBusy}>Turn on replies</button>
</form>
)}
<div className="wa-inbox">
<aside className="wa-list">
<div className="wa-list-head">

View file

@ -0,0 +1,251 @@
import { Loader2 } from 'lucide-react'
import { useEffect, useState, type FormEvent } from 'react'
import { Link } from 'react-router-dom'
import { whatsappApi, type WhatsAppAccount, type WhatsAppTemplateRow } from '../../lib/api'
const TEAM_TEMPLATE_NAME = 'urmi_team_aircheck'
const TEAM_TEMPLATE_BODY = "Team, the broadcast desk is on air. This is the first note Urmi is sending through Meta's marketing line, and it is written for the people building it. Read it on your phone, then bring it to standup so we can close the test."
type BroadcastResult = {
template_name: string
sent: number
failed: number
results: { to: string; status: string; error?: string; message_id?: string | null }[]
}
type CreatedTemplate = {
name: string
status: string
}
export function WhatsAppBroadcastPage() {
const [accounts, setAccounts] = useState<WhatsAppAccount[]>([])
const [accountId, setAccountId] = useState('')
const [templates, setTemplates] = useState<WhatsAppTemplateRow[]>([])
const [templatesReady, setTemplatesReady] = useState(false)
const [templateName, setTemplateName] = useState(TEAM_TEMPLATE_NAME)
const [templateLanguage, setTemplateLanguage] = useState('en')
const [draftName, setDraftName] = useState(TEAM_TEMPLATE_NAME)
const [draftBody, setDraftBody] = useState(TEAM_TEMPLATE_BODY)
const [creating, setCreating] = useState(false)
const [created, setCreated] = useState<CreatedTemplate | null>(null)
const [templateTick, setTemplateTick] = useState(0)
const [recipients, setRecipients] = useState('')
const [bodyValues, setBodyValues] = useState('')
const [strict, setStrict] = useState(true)
const [loading, setLoading] = useState(true)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [result, setResult] = useState<BroadcastResult | null>(null)
useEffect(() => {
whatsappApi.accounts()
.then((rows) => {
const ready = rows.filter((row) => row.messaging_status === 'active' && row.phones.some((phone) => phone.status === 'connected'))
setAccounts(ready)
if (ready[0]) setAccountId(ready[0].id)
})
.catch((reason) => setError(reason instanceof Error ? reason.message : 'Could not load WhatsApp accounts'))
.finally(() => setLoading(false))
}, [])
useEffect(() => {
if (!accountId) return
setTemplatesReady(false)
whatsappApi.templates(accountId)
.then((payload) => {
const marketing = payload.templates.filter((item) => (item.category || '').toUpperCase() === 'MARKETING')
setTemplates(marketing)
setTemplatesReady(payload.available)
const approved = marketing.find((item) => (item.status || '').toUpperCase() === 'APPROVED' && item.name)
if (approved?.name) {
setTemplateName(approved.name)
setTemplateLanguage(approved.language || 'en')
}
})
.catch(() => {
setTemplates([])
setTemplatesReady(false)
})
}, [accountId, templateTick])
async function createTemplate(event: FormEvent) {
event.preventDefault()
setCreating(true)
setError('')
setCreated(null)
try {
const payload = await whatsappApi.createMarketingTemplate(accountId, {
name: draftName.trim(),
language: 'en',
body: draftBody.trim(),
})
setCreated(payload)
setTemplateName(payload.name)
setTemplateLanguage(payload.language || 'en')
setTemplateTick((value) => value + 1)
} catch (reason) {
setError(reason instanceof Error ? reason.message : 'Meta did not accept this template')
} finally {
setCreating(false)
}
}
async function submit(event: FormEvent) {
event.preventDefault()
setBusy(true)
setError('')
setResult(null)
const numbers = recipients.split(/[\n,]/).map((item) => item.trim()).filter(Boolean)
const parameters = bodyValues.split('\n').map((item) => item.trim()).filter(Boolean)
try {
const payload = await whatsappApi.sendBroadcast(accountId, {
template_name: templateName.trim(),
template_language: templateLanguage.trim() || 'en',
recipients: numbers,
body_parameters: parameters,
product_policy: strict ? 'STRICT' : 'CLOUD_API_FALLBACK',
})
setResult(payload)
} catch (reason) {
setError(reason instanceof Error ? reason.message : 'Meta did not accept this broadcast')
} finally {
setBusy(false)
}
}
const approved = templates.filter((item) => (item.status || '').toUpperCase() === 'APPROVED' && item.name)
const pending = templates.filter((item) => (item.status || '').toUpperCase() !== 'APPROVED' && item.name)
return (
<div className="wa-biz wa-token-page">
<div className="account-heading">
<span className="eyebrow">Messages</span>
<h1>WhatsApp broadcast</h1>
<p>Sends a marketing template through Meta’s marketing endpoint. Chat replies stay on the WhatsApp page.</p>
</div>
{!loading && accounts.length > 0 && (
<form className="wa-biz-card" onSubmit={createTemplate}>
<h2>Create the template here</h2>
<p>Urmi submits this to Meta as a Marketing template on the connected account. Meta still has to approve it before a broadcast can send. That usually takes a few minutes.</p>
<div className="wa-token-form">
<label className="explorer-input">
<strong>Template name</strong>
<span>Lowercase letters, numbers, and underscores. Meta uses this name when you send.</span>
<input value={draftName} onChange={(event) => setDraftName(event.target.value)} required />
</label>
<label className="explorer-input">
<strong>Message</strong>
<span>English, no header, buttons, or placeholders. Written for the internal team.</span>
<textarea value={draftBody} onChange={(event) => setDraftBody(event.target.value)} rows={5} required />
</label>
<button className="primary-button" type="submit" disabled={creating || !accountId}>
{creating ? <Loader2 size={16} className="wa-spin" /> : null}
Submit template to Meta
</button>
</div>
{created && (
<p className="wa-token-result">{created.name} is {created.status.toLowerCase()}. Send it after Meta marks it approved.</p>
)}
</form>
)}
{error && <p className="auth-error">{error}</p>}
{loading && <div className="auth-loading">Loading accounts…</div>}
{!loading && accounts.length === 0 && (
<section className="panel placeholder">
<p>Connect a WhatsApp number before sending a broadcast.</p>
<Link className="primary-button" to="/console/whatsapp/token">Add a WhatsApp token</Link>
</section>
)}
{!loading && accounts.length > 0 && (
<form className="wa-biz-card" onSubmit={submit}>
<div className="wa-token-form">
<label className="explorer-input">
<strong>Account</strong>
<span>The connected number this broadcast is sent from.</span>
<select value={accountId} onChange={(event) => setAccountId(event.target.value)}>
{accounts.map((account) => (
<option key={account.id} value={account.id}>
{account.name} · {account.primary_phone?.display_phone || account.phones[0]?.display_phone || 'WhatsApp'}
</option>
))}
</select>
</label>
<label className="explorer-input">
<strong>Marketing template</strong>
<span>
{templatesReady
? approved.length
? 'Approved marketing templates on this account.'
: pending.length
? `${pending.map((item) => item.name).join(', ')} is waiting for Meta’s approval.`
: 'No approved marketing template yet. Submit the team message above, then come back when Meta approves it.'
: 'Template list is unavailable. You can still type the approved template name.'}
</span>
{approved.length > 0 ? (
<select
value={templateName}
onChange={(event) => {
const next = approved.find((item) => item.name === event.target.value)
setTemplateName(event.target.value)
if (next?.language) setTemplateLanguage(next.language)
}}
>
{approved.map((item) => (
<option key={`${item.name}-${item.language}`} value={item.name || ''}>
{item.name} ({item.language || 'en'})
</option>
))}
</select>
) : (
<input value={templateName} onChange={(event) => setTemplateName(event.target.value)} required />
)}
</label>
<label className="explorer-input">
<strong>Language</strong>
<span>Use the language code Meta shows on the template, such as en.</span>
<input value={templateLanguage} onChange={(event) => setTemplateLanguage(event.target.value)} required />
</label>
<label className="explorer-input">
<strong>Recipients</strong>
<span>One WhatsApp number per line, up to 20. Include the country code.</span>
<textarea value={recipients} onChange={(event) => setRecipients(event.target.value)} rows={4} required placeholder="9198XXXXXXXX" />
</label>
<label className="explorer-input">
<strong>Body values</strong>
<span>Leave this empty for the team aircheck. If a template has {'{{1}}'}, {'{{2}}'}, put one value per line in that order.</span>
<textarea value={bodyValues} onChange={(event) => setBodyValues(event.target.value)} rows={3} />
</label>
<label className="explorer-input">
<strong>Marketing endpoint only</strong>
<span>Leave this on to test Meta’s marketing API. Turn it off only if Meta says this account is not onboarded yet and you still want the message delivered.</span>
<input type="checkbox" checked={strict} onChange={(event) => setStrict(event.target.checked)} />
</label>
<button className="primary-button" type="submit" disabled={busy || !accountId}>
{busy ? <Loader2 size={16} className="wa-spin" /> : null}
Send broadcast
</button>
</div>
</form>
)}
{result && (
<section className="wa-biz-card wa-token-result">
<h2>{result.sent} sent, {result.failed} failed</h2>
<ul className="wa-broadcast-results">
{result.results.map((item) => (
<li key={`${item.to}-${item.message_id || item.error || item.status}`}>
<span>{item.to}</span>
<span>{item.status === 'sent' ? 'Sent' : item.error || 'Failed'}</span>
</li>
))}
</ul>
</section>
)}
</div>
)
}