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:
@@ -4,19 +4,24 @@
|
||||
|--------------------------------------------------------------------------
|
||||
| Processa a notification_queue para channel = 'whatsapp' via Evolution API.
|
||||
|
|
||||
| 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 ativos; se vier body.tenant_id, processa só aquele (modo single).
|
||||
|
|
||||
| Fluxo por item:
|
||||
| 1. Busca pendentes (channel='whatsapp', status='pendente', scheduled_at <= now)
|
||||
| 2. Marca como 'processando' (lock otimista)
|
||||
| 3. Busca credenciais Evolution API em notification_channels
|
||||
| 4. Resolve template: tenant → global fallback
|
||||
| 3. Busca credenciais Evolution API em notification_channels (tdb)
|
||||
| 4. Resolve template (todos os templates do schema pertencem ao tenant)
|
||||
| 5. Renderiza variáveis {{var}}
|
||||
| 6. Envia via Evolution API (sendText)
|
||||
| 7. Atualiza queue + insere notification_logs
|
||||
| 7. Atualiza queue + insere notification_logs (tdb)
|
||||
| 8. Em erro: retry com backoff ou marca 'falhou'
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
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': '*',
|
||||
@@ -73,22 +78,15 @@ async function sendWhatsapp(
|
||||
}
|
||||
}
|
||||
|
||||
// ── Main handler ───────────────────────────────────────────────
|
||||
// ── Processa a fila de UM tenant ───────────────────────────────
|
||||
|
||||
Deno.serve(async (req: Request) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response('ok', { headers: corsHeaders })
|
||||
}
|
||||
|
||||
const supabase = createClient(
|
||||
Deno.env.get('SUPABASE_URL')!,
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
|
||||
)
|
||||
type Result = { id: string; status: string; error?: string }
|
||||
|
||||
async function processTenantQueue(tdb: SupabaseClient): 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')
|
||||
@@ -98,28 +96,17 @@ 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: 'Nenhum WhatsApp na fila', processed: 0 }),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
|
||||
const results: Array<{ id: string; status: string; error?: string }> = []
|
||||
const results: Result[] = []
|
||||
|
||||
// Cache de credenciais por owner para evitar queries repetidas
|
||||
const credentialsCache = new Map<string, EvolutionCredentials | null>()
|
||||
|
||||
for (const item of items) {
|
||||
// 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)
|
||||
@@ -131,11 +118,11 @@ Deno.serve(async (req: Request) => {
|
||||
}
|
||||
|
||||
try {
|
||||
// 3. Busca credenciais Evolution API (com cache)
|
||||
// 3. Busca credenciais Evolution API (com cache por owner)
|
||||
let credentials = credentialsCache.get(item.owner_id)
|
||||
|
||||
if (credentials === undefined) {
|
||||
const { data: channel } = await supabase
|
||||
const { data: channel } = await tdb
|
||||
.from('notification_channels')
|
||||
.select('credentials')
|
||||
.eq('owner_id', item.owner_id)
|
||||
@@ -144,49 +131,34 @@ Deno.serve(async (req: Request) => {
|
||||
.is('deleted_at', null)
|
||||
.maybeSingle()
|
||||
|
||||
// Fallback: busca por tenant_id
|
||||
if (!channel?.credentials && item.tenant_id) {
|
||||
const { data: tenantChannel } = await supabase
|
||||
.from('notification_channels')
|
||||
.select('credentials')
|
||||
.eq('tenant_id', item.tenant_id)
|
||||
.eq('channel', 'whatsapp')
|
||||
.eq('is_active', true)
|
||||
.is('deleted_at', null)
|
||||
.maybeSingle()
|
||||
|
||||
credentials = tenantChannel?.credentials as EvolutionCredentials | null
|
||||
} else {
|
||||
credentials = channel?.credentials as EvolutionCredentials | null
|
||||
}
|
||||
|
||||
credentialsCache.set(item.owner_id, credentials ?? null)
|
||||
credentials = (channel?.credentials as EvolutionCredentials | null) ?? null
|
||||
credentialsCache.set(item.owner_id, credentials)
|
||||
}
|
||||
|
||||
if (!credentials) {
|
||||
throw new Error('Canal WhatsApp não encontrado ou inativo para este owner')
|
||||
}
|
||||
|
||||
// 4. Resolve template: tenant → global fallback
|
||||
// 4. Resolve template: todos os templates do schema pertencem ao tenant.
|
||||
// Preferimos o do owner; se não houver, caímos no default do schema.
|
||||
let templateBody: string | null = null
|
||||
|
||||
const { data: tenantTpl } = await supabase
|
||||
const { data: ownerTpl } = await tdb
|
||||
.from('notification_templates')
|
||||
.select('body_text, is_active')
|
||||
.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) {
|
||||
templateBody = tenantTpl.body_text
|
||||
if (ownerTpl) {
|
||||
templateBody = ownerTpl.body_text
|
||||
} 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)
|
||||
@@ -194,7 +166,7 @@ Deno.serve(async (req: Request) => {
|
||||
.is('deleted_at', null)
|
||||
.maybeSingle()
|
||||
|
||||
templateBody = globalTpl?.body_text || null
|
||||
templateBody = defaultTpl?.body_text || null
|
||||
}
|
||||
|
||||
if (!templateBody) {
|
||||
@@ -209,7 +181,7 @@ Deno.serve(async (req: Request) => {
|
||||
const sendResult = await sendWhatsapp(credentials, item.recipient_address, message)
|
||||
|
||||
// 7. Sucesso
|
||||
await supabase
|
||||
await tdb
|
||||
.from('notification_queue')
|
||||
.update({
|
||||
status: 'enviado',
|
||||
@@ -218,8 +190,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,
|
||||
@@ -245,7 +216,7 @@ Deno.serve(async (req: Request) => {
|
||||
const isExhausted = attempts >= maxAttempts
|
||||
const retryMs = attempts * 2 * 60 * 1000
|
||||
|
||||
await supabase
|
||||
await tdb
|
||||
.from('notification_queue')
|
||||
.update({
|
||||
status: isExhausted ? 'falhou' : 'pendente',
|
||||
@@ -254,8 +225,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,
|
||||
@@ -273,12 +243,73 @@ 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()
|
||||
|
||||
// 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))
|
||||
} else {
|
||||
const tenants = await listTenantSchemas(admin)
|
||||
for (const t of tenants) {
|
||||
try {
|
||||
const tdb = admin.schema(t.schema)
|
||||
results.push(...await processTenantQueue(tdb))
|
||||
} catch (e) {
|
||||
console.error(`[process-notification-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: 'Nenhum 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 retried = results.filter(r => r.status === 'retry').length
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ processed: results.length, sent, failed, retried, details: results }),
|
||||
JSON.stringify({ processed: results.length, sent, failed, retried, details: results, tenantErrors: errors }),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user