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:
@@ -19,6 +19,7 @@
|
||||
*/
|
||||
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
||||
import { adminClient, tenantDbForId } from '../_shared/tenant.ts'
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
@@ -143,10 +144,17 @@ Deno.serve(async (req: Request) => {
|
||||
const { data: authData, error: authErr } = await supaAuthed.auth.getUser()
|
||||
if (authErr || !authData?.user) return json({ ok: false, error: 'auth' }, 401)
|
||||
|
||||
const supaSvc = createClient(
|
||||
Deno.env.get('SUPABASE_URL')!,
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
|
||||
)
|
||||
const supaSvc = adminClient()
|
||||
|
||||
// Client ligado ao schema do tenant (tabelas tenant: notification_channels,
|
||||
// conversation_messages). Lança se o tenant não existir/sem schema.
|
||||
let tdb
|
||||
try {
|
||||
tdb = await tenantDbForId(supaSvc, tenant_id)
|
||||
} catch (e) {
|
||||
console.error('[send-whatsapp-message] schema indisponível:', (e as Error).message)
|
||||
return json({ ok: false, error: 'tenant_invalido' }, 400)
|
||||
}
|
||||
|
||||
const userId = authData.user.id
|
||||
// Valida membership
|
||||
@@ -162,11 +170,10 @@ Deno.serve(async (req: Request) => {
|
||||
if (!membership) return json({ ok: false, error: 'forbidden' }, 403)
|
||||
}
|
||||
|
||||
// Busca canal (Evolution ou Twilio)
|
||||
const { data: channel, error: chErr } = await supaSvc
|
||||
// Busca canal (Evolution ou Twilio) — tabela tenant
|
||||
const { data: channel, error: chErr } = await tdb
|
||||
.from('notification_channels')
|
||||
.select('credentials, provider, twilio_subaccount_sid, twilio_phone_number, is_active')
|
||||
.eq('tenant_id', tenant_id)
|
||||
.eq('channel', 'whatsapp')
|
||||
.is('deleted_at', null)
|
||||
.maybeSingle()
|
||||
@@ -229,8 +236,7 @@ Deno.serve(async (req: Request) => {
|
||||
}
|
||||
|
||||
// Registra mensagem + vincula a dedução (se possível — já foi feita sem msg_id)
|
||||
const { data: inserted, error: insErr } = await supaSvc.from('conversation_messages').insert({
|
||||
tenant_id,
|
||||
const { data: inserted, error: insErr } = await tdb.from('conversation_messages').insert({
|
||||
patient_id: resolvedPatientId,
|
||||
channel: 'whatsapp',
|
||||
direction: 'outbound',
|
||||
@@ -294,8 +300,7 @@ Deno.serve(async (req: Request) => {
|
||||
|
||||
const providerMessageId = (evoJson as { key?: { id?: string } } | null)?.key?.id ?? null
|
||||
|
||||
const { data: inserted, error: insErr } = await supaSvc.from('conversation_messages').insert({
|
||||
tenant_id,
|
||||
const { data: inserted, error: insErr } = await tdb.from('conversation_messages').insert({
|
||||
patient_id: resolvedPatientId,
|
||||
channel: 'whatsapp',
|
||||
direction: 'outbound',
|
||||
|
||||
Reference in New Issue
Block a user