9b21642e15
- _shared/tenant.ts: helper (adminClient, tenantDbForId, schemaForTenant, listTenantSchemas, resolveTenantByChannel, tenantSchemaName) - _shared/whatsapp-hooks.ts: hooks de tabela tenant recebem tdb; RPCs de credito (deduct/add_whatsapp_credits) e tenant_members seguem em supa+p_tenant_id - inbound (twilio/evolution): tenant_id da URL -> tdb pra conversation_messages e notification_channels - crons de fila (process-notification/email/sms/whatsapp-queue): varrem listTenantSchemas e drenam a fila de cada schema (Q3: filas sao per-tenant); modo single-tenant se body.tenant_id vier - crons reminders/checks (send-session-reminders, conversation-sla-check, whatsapp-heartbeat-check, convert-abandoned-intakes, sync-email-templates): loop por tenant - routing por tenant_id (send-whatsapp-message, send-session-reminder-manual, twilio-provision, de/reactivate-channel, twilio-webhook): tenantDbForId; channel-actions sem tenant_id varrem schemas por channel_id - asaas-*: tenant_id do body -> tdb; asaas-webhook fica global (whatsapp_credit_purchases) - notification-webhook (Meta): resolve tenant via channel_routing por phone_number_id, fan-out por message_id quando nao resolve - caller send-session-reminder-manual passa tenant_id (evento vive no schema) Pendente: save-intake-progress e fluxos anon por token (decisao de roteamento) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
117 lines
4.2 KiB
TypeScript
117 lines
4.2 KiB
TypeScript
/*
|
|
|--------------------------------------------------------------------------
|
|
| Agência PSI — Edge Function: twilio-whatsapp-webhook
|
|
|--------------------------------------------------------------------------
|
|
| Recebe callbacks de status do Twilio para mensagens WhatsApp enviadas
|
|
| pelas subcontas de cada tenant.
|
|
|
|
|
| URL configurada no número de cada subconta:
|
|
| https://<project>.supabase.co/functions/v1/twilio-whatsapp-webhook?tenant_id=<uuid>
|
|
|
|
|
| Eventos recebidos (MessageStatus):
|
|
| queued, failed, sent, delivered, undelivered, read
|
|
|--------------------------------------------------------------------------
|
|
*/
|
|
|
|
import { adminClient, tenantDbForId } from '../_shared/tenant.ts'
|
|
|
|
const corsHeaders = {
|
|
'Access-Control-Allow-Origin': '*',
|
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
|
|
}
|
|
|
|
// Mapeia status Twilio → status interno
|
|
function mapStatus(twilioStatus: string): string | null {
|
|
switch (twilioStatus) {
|
|
case 'delivered': return 'delivered'
|
|
case 'read': return 'read'
|
|
case 'failed':
|
|
case 'undelivered': return 'failed'
|
|
case 'sent': return 'sent'
|
|
default: return null
|
|
}
|
|
}
|
|
|
|
Deno.serve(async (req: Request) => {
|
|
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })
|
|
|
|
// Twilio envia POST com form-encoded
|
|
if (req.method !== 'POST') {
|
|
return new Response('ok', { status: 200, headers: corsHeaders })
|
|
}
|
|
|
|
try {
|
|
const admin = adminClient()
|
|
|
|
const url = new URL(req.url)
|
|
const tenantId = url.searchParams.get('tenant_id')
|
|
|
|
const formData = await req.formData()
|
|
const messageSid = formData.get('MessageSid') as string
|
|
const messageStatus = formData.get('MessageStatus') as string
|
|
const to = formData.get('To') as string
|
|
const errorCode = formData.get('ErrorCode') as string | null
|
|
const errorMessage = formData.get('ErrorMessage') as string | null
|
|
|
|
if (!messageSid || !messageStatus) {
|
|
return new Response('ok', { status: 200, headers: corsHeaders })
|
|
}
|
|
|
|
const internalStatus = mapStatus(messageStatus)
|
|
if (!internalStatus) {
|
|
// Status intermediário (queued, accepted, etc.) — ignora
|
|
return new Response('ok', { status: 200, headers: corsHeaders })
|
|
}
|
|
|
|
// Atualiza notification_logs pelo provider_message_id
|
|
const updateData: Record<string, unknown> = {
|
|
provider_status: messageStatus,
|
|
status: internalStatus,
|
|
}
|
|
|
|
if (internalStatus === 'delivered') {
|
|
updateData.delivered_at = new Date().toISOString()
|
|
} else if (internalStatus === 'read') {
|
|
updateData.read_at = new Date().toISOString()
|
|
updateData.delivered_at = new Date().toISOString()
|
|
} else if (internalStatus === 'failed') {
|
|
updateData.failed_at = new Date().toISOString()
|
|
updateData.failure_reason = errorMessage
|
|
? `${errorCode}: ${errorMessage}`
|
|
: `Twilio status: ${messageStatus}`
|
|
}
|
|
|
|
// notification_logs vive no schema do tenant — precisamos do tenant_id da URL
|
|
// pra resolver o schema. Sem ele não há como localizar o log.
|
|
if (!tenantId) {
|
|
console.warn(`[webhook] ${messageSid} → ${messageStatus} sem tenant_id na URL; não atualiza log`)
|
|
} else {
|
|
try {
|
|
const tdb = await tenantDbForId(admin, tenantId)
|
|
const { error } = await tdb
|
|
.from('notification_logs')
|
|
.update(updateData)
|
|
.eq('provider_message_id', messageSid)
|
|
|
|
if (error) {
|
|
console.error('[webhook] Erro ao atualizar log:', error.message)
|
|
} else {
|
|
console.log(`[webhook] ${messageSid} → ${messageStatus} (tenant: ${tenantId})`)
|
|
}
|
|
} catch (e) {
|
|
console.error('[webhook] schema indisponível pra tenant', tenantId, ':', (e as Error).message)
|
|
}
|
|
}
|
|
|
|
// Twilio espera 200 TwiML vazio ou texto simples
|
|
return new Response('<?xml version="1.0" encoding="UTF-8"?><Response></Response>', {
|
|
status: 200,
|
|
headers: { ...corsHeaders, 'Content-Type': 'text/xml' },
|
|
})
|
|
} catch (e) {
|
|
console.error('[webhook] Erro:', e)
|
|
return new Response('ok', { status: 200, headers: corsHeaders })
|
|
}
|
|
})
|