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
@@ -11,6 +11,7 @@
*/
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
import { adminClient, listTenantSchemas } from '../_shared/tenant.ts'
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
@@ -48,20 +49,29 @@ 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()
// Busca o canal
const { data: channel, error: chErr } = await supaSvc
.from('notification_channels')
.select('id, tenant_id')
.eq('id', channelId)
.is('deleted_at', null)
.maybeSingle()
// schema-per-tenant: notification_channels vive no schema do tenant (sem
// coluna tenant_id) e o caller só manda channel_id. Varremos os schemas
// provisionados pra localizar o canal e descobrir o tenant dono.
let tdb = null
let tenantId: string | null = null
for (const ref of await listTenantSchemas(supaSvc)) {
const candidate = supaSvc.schema(ref.schema)
const { data, error } = await candidate
.from('notification_channels')
.select('id')
.eq('id', channelId)
.is('deleted_at', null)
.maybeSingle()
if (error) {
console.warn('[deactivate] busca canal em', ref.schema, ':', error.message)
continue
}
if (data) { tdb = candidate; tenantId = ref.tenantId; break }
}
if (chErr || !channel) return json({ ok: false, error: 'channel_not_found' }, 404)
if (!tdb || !tenantId) return json({ ok: false, error: 'channel_not_found' }, 404)
// Autoriza: user deve ser saas_admin OU membro ativo do tenant dono do canal
const { data: isAdmin } = await supaSvc.rpc('is_saas_admin')
@@ -70,7 +80,7 @@ Deno.serve(async (req: Request) => {
const { data: membership } = await supaSvc
.from('tenant_members')
.select('id')
.eq('tenant_id', channel.tenant_id)
.eq('tenant_id', tenantId)
.eq('user_id', userId)
.eq('status', 'active')
.maybeSingle()
@@ -78,8 +88,8 @@ Deno.serve(async (req: Request) => {
}
if (!authorized) return json({ ok: false, error: 'forbidden' }, 403)
// Desativa (soft-delete)
const { error: updErr } = await supaSvc
// Desativa (soft-delete) — tabela tenant
const { error: updErr } = await tdb
.from('notification_channels')
.update({
is_active: false,