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:
@@ -9,19 +9,25 @@
|
||||
| - Antes de enviar, debita 1 crédito do tenant via RPC
|
||||
| - Sem crédito → marca como 'sem_credito'
|
||||
|
|
||||
| schema-per-tenant: notification_queue/templates/logs vivem no schema físico
|
||||
| de cada tenant (SEM coluna tenant_id). O cron VARRE todos os tenants; se vier
|
||||
| body.tenant_id, processa só aquele (modo single). addon_credits é GLOBAL
|
||||
| (admin) e a RPC debit_addon_credit continua em admin.rpc com p_tenant_id.
|
||||
|
|
||||
| Fluxo:
|
||||
| 1. Busca pendentes (channel='sms', status='pendente', scheduled_at <= now)
|
||||
| 2. Lock otimista (status → processando)
|
||||
| 3. Debita crédito SMS do tenant (addon_credits)
|
||||
| 4. Resolve template (tenant → global fallback)
|
||||
| 3. Debita crédito SMS do tenant (RPC, admin + p_tenant_id)
|
||||
| 4. Resolve template (templates do schema pertencem ao tenant)
|
||||
| 5. Renderiza variáveis {{var}}
|
||||
| 6. Envia via Twilio REST API (credenciais da plataforma)
|
||||
| 7. Atualiza queue + insere notification_logs
|
||||
| 7. Atualiza queue + insere notification_logs (tdb)
|
||||
| 8. Retry com backoff em caso de erro
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
||||
import type { SupabaseClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
||||
import { adminClient, listTenantSchemas, tenantDbForId, schemaForTenant } from '../_shared/tenant.ts'
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
@@ -89,22 +95,19 @@ function mockSend(_to: string, _body: string): { sid: string; status: string } {
|
||||
return { sid, status: 'sent' }
|
||||
}
|
||||
|
||||
// ── Main handler ───────────────────────────────────────────────
|
||||
// ── Processa a fila de UM tenant ───────────────────────────────
|
||||
|
||||
Deno.serve(async (req: Request) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response('ok', { headers: corsHeaders })
|
||||
}
|
||||
|
||||
const supabase = createClient(
|
||||
Deno.env.get('SUPABASE_URL')!,
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
|
||||
)
|
||||
type Result = { id: string; status: string; error?: string }
|
||||
|
||||
async function processTenantQueue(
|
||||
admin: SupabaseClient,
|
||||
tdb: SupabaseClient,
|
||||
tenantId: string
|
||||
): Promise<Result[]> {
|
||||
const now = new Date().toISOString()
|
||||
|
||||
// 1. Busca itens pendentes
|
||||
const { data: items, error: fetchErr } = await supabase
|
||||
// 1. Busca itens pendentes deste tenant
|
||||
const { data: items, error: fetchErr } = await tdb
|
||||
.from('notification_queue')
|
||||
.select('*')
|
||||
.eq('channel', 'sms')
|
||||
@@ -113,28 +116,17 @@ Deno.serve(async (req: Request) => {
|
||||
.order('scheduled_at', { ascending: true })
|
||||
.limit(20)
|
||||
|
||||
if (fetchErr) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: fetchErr.message }),
|
||||
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
if (fetchErr) throw new Error(fetchErr.message)
|
||||
if (!items?.length) return []
|
||||
|
||||
if (!items?.length) {
|
||||
return new Response(
|
||||
JSON.stringify({ message: 'Nenhum SMS na fila', processed: 0 }),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
|
||||
const results: Array<{ id: string; status: string; error?: string }> = []
|
||||
const results: Result[] = []
|
||||
|
||||
for (const item of items) {
|
||||
// Filtra por max_attempts
|
||||
if (item.attempts >= (item.max_attempts || 5)) continue
|
||||
|
||||
// 2. Lock otimista
|
||||
const { error: lockErr } = await supabase
|
||||
const { error: lockErr } = await tdb
|
||||
.from('notification_queue')
|
||||
.update({ status: 'processando', attempts: item.attempts + 1 })
|
||||
.eq('id', item.id)
|
||||
@@ -146,10 +138,10 @@ Deno.serve(async (req: Request) => {
|
||||
}
|
||||
|
||||
try {
|
||||
// 3. Debita crédito SMS do tenant
|
||||
const { data: debitResult, error: debitErr } = await supabase
|
||||
// 3. Debita crédito SMS do tenant (RPC global, p_tenant_id da iteração)
|
||||
const { data: debitResult, error: debitErr } = await admin
|
||||
.rpc('debit_addon_credit', {
|
||||
p_tenant_id: item.tenant_id,
|
||||
p_tenant_id: tenantId,
|
||||
p_addon_type: 'sms',
|
||||
p_queue_id: item.id,
|
||||
p_description: `SMS para ${item.recipient_address}`,
|
||||
@@ -161,13 +153,12 @@ Deno.serve(async (req: Request) => {
|
||||
|
||||
if (!debitResult?.success) {
|
||||
// Sem crédito — não envia, marca como sem_credito
|
||||
await supabase
|
||||
await tdb
|
||||
.from('notification_queue')
|
||||
.update({ status: 'sem_credito', last_error: debitResult?.reason || 'Sem créditos SMS' })
|
||||
.eq('id', item.id)
|
||||
|
||||
await supabase.from('notification_logs').insert({
|
||||
tenant_id: item.tenant_id,
|
||||
await tdb.from('notification_logs').insert({
|
||||
owner_id: item.owner_id,
|
||||
queue_id: item.id,
|
||||
agenda_evento_id: item.agenda_evento_id,
|
||||
@@ -185,26 +176,26 @@ Deno.serve(async (req: Request) => {
|
||||
continue
|
||||
}
|
||||
|
||||
// 4. Resolve template: tenant → global fallback
|
||||
// 4. Resolve template: templates do schema pertencem ao tenant.
|
||||
// Preferimos override do owner; senão default do schema.
|
||||
let template: { body_text: string } | null = null
|
||||
|
||||
const { data: tenantTpl } = await supabase
|
||||
const { data: ownerTpl } = await tdb
|
||||
.from('notification_templates')
|
||||
.select('body_text, is_active')
|
||||
.eq('tenant_id', item.tenant_id)
|
||||
.eq('owner_id', item.owner_id)
|
||||
.eq('key', item.template_key)
|
||||
.eq('channel', 'sms')
|
||||
.eq('is_active', true)
|
||||
.is('deleted_at', null)
|
||||
.maybeSingle()
|
||||
|
||||
if (tenantTpl) {
|
||||
template = tenantTpl
|
||||
if (ownerTpl) {
|
||||
template = ownerTpl
|
||||
} else {
|
||||
const { data: globalTpl } = await supabase
|
||||
const { data: defaultTpl } = await tdb
|
||||
.from('notification_templates')
|
||||
.select('body_text')
|
||||
.is('tenant_id', null)
|
||||
.eq('key', item.template_key)
|
||||
.eq('channel', 'sms')
|
||||
.eq('is_default', true)
|
||||
@@ -212,7 +203,7 @@ Deno.serve(async (req: Request) => {
|
||||
.is('deleted_at', null)
|
||||
.maybeSingle()
|
||||
|
||||
template = globalTpl
|
||||
template = defaultTpl
|
||||
}
|
||||
|
||||
if (!template) {
|
||||
@@ -223,11 +214,11 @@ Deno.serve(async (req: Request) => {
|
||||
const vars = item.resolved_vars || {}
|
||||
const message = renderTemplate(template.body_text, vars)
|
||||
|
||||
// 6. Busca from_number override do tenant (se tiver)
|
||||
const { data: creditRow } = await supabase
|
||||
// 6. Busca from_number override do tenant (addon_credits é GLOBAL → admin)
|
||||
const { data: creditRow } = await admin
|
||||
.from('addon_credits')
|
||||
.select('from_number_override')
|
||||
.eq('tenant_id', item.tenant_id)
|
||||
.eq('tenant_id', tenantId)
|
||||
.eq('addon_type', 'sms')
|
||||
.maybeSingle()
|
||||
|
||||
@@ -243,7 +234,7 @@ Deno.serve(async (req: Request) => {
|
||||
}
|
||||
|
||||
// 8. Sucesso
|
||||
await supabase
|
||||
await tdb
|
||||
.from('notification_queue')
|
||||
.update({
|
||||
status: 'enviado',
|
||||
@@ -252,8 +243,7 @@ Deno.serve(async (req: Request) => {
|
||||
})
|
||||
.eq('id', item.id)
|
||||
|
||||
await supabase.from('notification_logs').insert({
|
||||
tenant_id: item.tenant_id,
|
||||
await tdb.from('notification_logs').insert({
|
||||
owner_id: item.owner_id,
|
||||
queue_id: item.id,
|
||||
agenda_evento_id: item.agenda_evento_id,
|
||||
@@ -279,7 +269,7 @@ Deno.serve(async (req: Request) => {
|
||||
const isExhausted = attempts >= maxAttempts
|
||||
const retryMs = attempts * 2 * 60 * 1000
|
||||
|
||||
await supabase
|
||||
await tdb
|
||||
.from('notification_queue')
|
||||
.update({
|
||||
status: isExhausted ? 'falhou' : 'pendente',
|
||||
@@ -288,8 +278,7 @@ Deno.serve(async (req: Request) => {
|
||||
})
|
||||
.eq('id', item.id)
|
||||
|
||||
await supabase.from('notification_logs').insert({
|
||||
tenant_id: item.tenant_id,
|
||||
await tdb.from('notification_logs').insert({
|
||||
owner_id: item.owner_id,
|
||||
queue_id: item.id,
|
||||
agenda_evento_id: item.agenda_evento_id,
|
||||
@@ -307,12 +296,73 @@ Deno.serve(async (req: Request) => {
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
// ── Main handler ───────────────────────────────────────────────
|
||||
|
||||
Deno.serve(async (req: Request) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response('ok', { headers: corsHeaders })
|
||||
}
|
||||
|
||||
const admin = adminClient()
|
||||
|
||||
// Modo single-tenant se body.tenant_id; senão varre todos.
|
||||
let bodyTenantId: string | null = null
|
||||
try {
|
||||
const body = await req.json()
|
||||
bodyTenantId = body?.tenant_id ?? null
|
||||
} catch {
|
||||
// sem body / body inválido → modo varredura
|
||||
}
|
||||
|
||||
const results: Result[] = []
|
||||
const errors: Array<{ tenantId: string; error: string }> = []
|
||||
|
||||
try {
|
||||
if (bodyTenantId) {
|
||||
const schema = await schemaForTenant(admin, bodyTenantId)
|
||||
if (!schema) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: `schema indisponível para tenant ${bodyTenantId}` }),
|
||||
{ status: 404, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
const tdb = await tenantDbForId(admin, bodyTenantId)
|
||||
results.push(...await processTenantQueue(admin, tdb, bodyTenantId))
|
||||
} else {
|
||||
const tenants = await listTenantSchemas(admin)
|
||||
for (const t of tenants) {
|
||||
try {
|
||||
const tdb = admin.schema(t.schema)
|
||||
results.push(...await processTenantQueue(admin, tdb, t.tenantId))
|
||||
} catch (e) {
|
||||
console.error(`[process-sms-queue] tenant ${t.tenantId} falhou:`, e.message)
|
||||
errors.push({ tenantId: t.tenantId, error: e.message })
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: err.message }),
|
||||
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
|
||||
if (!results.length && !errors.length) {
|
||||
return new Response(
|
||||
JSON.stringify({ message: 'Nenhum SMS na fila', processed: 0 }),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
|
||||
const sent = results.filter(r => r.status === 'enviado').length
|
||||
const failed = results.filter(r => r.status === 'falhou').length
|
||||
const noCredit = results.filter(r => r.status === 'sem_credito').length
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ processed: results.length, sent, failed, no_credit: noCredit, details: results }),
|
||||
JSON.stringify({ processed: results.length, sent, failed, no_credit: noCredit, details: results, tenantErrors: errors }),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user