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:
Leonardo
2026-06-13 08:44:09 -03:00
parent ba8348d4a6
commit 9b21642e15
27 changed files with 1291 additions and 835 deletions
@@ -28,6 +28,7 @@ import {
registerOptout,
type SendFn
} from '../_shared/whatsapp-hooks.ts'
import { tenantDbForId } from '../_shared/tenant.ts'
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
@@ -136,12 +137,11 @@ function base64ToBytes(b64: string): Uint8Array {
type EvolutionCreds = { apiUrl: string; apiKey: string; instance: string }
// Busca credenciais Evolution do tenant em notification_channels
async function getTenantEvolutionCreds(supa: SupabaseClient, tenantId: string): Promise<EvolutionCreds | null> {
const { data: channel, error } = await supa
// Busca credenciais Evolution do tenant em notification_channels (schema do tenant)
async function getTenantEvolutionCreds(tdb: SupabaseClient): Promise<EvolutionCreds | null> {
const { data: channel, error } = await tdb
.from('notification_channels')
.select('credentials')
.eq('tenant_id', tenantId)
.eq('channel', 'whatsapp')
.is('deleted_at', null)
.maybeSingle()
@@ -259,6 +259,7 @@ Deno.serve(async (req: Request) => {
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
)
const tdb = await tenantDbForId(supabase, tenantId)
const payload = await req.json().catch(() => null)
if (!payload || typeof payload !== 'object') {
@@ -292,10 +293,9 @@ Deno.serve(async (req: Request) => {
patch.read_by_recipient_at = new Date().toISOString()
patch.delivered_at = patch.delivered_at ?? new Date().toISOString()
}
await supabase
await tdb
.from('conversation_messages')
.update(patch)
.eq('tenant_id', tenantId)
.eq('provider_message_id', msgId)
.eq('direction', 'outbound')
}
@@ -340,7 +340,7 @@ Deno.serve(async (req: Request) => {
let storedMediaUrl: string | null = parts.mediaUrl
let mediaError: string | null = null
if (parts.hasEncryptedMedia && messageObj && parts.mediaMime) {
const creds = await getTenantEvolutionCreds(supabase, tenantId)
const creds = await getTenantEvolutionCreds(tdb)
if (!creds) {
mediaError = 'creds_not_found'
storedMediaUrl = null
@@ -391,10 +391,9 @@ Deno.serve(async (req: Request) => {
// Dedup outbound echo
if (fromMe && messageId) {
const { data: existing } = await supabase
const { data: existing } = await tdb
.from('conversation_messages')
.select('id')
.eq('tenant_id', tenantId)
.eq('provider_message_id', messageId)
.eq('direction', 'outbound')
.maybeSingle()
@@ -410,8 +409,7 @@ Deno.serve(async (req: Request) => {
const direction = fromMe ? 'outbound' : 'inbound'
const kanbanStatus = fromMe ? 'awaiting_patient' : 'awaiting_us'
const { error: insErr } = await supabase.from('conversation_messages').insert({
tenant_id: tenantId,
const { error: insErr } = await tdb.from('conversation_messages').insert({
patient_id: patientId,
channel: 'whatsapp',
direction,
@@ -438,13 +436,13 @@ Deno.serve(async (req: Request) => {
if (!fromMe && !insErr && fromPhone) {
// SendFn injetado: Evolution nao deduz creditos (provider gratis/self-hosted)
const creds = await getTenantEvolutionCreds(supabase, tenantId)
const creds = await getTenantEvolutionCreds(tdb)
const sendFn: SendFn = creds
? (phone, text) => sendViaEvolution(creds, phone, text)
: async () => ({ ok: false, error: 'creds_missing' })
try {
const optedBackIn = await maybeOptIn(supabase, tenantId, fromPhone, cleanBody)
const optedBackIn = await maybeOptIn(tdb, fromPhone, cleanBody)
if (optedBackIn) optoutAction = 'in'
} catch (err) {
console.error('[optout] opt-in check error:', err)
@@ -452,9 +450,9 @@ Deno.serve(async (req: Request) => {
if (!optoutAction) {
try {
const keyword = await detectOptoutKeyword(supabase, tenantId, cleanBody)
const keyword = await detectOptoutKeyword(tdb, cleanBody)
if (keyword) {
await registerOptout(supabase, tenantId, fromPhone, patientId, cleanBody, keyword, 'evolution', sendFn)
await registerOptout(tdb, fromPhone, patientId, cleanBody, keyword, 'evolution', sendFn)
optoutAction = 'out'
}
} catch (err) {
@@ -471,14 +469,14 @@ Deno.serve(async (req: Request) => {
// a inbound (iniciou sessão ou avançou step), não manda auto-reply
// pra evitar resposta duplicada.
try {
botResult = await maybeProcessBot(supabase, tenantId, threadKey, patientId, fromPhone, cleanBody, sendFn)
botResult = await maybeProcessBot(tdb, supabase, tenantId, threadKey, patientId, fromPhone, cleanBody, sendFn)
} catch (err) {
console.error('[bot] unexpected error:', err)
}
if (!botResult?.processed) {
try {
autoReplyResult = await maybeSendAutoReply(supabase, tenantId, threadKey, fromPhone, 'evolution', sendFn)
autoReplyResult = await maybeSendAutoReply(tdb, threadKey, fromPhone, 'evolution', sendFn)
} catch (err) {
console.error('[auto-reply] unexpected error:', err)
}