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
@@ -14,7 +14,7 @@
|--------------------------------------------------------------------------
*/
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
import { adminClient, tenantDbForId } from '../_shared/tenant.ts'
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
@@ -45,13 +45,12 @@ Deno.serve(async (req: Request) => {
)
}
const supabase = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
)
const admin = adminClient()
// email_templates_tenant é TENANT → tdb (schema do tenant)
const tdb = await tenantDbForId(admin, tenant_id)
// 1. Busca todos os templates globais ativos
const { data: globals, error: globalsErr } = await supabase
// 1. Busca todos os templates globais ativos (GLOBAL → admin)
const { data: globals, error: globalsErr } = await admin
.from('email_templates_global')
.select('key, version')
.eq('is_active', true)
@@ -64,11 +63,10 @@ Deno.serve(async (req: Request) => {
)
}
// 2. Busca templates existentes do tenant
const { data: tenantTemplates, error: tenantErr } = await supabase
// 2. Busca templates existentes do tenant (TENANT → tdb, sem tenant_id)
const { data: tenantTemplates, error: tenantErr } = await tdb
.from('email_templates_tenant')
.select('template_key, synced_version')
.eq('tenant_id', tenant_id)
.eq('owner_id', owner_id)
if (tenantErr) throw tenantErr
@@ -84,11 +82,10 @@ Deno.serve(async (req: Request) => {
const existingVersion = tenantMap.get(global.key)
if (existingVersion === undefined) {
// Não existe → INSERT com campos null (herda do global)
const { error: insertErr } = await supabase
// Não existe → INSERT com campos null (herda do global). Tenant → tdb, sem tenant_id.
const { error: insertErr } = await tdb
.from('email_templates_tenant')
.insert({
tenant_id,
owner_id,
template_key: global.key,
subject: null,
@@ -104,11 +101,10 @@ Deno.serve(async (req: Request) => {
}
synced++
} else if (existingVersion < global.version) {
// Existe mas desatualizado → UPDATE apenas synced_version
const { error: updateErr } = await supabase
// Existe mas desatualizado → UPDATE apenas synced_version (tenant → tdb)
const { error: updateErr } = await tdb
.from('email_templates_tenant')
.update({ synced_version: global.version })
.eq('tenant_id', tenant_id)
.eq('owner_id', owner_id)
.eq('template_key', global.key)