F4 schema-per-tenant: edge functions roteiam pro schema do tenant
- _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>
This commit is contained in:
@@ -5,11 +5,15 @@
|
||||
| Processa a notification_queue para channel='whatsapp' e provider='twilio'.
|
||||
| Usa credenciais da SUBCONTA de cada tenant (modelo de subcontas).
|
||||
|
|
||||
| schema-per-tenant: notification_queue/channels/templates/logs vivem no
|
||||
| schema físico de cada tenant (SEM coluna tenant_id). O cron VARRE todos os
|
||||
| tenants; se vier body.tenant_id, processa só aquele (modo single).
|
||||
|
|
||||
| Fluxo:
|
||||
| 1. Busca itens pendentes (channel='whatsapp', status='pendente')
|
||||
| 2. Filtra somente tenants com provider='twilio' em notification_channels
|
||||
| 3. Lock otimista (status → processando)
|
||||
| 4. Resolve template (tenant → global fallback)
|
||||
| 4. Resolve template (templates do schema pertencem ao tenant)
|
||||
| 5. Renderiza variáveis {{var}}
|
||||
| 6. Envia via Twilio usando credenciais da SUBCONTA do tenant
|
||||
| 7. Atualiza queue + insere notification_logs com estimated_cost_brl
|
||||
@@ -17,7 +21,8 @@
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
||||
import type { SupabaseClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
||||
import { adminClient, listTenantSchemas, tenantDbForId, schemaForTenant } from '../_shared/tenant.ts'
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
@@ -82,22 +87,23 @@ function mockSend(to: string, body: string): { sid: string; status: string } {
|
||||
return { sid, status: 'sent' }
|
||||
}
|
||||
|
||||
// ── Main handler ──────────────────────────────────────────────────────────
|
||||
// ── Processa a fila de UM tenant ───────────────────────────────────────────
|
||||
|
||||
Deno.serve(async (req: Request) => {
|
||||
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })
|
||||
type Result = { id: string; status: string; error?: string }
|
||||
|
||||
const supabase = createClient(
|
||||
Deno.env.get('SUPABASE_URL')!,
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
|
||||
)
|
||||
|
||||
const usdBrlRate = parseFloat(Deno.env.get('USD_BRL_RATE') ?? '5.5')
|
||||
interface TwilioChannel {
|
||||
twilio_subaccount_sid: string
|
||||
twilio_phone_number: string
|
||||
cost_per_message_usd: number
|
||||
price_per_message_brl: number
|
||||
credentials: Record<string, string>
|
||||
}
|
||||
|
||||
async function processTenantQueue(tdb: SupabaseClient, usdBrlRate: number): Promise<Result[]> {
|
||||
const now = new Date().toISOString()
|
||||
|
||||
// 1. Busca itens pendentes de WhatsApp
|
||||
const { data: items, error: fetchErr } = await supabase
|
||||
// 1. Busca itens pendentes de WhatsApp deste tenant
|
||||
const { data: items, error: fetchErr } = await tdb
|
||||
.from('notification_queue')
|
||||
.select('*')
|
||||
.eq('channel', 'whatsapp')
|
||||
@@ -106,51 +112,33 @@ Deno.serve(async (req: Request) => {
|
||||
.order('scheduled_at', { ascending: true })
|
||||
.limit(20)
|
||||
|
||||
if (fetchErr) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: fetchErr.message }),
|
||||
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
if (fetchErr) throw new Error(fetchErr.message)
|
||||
if (!items?.length) return []
|
||||
|
||||
if (!items?.length) {
|
||||
return new Response(
|
||||
JSON.stringify({ message: 'Nenhuma mensagem WhatsApp na fila', processed: 0 }),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
|
||||
// Cache de canais por tenant para evitar N+1
|
||||
const channelCache: Record<string, {
|
||||
twilio_subaccount_sid: string
|
||||
twilio_phone_number: string
|
||||
cost_per_message_usd: number
|
||||
price_per_message_brl: number
|
||||
credentials: Record<string, string>
|
||||
} | null> = {}
|
||||
|
||||
async function getChannel(tenantId: string) {
|
||||
if (tenantId in channelCache) return channelCache[tenantId]
|
||||
const { data } = await supabase
|
||||
// Há exatamente um canal twilio whatsapp por tenant (no schema do tenant).
|
||||
// Resolve uma vez (lazy) e reusa.
|
||||
let channel: TwilioChannel | null | undefined = undefined
|
||||
async function getChannel(): Promise<TwilioChannel | null> {
|
||||
if (channel !== undefined) return channel
|
||||
const { data } = await tdb
|
||||
.from('notification_channels')
|
||||
.select('twilio_subaccount_sid, twilio_phone_number, cost_per_message_usd, price_per_message_brl, credentials')
|
||||
.eq('tenant_id', tenantId)
|
||||
.eq('channel', 'whatsapp')
|
||||
.eq('provider', 'twilio')
|
||||
.eq('is_active', true)
|
||||
.is('deleted_at', null)
|
||||
.maybeSingle()
|
||||
channelCache[tenantId] = data
|
||||
return data
|
||||
channel = (data as TwilioChannel | null) ?? null
|
||||
return channel
|
||||
}
|
||||
|
||||
const results: Array<{ id: string; status: string; error?: string }> = []
|
||||
const results: Result[] = []
|
||||
|
||||
for (const item of items) {
|
||||
if (item.attempts >= (item.max_attempts || 5)) continue
|
||||
|
||||
// 2. Lock otimista
|
||||
const { error: lockErr } = await supabase
|
||||
const { error: lockErr } = await tdb
|
||||
.from('notification_queue')
|
||||
.update({ status: 'processando', attempts: item.attempts + 1 })
|
||||
.eq('id', item.id)
|
||||
@@ -163,41 +151,41 @@ Deno.serve(async (req: Request) => {
|
||||
|
||||
try {
|
||||
// 3. Busca canal twilio do tenant
|
||||
const channel = await getChannel(item.tenant_id)
|
||||
if (!channel?.twilio_subaccount_sid) {
|
||||
const ch = await getChannel()
|
||||
if (!ch?.twilio_subaccount_sid) {
|
||||
throw new Error('Tenant não tem subconta Twilio WhatsApp ativa')
|
||||
}
|
||||
|
||||
const subToken = channel.credentials?.subaccount_auth_token
|
||||
const subToken = ch.credentials?.subaccount_auth_token
|
||||
if (!subToken) throw new Error('subaccount_auth_token não encontrado nas credenciais')
|
||||
|
||||
// 4. Resolve template: tenant → global fallback
|
||||
// 4. Resolve template: templates do schema pertencem ao tenant.
|
||||
// Preferimos override do owner; senão default do schema.
|
||||
let template: { body_text: string } | null = null
|
||||
|
||||
const { data: tenantTpl } = await supabase
|
||||
const { data: ownerTpl } = await tdb
|
||||
.from('notification_templates')
|
||||
.select('body_text')
|
||||
.eq('tenant_id', item.tenant_id)
|
||||
.eq('owner_id', item.owner_id)
|
||||
.eq('key', item.template_key)
|
||||
.eq('channel', 'whatsapp')
|
||||
.eq('is_active', true)
|
||||
.is('deleted_at', null)
|
||||
.maybeSingle()
|
||||
|
||||
if (tenantTpl) {
|
||||
template = tenantTpl
|
||||
if (ownerTpl) {
|
||||
template = ownerTpl
|
||||
} else {
|
||||
const { data: globalTpl } = await supabase
|
||||
const { data: defaultTpl } = await tdb
|
||||
.from('notification_templates')
|
||||
.select('body_text')
|
||||
.is('tenant_id', null)
|
||||
.eq('key', item.template_key)
|
||||
.eq('channel', 'whatsapp')
|
||||
.eq('is_default', true)
|
||||
.eq('is_active', true)
|
||||
.is('deleted_at', null)
|
||||
.maybeSingle()
|
||||
template = globalTpl
|
||||
template = defaultTpl
|
||||
}
|
||||
|
||||
if (!template) throw new Error(`Template WhatsApp não encontrado: ${item.template_key}`)
|
||||
@@ -213,19 +201,19 @@ Deno.serve(async (req: Request) => {
|
||||
sendResult = mockSend(item.recipient_address, message)
|
||||
} else {
|
||||
sendResult = await sendWhatsAppViaTwilio(
|
||||
channel.twilio_subaccount_sid,
|
||||
ch.twilio_subaccount_sid,
|
||||
subToken,
|
||||
channel.twilio_phone_number,
|
||||
ch.twilio_phone_number,
|
||||
item.recipient_address,
|
||||
message
|
||||
)
|
||||
}
|
||||
|
||||
// Custo estimado em BRL
|
||||
const costBrl = (channel.cost_per_message_usd ?? 0) * usdBrlRate
|
||||
const costBrl = (ch.cost_per_message_usd ?? 0) * usdBrlRate
|
||||
|
||||
// 7. Sucesso — atualiza fila
|
||||
await supabase
|
||||
await tdb
|
||||
.from('notification_queue')
|
||||
.update({
|
||||
status: 'enviado',
|
||||
@@ -235,8 +223,7 @@ Deno.serve(async (req: Request) => {
|
||||
.eq('id', item.id)
|
||||
|
||||
// 7b. Insere no log
|
||||
await supabase.from('notification_logs').insert({
|
||||
tenant_id: item.tenant_id,
|
||||
await tdb.from('notification_logs').insert({
|
||||
owner_id: item.owner_id,
|
||||
queue_id: item.id,
|
||||
agenda_evento_id: item.agenda_evento_id,
|
||||
@@ -264,7 +251,7 @@ Deno.serve(async (req: Request) => {
|
||||
const isExhausted = attempts >= maxAttempts
|
||||
const retryMs = Math.min(attempts * 2 * 60 * 1000, 30 * 60 * 1000) // max 30min
|
||||
|
||||
await supabase
|
||||
await tdb
|
||||
.from('notification_queue')
|
||||
.update({
|
||||
status: isExhausted ? 'falhou' : 'pendente',
|
||||
@@ -273,8 +260,7 @@ Deno.serve(async (req: Request) => {
|
||||
})
|
||||
.eq('id', item.id)
|
||||
|
||||
await supabase.from('notification_logs').insert({
|
||||
tenant_id: item.tenant_id,
|
||||
await tdb.from('notification_logs').insert({
|
||||
owner_id: item.owner_id,
|
||||
queue_id: item.id,
|
||||
agenda_evento_id: item.agenda_evento_id,
|
||||
@@ -293,12 +279,72 @@ Deno.serve(async (req: Request) => {
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
// ── Main handler ──────────────────────────────────────────────────────────
|
||||
|
||||
Deno.serve(async (req: Request) => {
|
||||
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })
|
||||
|
||||
const admin = adminClient()
|
||||
const usdBrlRate = parseFloat(Deno.env.get('USD_BRL_RATE') ?? '5.5')
|
||||
|
||||
// Modo single-tenant se body.tenant_id; senão varre todos.
|
||||
let bodyTenantId: string | null = null
|
||||
try {
|
||||
const body = await req.json()
|
||||
bodyTenantId = body?.tenant_id ?? null
|
||||
} catch {
|
||||
// sem body / body inválido → modo varredura
|
||||
}
|
||||
|
||||
const results: Result[] = []
|
||||
const errors: Array<{ tenantId: string; error: string }> = []
|
||||
|
||||
try {
|
||||
if (bodyTenantId) {
|
||||
const schema = await schemaForTenant(admin, bodyTenantId)
|
||||
if (!schema) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: `schema indisponível para tenant ${bodyTenantId}` }),
|
||||
{ status: 404, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
const tdb = await tenantDbForId(admin, bodyTenantId)
|
||||
results.push(...await processTenantQueue(tdb, usdBrlRate))
|
||||
} else {
|
||||
const tenants = await listTenantSchemas(admin)
|
||||
for (const t of tenants) {
|
||||
try {
|
||||
const tdb = admin.schema(t.schema)
|
||||
results.push(...await processTenantQueue(tdb, usdBrlRate))
|
||||
} catch (e) {
|
||||
console.error(`[process-whatsapp-queue] tenant ${t.tenantId} falhou:`, e.message)
|
||||
errors.push({ tenantId: t.tenantId, error: e.message })
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: err.message }),
|
||||
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
|
||||
if (!results.length && !errors.length) {
|
||||
return new Response(
|
||||
JSON.stringify({ message: 'Nenhuma mensagem WhatsApp na fila', processed: 0 }),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
|
||||
const sent = results.filter(r => r.status === 'enviado').length
|
||||
const failed = results.filter(r => r.status === 'falhou').length
|
||||
const retry = results.filter(r => r.status === 'retry').length
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ processed: results.length, sent, failed, retry, details: results }),
|
||||
JSON.stringify({ processed: results.length, sent, failed, retry, details: results, tenantErrors: errors }),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user