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:
@@ -20,7 +20,8 @@
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
import { createClient, SupabaseClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
||||
import { type SupabaseClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
||||
import { adminClient, listTenantSchemas } from '../_shared/tenant.ts'
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
@@ -166,11 +167,10 @@ async function sendViaTwilio(
|
||||
}
|
||||
|
||||
// Verifica se paciente está opted-out
|
||||
async function isOptedOut(supa: SupabaseClient, tenantId: string, phone: string): Promise<boolean> {
|
||||
const { data } = await supa
|
||||
async function isOptedOut(tdb: SupabaseClient, phone: string): Promise<boolean> {
|
||||
const { data } = await tdb
|
||||
.from('conversation_optouts')
|
||||
.select('id')
|
||||
.eq('tenant_id', tenantId)
|
||||
.eq('phone', phone)
|
||||
.is('opted_back_in_at', null)
|
||||
.limit(1)
|
||||
@@ -185,9 +185,12 @@ type ProcessStats = {
|
||||
errors: number
|
||||
}
|
||||
|
||||
// Processa eventos em uma janela especifica
|
||||
// Processa eventos em uma janela especifica (já escopado a um tenant via tdb)
|
||||
async function processWindow(
|
||||
supa: SupabaseClient,
|
||||
tdb: SupabaseClient,
|
||||
admin: SupabaseClient,
|
||||
tenantId: string,
|
||||
tenantName: string,
|
||||
type: '24h' | '2h',
|
||||
minutesAhead: number,
|
||||
stats: ProcessStats
|
||||
@@ -196,11 +199,11 @@ async function processWindow(
|
||||
const start = new Date(Date.now() + (minutesAhead - windowMin) * 60 * 1000).toISOString()
|
||||
const end = new Date(Date.now() + (minutesAhead + windowMin) * 60 * 1000).toISOString()
|
||||
|
||||
// Busca eventos na janela com patient + tenant (nome da clinica via company_profiles/tenants)
|
||||
const { data: events, error } = await supa
|
||||
// Busca eventos na janela com patient (tenant tables via tdb; schema já filtra o tenant)
|
||||
const { data: events, error } = await tdb
|
||||
.from('agenda_eventos')
|
||||
.select(`
|
||||
id, tenant_id, inicio_em, modalidade, patient_id, status,
|
||||
id, inicio_em, modalidade, patient_id, status,
|
||||
patients:patient_id (id, nome_completo, telefone)
|
||||
`)
|
||||
.eq('status', 'agendado')
|
||||
@@ -217,23 +220,22 @@ async function processWindow(
|
||||
for (const ev of events || []) {
|
||||
try {
|
||||
const eventId = ev.id as string
|
||||
const tenantId = ev.tenant_id as string
|
||||
const pat = Array.isArray(ev.patients) ? ev.patients[0] : ev.patients
|
||||
if (!pat || !pat.telefone) {
|
||||
// Sem telefone — loga e pula
|
||||
await logSkip(supa, eventId, tenantId, type, 'no_phone')
|
||||
await logSkip(tdb, eventId, type, 'no_phone')
|
||||
stats.skipped.no_phone = (stats.skipped.no_phone || 0) + 1
|
||||
continue
|
||||
}
|
||||
const phone = normalizePhoneBR(pat.telefone)
|
||||
if (!/^\d{10,15}$/.test(phone)) {
|
||||
await logSkip(supa, eventId, tenantId, type, 'invalid_phone')
|
||||
await logSkip(tdb, eventId, type, 'invalid_phone')
|
||||
stats.skipped.invalid_phone = (stats.skipped.invalid_phone || 0) + 1
|
||||
continue
|
||||
}
|
||||
|
||||
// Ja enviado? (UNIQUE constraint previne dup mas checamos pra economizar)
|
||||
const { data: existing } = await supa
|
||||
const { data: existing } = await tdb
|
||||
.from('session_reminder_logs')
|
||||
.select('id')
|
||||
.eq('event_id', eventId)
|
||||
@@ -244,11 +246,10 @@ async function processWindow(
|
||||
continue
|
||||
}
|
||||
|
||||
// Settings do tenant
|
||||
const { data: settings } = await supa
|
||||
// Settings do tenant (tabela tenant; uma linha por schema)
|
||||
const { data: settings } = await tdb
|
||||
.from('session_reminder_settings')
|
||||
.select('*')
|
||||
.eq('tenant_id', tenantId)
|
||||
.maybeSingle()
|
||||
|
||||
if (!settings || !settings.enabled) {
|
||||
@@ -269,48 +270,40 @@ async function processWindow(
|
||||
const startHHMM = String(settings.quiet_hours_start || '22:00').slice(0, 5)
|
||||
const endHHMM = String(settings.quiet_hours_end || '08:00').slice(0, 5)
|
||||
if (isQuietHoursNow(startHHMM, endHHMM)) {
|
||||
await logSkip(supa, eventId, tenantId, type, 'quiet_hours')
|
||||
await logSkip(tdb, eventId, type, 'quiet_hours')
|
||||
stats.skipped.quiet_hours = (stats.skipped.quiet_hours || 0) + 1
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Opt-out
|
||||
if (settings.respect_opt_out && await isOptedOut(supa, tenantId, phone)) {
|
||||
await logSkip(supa, eventId, tenantId, type, 'opted_out')
|
||||
if (settings.respect_opt_out && await isOptedOut(tdb, phone)) {
|
||||
await logSkip(tdb, eventId, type, 'opted_out')
|
||||
stats.skipped.opted_out = (stats.skipped.opted_out || 0) + 1
|
||||
continue
|
||||
}
|
||||
|
||||
// Canal ativo
|
||||
const { data: channel } = await supa
|
||||
const { data: channel } = await tdb
|
||||
.from('notification_channels')
|
||||
.select('provider, credentials, twilio_phone_number, is_active')
|
||||
.eq('tenant_id', tenantId)
|
||||
.eq('channel', 'whatsapp')
|
||||
.is('deleted_at', null)
|
||||
.maybeSingle()
|
||||
if (!channel || !channel.is_active) {
|
||||
await logSkip(supa, eventId, tenantId, type, 'no_channel')
|
||||
await logSkip(tdb, eventId, type, 'no_channel')
|
||||
stats.skipped.no_channel = (stats.skipped.no_channel || 0) + 1
|
||||
continue
|
||||
}
|
||||
|
||||
// Nome da clinica (tenants.name)
|
||||
const { data: tenant } = await supa
|
||||
.from('tenants')
|
||||
.select('name')
|
||||
.eq('id', tenantId)
|
||||
.maybeSingle()
|
||||
|
||||
// Monta mensagem
|
||||
// Monta mensagem (nome da clínica vem do tenant global, resolvido no loop)
|
||||
const tpl = type === '24h' ? settings.template_24h : settings.template_2h
|
||||
const text = renderTemplate(tpl, {
|
||||
nome_paciente: pat.nome_completo || 'Paciente',
|
||||
data_sessao: fmtDateDayMonth(ev.inicio_em),
|
||||
hora_sessao: fmtTime(ev.inicio_em),
|
||||
modalidade: ev.modalidade === 'online' ? 'online' : 'presencial',
|
||||
nome_clinica: tenant?.name || ''
|
||||
nome_clinica: tenantName || ''
|
||||
})
|
||||
|
||||
// Envia (Evolution only por enquanto)
|
||||
@@ -319,23 +312,22 @@ async function processWindow(
|
||||
if (providerKind === 'evolution') {
|
||||
const creds = (channel.credentials ?? {}) as Record<string, string>
|
||||
if (!creds.api_url || !creds.api_key || !creds.instance_name) {
|
||||
await logSkip(supa, eventId, tenantId, type, 'creds_missing')
|
||||
await logSkip(tdb, eventId, type, 'creds_missing')
|
||||
stats.skipped.creds_missing = (stats.skipped.creds_missing || 0) + 1
|
||||
continue
|
||||
}
|
||||
const sendRes = await sendViaEvolution(creds.api_url, creds.api_key, creds.instance_name, phone, text)
|
||||
if (!sendRes.ok) {
|
||||
console.error('[reminders] send failed for event', eventId, sendRes.error)
|
||||
await supa.from('session_reminder_logs').insert({
|
||||
event_id: eventId, tenant_id: tenantId, reminder_type: type,
|
||||
await tdb.from('session_reminder_logs').insert({
|
||||
event_id: eventId, reminder_type: type,
|
||||
provider: 'evolution', skip_reason: `send_failed: ${sendRes.error}`, to_phone: phone
|
||||
})
|
||||
stats.errors++
|
||||
continue
|
||||
}
|
||||
// Registra outbound message + log
|
||||
const { data: msg } = await supa.from('conversation_messages').insert({
|
||||
tenant_id: tenantId,
|
||||
const { data: msg } = await tdb.from('conversation_messages').insert({
|
||||
patient_id: pat.id,
|
||||
channel: 'whatsapp',
|
||||
direction: 'outbound',
|
||||
@@ -349,8 +341,8 @@ async function processWindow(
|
||||
responded_at: new Date().toISOString()
|
||||
}).select('id').single()
|
||||
|
||||
await supa.from('session_reminder_logs').insert({
|
||||
event_id: eventId, tenant_id: tenantId, reminder_type: type,
|
||||
await tdb.from('session_reminder_logs').insert({
|
||||
event_id: eventId, reminder_type: type,
|
||||
provider: 'evolution', to_phone: phone,
|
||||
provider_message_id: sendRes.messageId ?? null,
|
||||
conversation_message_id: msg?.id ?? null
|
||||
@@ -358,10 +350,9 @@ async function processWindow(
|
||||
stats.sent++
|
||||
} else if (providerKind === 'twilio') {
|
||||
// Busca creds twilio (colunas dedicadas + credentials JSONB com auth_token)
|
||||
const { data: fullChannel } = await supa
|
||||
const { data: fullChannel } = await tdb
|
||||
.from('notification_channels')
|
||||
.select('twilio_subaccount_sid, twilio_phone_number, credentials')
|
||||
.eq('tenant_id', tenantId)
|
||||
.eq('channel', 'whatsapp')
|
||||
.is('deleted_at', null)
|
||||
.maybeSingle()
|
||||
@@ -371,13 +362,13 @@ async function processWindow(
|
||||
const twFrom = fullChannel?.twilio_phone_number as string
|
||||
|
||||
if (!subSid || !subToken || !twFrom) {
|
||||
await logSkip(supa, eventId, tenantId, type, 'twilio_creds_missing')
|
||||
await logSkip(tdb, eventId, type, 'twilio_creds_missing')
|
||||
stats.skipped.twilio_creds_missing = (stats.skipped.twilio_creds_missing || 0) + 1
|
||||
continue
|
||||
}
|
||||
|
||||
// Deduz 1 crédito ANTES (atômico via RPC)
|
||||
const { error: dedErr } = await supa.rpc('deduct_whatsapp_credits', {
|
||||
// Deduz 1 crédito ANTES (atômico via RPC; whatsapp_credit_* é GLOBAL → admin)
|
||||
const { error: dedErr } = await admin.rpc('deduct_whatsapp_credits', {
|
||||
p_tenant_id: tenantId,
|
||||
p_amount: 1,
|
||||
p_conversation_message_id: null,
|
||||
@@ -385,15 +376,15 @@ async function processWindow(
|
||||
})
|
||||
if (dedErr) {
|
||||
const reason = String(dedErr.message || '').includes('insufficient_credits') ? 'insufficient_credits' : 'deduct_error'
|
||||
await logSkip(supa, eventId, tenantId, type, reason)
|
||||
await logSkip(tdb, eventId, type, reason)
|
||||
stats.skipped[reason] = (stats.skipped[reason] || 0) + 1
|
||||
continue
|
||||
}
|
||||
|
||||
const sendRes = await sendViaTwilio(subSid, subToken, twFrom, phone, text)
|
||||
if (!sendRes.ok) {
|
||||
// Refund
|
||||
await supa.rpc('add_whatsapp_credits', {
|
||||
// Refund (GLOBAL → admin)
|
||||
await admin.rpc('add_whatsapp_credits', {
|
||||
p_tenant_id: tenantId,
|
||||
p_amount: 1,
|
||||
p_kind: 'refund',
|
||||
@@ -402,16 +393,15 @@ async function processWindow(
|
||||
p_note: `Refund lembrete falhou: ${sendRes.error?.slice(0, 200)}`
|
||||
})
|
||||
console.error('[reminders] twilio send failed:', sendRes.error)
|
||||
await supa.from('session_reminder_logs').insert({
|
||||
event_id: eventId, tenant_id: tenantId, reminder_type: type,
|
||||
await tdb.from('session_reminder_logs').insert({
|
||||
event_id: eventId, reminder_type: type,
|
||||
provider: 'twilio', skip_reason: `send_failed: ${sendRes.error}`, to_phone: phone
|
||||
})
|
||||
stats.errors++
|
||||
continue
|
||||
}
|
||||
|
||||
const { data: msg } = await supa.from('conversation_messages').insert({
|
||||
tenant_id: tenantId,
|
||||
const { data: msg } = await tdb.from('conversation_messages').insert({
|
||||
patient_id: pat.id,
|
||||
channel: 'whatsapp',
|
||||
direction: 'outbound',
|
||||
@@ -426,15 +416,15 @@ async function processWindow(
|
||||
delivery_status: sendRes.status === 'delivered' ? 'delivered' : 'sent'
|
||||
}).select('id').single()
|
||||
|
||||
await supa.from('session_reminder_logs').insert({
|
||||
event_id: eventId, tenant_id: tenantId, reminder_type: type,
|
||||
await tdb.from('session_reminder_logs').insert({
|
||||
event_id: eventId, reminder_type: type,
|
||||
provider: 'twilio', to_phone: phone,
|
||||
provider_message_id: sendRes.messageId ?? null,
|
||||
conversation_message_id: msg?.id ?? null
|
||||
})
|
||||
stats.sent++
|
||||
} else {
|
||||
await logSkip(supa, eventId, tenantId, type, 'unknown_provider')
|
||||
await logSkip(tdb, eventId, type, 'unknown_provider')
|
||||
stats.skipped.unknown_provider = (stats.skipped.unknown_provider || 0) + 1
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -445,10 +435,10 @@ async function processWindow(
|
||||
}
|
||||
|
||||
async function logSkip(
|
||||
supa: SupabaseClient, eventId: string, tenantId: string, type: '24h' | '2h', reason: string
|
||||
tdb: SupabaseClient, eventId: string, type: '24h' | '2h', reason: string
|
||||
) {
|
||||
await supa.from('session_reminder_logs').insert({
|
||||
event_id: eventId, tenant_id: tenantId, reminder_type: type,
|
||||
await tdb.from('session_reminder_logs').insert({
|
||||
event_id: eventId, reminder_type: type,
|
||||
provider: 'skipped', skip_reason: reason
|
||||
})
|
||||
}
|
||||
@@ -457,17 +447,27 @@ Deno.serve(async (req: Request) => {
|
||||
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })
|
||||
|
||||
try {
|
||||
const supabase = createClient(
|
||||
Deno.env.get('SUPABASE_URL')!,
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
|
||||
)
|
||||
const admin = adminClient()
|
||||
|
||||
const stats: ProcessStats = { considered: 0, sent: 0, skipped: {}, errors: 0 }
|
||||
|
||||
// 24h antes
|
||||
await processWindow(supabase, '24h', 24 * 60, stats)
|
||||
// 2h antes
|
||||
await processWindow(supabase, '2h', 2 * 60, stats)
|
||||
// Varre todos os tenants com schema provisionado
|
||||
for (const t of await listTenantSchemas(admin)) {
|
||||
const tdb = admin.schema(t.schema)
|
||||
|
||||
// Nome da clínica (tenants é GLOBAL → admin)
|
||||
const { data: tenant } = await admin
|
||||
.from('tenants')
|
||||
.select('name')
|
||||
.eq('id', t.tenantId)
|
||||
.maybeSingle()
|
||||
const tenantName = tenant?.name || ''
|
||||
|
||||
// 24h antes
|
||||
await processWindow(tdb, admin, t.tenantId, tenantName, '24h', 24 * 60, stats)
|
||||
// 2h antes
|
||||
await processWindow(tdb, admin, t.tenantId, tenantName, '2h', 2 * 60, stats)
|
||||
}
|
||||
|
||||
return json({ ok: true, stats })
|
||||
} catch (err) {
|
||||
|
||||
Reference in New Issue
Block a user