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
@@ -23,7 +23,8 @@
|--------------------------------------------------------------------------
*/
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
import { createClient, type SupabaseClient } from 'https://esm.sh/@supabase/supabase-js@2'
import { adminClient, tenantDbForId, listTenantSchemas } from '../_shared/tenant.ts'
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
@@ -71,27 +72,42 @@ Deno.serve(async (req: Request) => {
const userId = authData.user.id
// Service role pra bypass RLS
const supaSvc = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
)
const supaSvc = adminClient()
// Localiza o canal alvo
let target: { id: string, tenant_id: string, channel: string, provider: string, metadata: Record<string, unknown> | null } | null = null
// schema-per-tenant: notification_channels vive no schema do tenant (sem
// coluna tenant_id). Resolvemos o schema (tdb) + o tenant dono (targetTenantId).
let tdb: SupabaseClient | null = null
let targetTenantId: string | null = null
let target: { id: string, channel: string, provider: string, metadata: Record<string, unknown> | null } | null = null
if (channelId) {
const { data } = await supaSvc
.from('notification_channels')
.select('id, tenant_id, channel, provider, metadata')
.eq('id', channelId)
.maybeSingle()
target = data
// Só temos channel_id — varremos os schemas provisionados pra achar o canal.
// NÃO filtramos por deleted_at: o alvo geralmente está soft-deleted.
for (const ref of await listTenantSchemas(supaSvc)) {
const candidate = supaSvc.schema(ref.schema)
const { data, error } = await candidate
.from('notification_channels')
.select('id, channel, provider, metadata')
.eq('id', channelId)
.maybeSingle()
if (error) {
console.warn('[reactivate] busca canal em', ref.schema, ':', error.message)
continue
}
if (data) { tdb = candidate; targetTenantId = ref.tenantId; target = data; break }
}
} else {
// Busca o mais recente soft-deleted daquele tenant+provider
const { data } = await supaSvc
// tenant_id + provider: schema conhecido. Busca o mais recente daquele provider.
try {
tdb = await tenantDbForId(supaSvc, tenantId!)
} catch (e) {
console.error('[reactivate] schema indisponível:', (e as Error).message)
return json({ ok: false, error: 'tenant_invalido' }, 400)
}
targetTenantId = tenantId!
const { data } = await tdb
.from('notification_channels')
.select('id, tenant_id, channel, provider, metadata')
.eq('tenant_id', tenantId!)
.select('id, channel, provider, metadata')
.eq('provider', provider!)
.eq('channel', 'whatsapp')
.order('created_at', { ascending: false })
@@ -100,7 +116,7 @@ Deno.serve(async (req: Request) => {
target = data
}
if (!target) return json({ ok: false, error: 'channel_not_found' }, 404)
if (!tdb || !targetTenantId || !target) return json({ ok: false, error: 'channel_not_found' }, 404)
// Autoriza: saas_admin OU membro ativo do tenant
const { data: isAdmin } = await supaSvc.rpc('is_saas_admin')
@@ -109,7 +125,7 @@ Deno.serve(async (req: Request) => {
const { data: membership } = await supaSvc
.from('tenant_members')
.select('id')
.eq('tenant_id', target.tenant_id)
.eq('tenant_id', targetTenantId)
.eq('user_id', userId)
.eq('status', 'active')
.maybeSingle()
@@ -117,20 +133,19 @@ Deno.serve(async (req: Request) => {
}
if (!authorized) return json({ ok: false, error: 'forbidden' }, 403)
// Exclusividade: soft-deleta outros canais ativos do mesmo tenant+channel
// (se estava Twilio ativo e reativa Evolution, Twilio é desativado)
// Exclusividade: soft-deleta outros canais ativos do mesmo channel (tabela
// tenant — o escopo do tenant já é o próprio schema, sem tenant_id)
const nowIso = new Date().toISOString()
const { data: others } = await supaSvc
const { data: others } = await tdb
.from('notification_channels')
.select('id')
.eq('tenant_id', target.tenant_id)
.eq('channel', target.channel)
.neq('id', target.id)
.is('deleted_at', null)
let deactivatedOthers = 0
if (others && others.length > 0) {
const { error: deactErr } = await supaSvc
const { error: deactErr } = await tdb
.from('notification_channels')
.update({ is_active: false, deleted_at: nowIso })
.in('id', others.map((o) => o.id))
@@ -146,7 +161,7 @@ Deno.serve(async (req: Request) => {
const cleanedMeta: Record<string, unknown> = { ...(target.metadata || {}) }
delete cleanedMeta.first_unhealthy_at
const { error: updErr } = await supaSvc
const { error: updErr } = await tdb
.from('notification_channels')
.update({
is_active: true,
@@ -166,7 +181,7 @@ Deno.serve(async (req: Request) => {
ok: true,
channel_id: target.id,
provider: target.provider,
tenant_id: target.tenant_id,
tenant_id: targetTenantId,
deactivated_others: deactivatedOthers
})
} catch (err) {