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
@@ -31,6 +31,7 @@ import {
registerOptout,
type TwilioChannel
} from '../_shared/whatsapp-hooks.ts'
import { tenantDbForId } from '../_shared/tenant.ts'
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
@@ -73,6 +74,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 formData = await req.formData()
const from = stripWhatsappPrefix(formData.get('From') as string)
@@ -111,8 +113,7 @@ Deno.serve(async (req: Request) => {
WaId: formData.get('WaId') ?? null,
}
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: 'inbound',
@@ -144,23 +145,22 @@ Deno.serve(async (req: Request) => {
try {
// Busca canal Twilio (uma vez) — reutilizado por registerOptout/autoReply
const { data: channel } = await supabase
const { data: channel } = await tdb
.from('notification_channels')
.select('credentials, provider, twilio_subaccount_sid, twilio_phone_number, is_active')
.eq('tenant_id', tenantId)
.eq('channel', 'whatsapp')
.is('deleted_at', null)
.maybeSingle()
if (channel && channel.is_active && channel.provider === 'twilio') {
// 1) Opt-IN (voltar) tem prioridade
if (await maybeOptIn(supabase, tenantId, from, cleanBody)) {
if (await maybeOptIn(tdb, from, cleanBody)) {
optoutAction = 'in'
}
// 2) Opt-OUT por keyword — envia ack via Twilio (deduz 1 credito)
if (!optoutAction) {
const keyword = await detectOptoutKeyword(supabase, tenantId, cleanBody)
const keyword = await detectOptoutKeyword(tdb, cleanBody)
if (keyword) {
const optoutSendFn = makeTwilioCreditedSendFn(
supabase,
@@ -169,8 +169,7 @@ Deno.serve(async (req: Request) => {
'Opt-out ack WhatsApp'
)
await registerOptout(
supabase,
tenantId,
tdb,
from,
patientId,
cleanBody,
@@ -193,6 +192,7 @@ Deno.serve(async (req: Request) => {
'Bot de triagem WhatsApp'
)
const botRes = await maybeProcessBot(
tdb,
supabase,
tenantId,
threadKey,
@@ -214,8 +214,7 @@ Deno.serve(async (req: Request) => {
'Auto-reply WhatsApp'
)
autoReplyResult = await maybeSendAutoReply(
supabase,
tenantId,
tdb,
threadKey,
from,
'twilio',