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
@@ -30,7 +30,7 @@
| 500 — erro Asaas
|--------------------------------------------------------------------------
*/
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { adminClient, tenantDbForId } from '../_shared/tenant.ts';
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
@@ -63,13 +63,13 @@ Deno.serve(async (req: Request) => {
return json({ ok: false, error: 'invalid_billing_type' }, 400);
}
const supa = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!);
const admin = adminClient();
const tdb = await tenantDbForId(admin, tenantId);
// 1. Verifica gateway habilitado + lê API key do tenant
const { data: settings } = await supa
const { data: settings } = await tdb
.from('payment_settings')
.select('asaas_enabled, asaas_environment, asaas_api_key_sandbox, asaas_api_key_prod')
.eq('tenant_id', tenantId)
.maybeSingle();
if (!settings?.asaas_enabled) {
@@ -87,11 +87,10 @@ Deno.serve(async (req: Request) => {
}
// 2. Lê financial_record + patient
const { data: record } = await supa
const { data: record } = await tdb
.from('financial_records')
.select('id, tenant_id, patient_id, amount, due_date, description, status, deleted_at, agenda_evento_id')
.select('id, patient_id, amount, due_date, description, status, deleted_at, agenda_evento_id')
.eq('id', recordId)
.eq('tenant_id', tenantId)
.is('deleted_at', null)
.maybeSingle();
@@ -101,7 +100,7 @@ Deno.serve(async (req: Request) => {
}
if (!record.patient_id) return json({ ok: false, error: 'record_has_no_patient' }, 400);
const { data: patient } = await supa
const { data: patient } = await tdb
.from('patients')
.select('id, nome_completo, email_principal, telefone, cpf')
.eq('id', record.patient_id)
@@ -113,10 +112,9 @@ Deno.serve(async (req: Request) => {
// 3. Garante customer no Asaas (chama interna asaas-create-customer-patient OU inline)
// TODO Fase B: chamar Edge Function asaas-create-customer-patient ou inline upsert.
// Por ora, busca cache local — se não existe, retorna erro.
let { data: customer } = await supa
let { data: customer } = await tdb
.from('asaas_customers')
.select('id, asaas_customer_id')
.eq('tenant_id', tenantId)
.eq('patient_id', patient.id)
.eq('environment', environment)
.is('deleted_at', null)