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:
@@ -7,17 +7,31 @@
|
||||
|
|
||||
| Runtime: Deno (Supabase Edge Functions)
|
||||
| Linguagem: JavaScript puro
|
||||
|
|
||||
| ── Schema-per-tenant ──
|
||||
| notification_logs / notification_preferences / patients vivem no schema
|
||||
| físico `tenant_<slug>` (SEM coluna tenant_id). Este webhook NÃO recebe
|
||||
| tenant_id na URL, então resolve o tenant assim:
|
||||
| - Meta: `value.metadata.phone_number_id` → resolveTenantByChannel
|
||||
| (channel_routing.sender_address). Cada `change` é resolvido pro seu tenant.
|
||||
| - Status sem identificador de canal (Evolution messages.update, ou Meta
|
||||
| quando o phone_number_id não casa): faz fan-out por listTenantSchemas,
|
||||
| procurando o log pelo provider_message_id no schema de cada tenant.
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
||||
import {
|
||||
adminClient,
|
||||
resolveTenantByChannel,
|
||||
listTenantSchemas,
|
||||
} from '../_shared/tenant.ts'
|
||||
|
||||
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')
|
||||
const SUPABASE_SERVICE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')
|
||||
const EVOLUTION_API_KEY = Deno.env.get('EVOLUTION_API_KEY') || ''
|
||||
const META_VERIFY_TOKEN = Deno.env.get('META_VERIFY_TOKEN') || ''
|
||||
|
||||
const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY)
|
||||
// Client service_role no public — usado pra globais (channel_routing, tenants)
|
||||
// e como base pra derivar os clients de schema de cada tenant.
|
||||
const admin = adminClient()
|
||||
|
||||
|
||||
Deno.serve(async (req) => {
|
||||
@@ -58,6 +72,9 @@ Deno.serve(async (req) => {
|
||||
* Eventos relevantes:
|
||||
* - messages.update: status de entrega (enviado, entregue, lido)
|
||||
* - messages.upsert: mensagem recebida (para detectar "SAIR")
|
||||
*
|
||||
* Nota: o webhook Evolution não traz identificador de canal/tenant aqui, então
|
||||
* tanto status quanto opt-out fazem fan-out por todos os schemas de tenant.
|
||||
*/
|
||||
async function handleEvolutionWebhook (req, body) {
|
||||
// Validação básica da API key
|
||||
@@ -96,7 +113,8 @@ async function handleEvolutionWebhook (req, body) {
|
||||
return jsonResponse({ ok: true, skipped: `status ${status} ignorado` })
|
||||
}
|
||||
|
||||
await updateLogStatus(messageId, mappedStatus)
|
||||
// Sem identificador de canal: procura o log em cada schema de tenant.
|
||||
await updateLogStatusFanout(messageId, mappedStatus)
|
||||
return jsonResponse({ ok: true, status: mappedStatus })
|
||||
}
|
||||
|
||||
@@ -152,6 +170,11 @@ function handleMetaVerification (url) {
|
||||
|
||||
/**
|
||||
* Processa webhooks da Meta WhatsApp Business API.
|
||||
*
|
||||
* Cada `change` traz `value.metadata.phone_number_id` (o canal Meta do tenant).
|
||||
* Resolvemos o tenant via channel_routing.sender_address pra obter o client do
|
||||
* schema correto. Se não resolver (canal não cadastrado), status cai no fan-out
|
||||
* por message_id; opt-out segue por telefone em todos os schemas.
|
||||
*/
|
||||
async function handleMetaWebhook (body) {
|
||||
const entries = body.entry || []
|
||||
@@ -162,6 +185,15 @@ async function handleMetaWebhook (body) {
|
||||
for (const change of changes) {
|
||||
const value = change.value || {}
|
||||
|
||||
// Identifica o canal Meta (phone_number_id) → tenant/schema
|
||||
const phoneNumberId = value.metadata?.phone_number_id
|
||||
? String(value.metadata.phone_number_id)
|
||||
: null
|
||||
const ref = phoneNumberId
|
||||
? await resolveTenantByChannel(admin, { senderAddress: phoneNumberId })
|
||||
: null
|
||||
const tdb = ref ? admin.schema(ref.schema) : null
|
||||
|
||||
// ── Status de mensagem ────
|
||||
if (value.statuses) {
|
||||
for (const st of value.statuses) {
|
||||
@@ -171,7 +203,12 @@ async function handleMetaWebhook (body) {
|
||||
|
||||
if (messageId && status) {
|
||||
const mappedStatus = status === 'failed' ? 'failed' : status
|
||||
await updateLogStatus(messageId, mappedStatus, errors[0]?.message)
|
||||
if (tdb) {
|
||||
await updateLogStatus(tdb, messageId, mappedStatus, errors[0]?.message)
|
||||
} else {
|
||||
// Canal não resolvido: procura o log em todos os schemas.
|
||||
await updateLogStatusFanout(messageId, mappedStatus, errors[0]?.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,7 +221,8 @@ async function handleMetaWebhook (body) {
|
||||
|
||||
if (['SAIR', 'PARAR', 'STOP', 'CANCELAR MENSAGENS'].includes(text)) {
|
||||
console.log(`[meta] Opt-out detectado: ${phone}`)
|
||||
await handleOptOut(phone, null)
|
||||
// Se resolvemos o tenant, processa só nele; senão, fan-out.
|
||||
await handleOptOut(phone, null, ref ? [ref] : null)
|
||||
}
|
||||
|
||||
// Botão de resposta rápida (quick reply)
|
||||
@@ -204,10 +242,8 @@ async function handleMetaWebhook (body) {
|
||||
|
||||
// ── Helpers compartilhados ──────────────────────────────────
|
||||
|
||||
/**
|
||||
* Atualiza o status no notification_logs com base no provider_message_id.
|
||||
*/
|
||||
async function updateLogStatus (providerMessageId, status, failureReason) {
|
||||
/** Monta o patch de notification_logs a partir do status mapeado. */
|
||||
function buildLogPatch (status, failureReason) {
|
||||
const now = new Date().toISOString()
|
||||
const updateData = { provider_status: status }
|
||||
|
||||
@@ -229,60 +265,120 @@ async function updateLogStatus (providerMessageId, status, failureReason) {
|
||||
updateData.failure_reason = failureReason || 'Falha reportada pelo provedor'
|
||||
break
|
||||
}
|
||||
return updateData
|
||||
}
|
||||
|
||||
const { error } = await supabase
|
||||
/**
|
||||
* Atualiza o status no notification_logs (schema do tenant já resolvido) com
|
||||
* base no provider_message_id. Retorna a contagem afetada (null se erro).
|
||||
*/
|
||||
async function updateLogStatus (tdb, providerMessageId, status, failureReason) {
|
||||
const updateData = buildLogPatch(status, failureReason)
|
||||
|
||||
const { data, error } = await tdb
|
||||
.from('notification_logs')
|
||||
.update(updateData)
|
||||
.eq('provider_message_id', providerMessageId)
|
||||
.select('id')
|
||||
|
||||
if (error) {
|
||||
console.warn(`[updateLogStatus] Erro ao atualizar ${providerMessageId}:`, error.message)
|
||||
return null
|
||||
}
|
||||
return data?.length ?? 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Fan-out: sem canal/tenant conhecido, procura o provider_message_id no
|
||||
* notification_logs de cada schema de tenant e atualiza onde encontrar.
|
||||
* Para no primeiro schema que afetar uma linha (message_id é único globalmente).
|
||||
*
|
||||
* TODO: provider_message_id não tem índice global; com muitos tenants este loop
|
||||
* fica O(n). Idealmente registrar (provider_message_id → tenant) num índice
|
||||
* global no envio (notification_logs/channel_routing) pra resolver em O(1).
|
||||
*/
|
||||
async function updateLogStatusFanout (providerMessageId, status, failureReason) {
|
||||
const updateData = buildLogPatch(status, failureReason)
|
||||
const tenants = await listTenantSchemas(admin)
|
||||
|
||||
for (const t of tenants) {
|
||||
const tdb = admin.schema(t.schema)
|
||||
const { data, error } = await tdb
|
||||
.from('notification_logs')
|
||||
.update(updateData)
|
||||
.eq('provider_message_id', providerMessageId)
|
||||
.select('id')
|
||||
|
||||
if (error) {
|
||||
console.warn(`[updateLogStatusFanout] erro no schema ${t.schema}:`, error.message)
|
||||
continue
|
||||
}
|
||||
if (data && data.length > 0) {
|
||||
return data.length
|
||||
}
|
||||
}
|
||||
|
||||
console.warn(`[updateLogStatusFanout] message ${providerMessageId} não encontrado em nenhum tenant`)
|
||||
return 0
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Processa opt-out: desativa WhatsApp para o paciente e cancela pendentes.
|
||||
* @param {string} phone - número de telefone (apenas dígitos)
|
||||
* @param {string|null} instanceName - nome da instância Evolution (para identificar owner)
|
||||
* @param {string|null} instanceName - nome da instância Evolution (legado, não usado pra resolver schema)
|
||||
* @param {Array|null} tenantsOverride - se informado, restringe a esses tenants;
|
||||
* senão faz fan-out por todos os schemas.
|
||||
*/
|
||||
async function handleOptOut (phone, instanceName) {
|
||||
async function handleOptOut (phone, instanceName, tenantsOverride = null) {
|
||||
// Normaliza telefone
|
||||
const cleanPhone = String(phone).replace(/\D/g, '')
|
||||
if (!cleanPhone) return
|
||||
|
||||
// Busca paciente(s) com esse telefone
|
||||
const { data: patients } = await supabase
|
||||
.from('patients')
|
||||
.select('id, owner_id, telefone')
|
||||
.or(`telefone.like.%${cleanPhone}%`)
|
||||
const tenants = tenantsOverride ?? await listTenantSchemas(admin)
|
||||
let matched = 0
|
||||
|
||||
if (!patients || patients.length === 0) {
|
||||
console.warn(`[opt-out] Nenhum paciente encontrado para ${cleanPhone}`)
|
||||
return
|
||||
for (const t of tenants) {
|
||||
const tdb = admin.schema(t.schema)
|
||||
|
||||
// Busca paciente(s) com esse telefone no schema deste tenant
|
||||
const { data: patients, error: patErr } = await tdb
|
||||
.from('patients')
|
||||
.select('id, owner_id, telefone')
|
||||
.or(`telefone.like.%${cleanPhone}%`)
|
||||
|
||||
if (patErr) {
|
||||
console.warn(`[opt-out] erro buscando paciente no schema ${t.schema}:`, patErr.message)
|
||||
continue
|
||||
}
|
||||
if (!patients || patients.length === 0) continue
|
||||
|
||||
for (const patient of patients) {
|
||||
matched++
|
||||
// Atualiza preferência (o trigger cancela pendentes automaticamente)
|
||||
const { error } = await tdb
|
||||
.from('notification_preferences')
|
||||
.upsert({
|
||||
owner_id: patient.owner_id,
|
||||
patient_id: patient.id,
|
||||
whatsapp_opt_in: false,
|
||||
lgpd_opt_out_date: new Date().toISOString(),
|
||||
lgpd_opt_out_reason: 'Paciente respondeu SAIR no WhatsApp',
|
||||
}, {
|
||||
onConflict: 'owner_id,patient_id',
|
||||
ignoreDuplicates: false,
|
||||
})
|
||||
|
||||
if (error) {
|
||||
console.error(`[opt-out] Erro ao salvar preferência para paciente ${patient.id} (schema ${t.schema}):`, error.message)
|
||||
} else {
|
||||
console.log(`[opt-out] WhatsApp desativado para paciente ${patient.id} (schema ${t.schema})`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const patient of patients) {
|
||||
// Atualiza preferência (o trigger cancela pendentes automaticamente)
|
||||
const { error } = await supabase
|
||||
.from('notification_preferences')
|
||||
.upsert({
|
||||
owner_id: patient.owner_id,
|
||||
tenant_id: patient.owner_id, // será ajustado pelo context
|
||||
patient_id: patient.id,
|
||||
whatsapp_opt_in: false,
|
||||
lgpd_opt_out_date: new Date().toISOString(),
|
||||
lgpd_opt_out_reason: 'Paciente respondeu SAIR no WhatsApp',
|
||||
}, {
|
||||
onConflict: 'owner_id,patient_id',
|
||||
ignoreDuplicates: false,
|
||||
})
|
||||
|
||||
if (error) {
|
||||
console.error(`[opt-out] Erro ao salvar preferência para paciente ${patient.id}:`, error.message)
|
||||
} else {
|
||||
console.log(`[opt-out] WhatsApp desativado para paciente ${patient.id}`)
|
||||
}
|
||||
if (matched === 0) {
|
||||
console.warn(`[opt-out] Nenhum paciente encontrado para ${cleanPhone}`)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user