9b21642e15
- _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>
132 lines
4.4 KiB
TypeScript
132 lines
4.4 KiB
TypeScript
/*
|
|
|--------------------------------------------------------------------------
|
|
| Agência PSI — Edge Function: sync-email-templates
|
|
|--------------------------------------------------------------------------
|
|
| Sincroniza templates globais ativos para email_templates_tenant.
|
|
|
|
|
| POST body: { tenant_id: string, owner_id: string }
|
|
|
|
|
| Para cada template em email_templates_global (is_active = true):
|
|
| - Se não existe no tenant → INSERT com subject/body NULL (herda global)
|
|
| - Se existe mas synced_version < global.version → UPDATE synced_version
|
|
|
|
|
| Retorna: { synced: number, updated: number }
|
|
|--------------------------------------------------------------------------
|
|
*/
|
|
|
|
import { adminClient, tenantDbForId } from '../_shared/tenant.ts'
|
|
|
|
const corsHeaders = {
|
|
'Access-Control-Allow-Origin': '*',
|
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
}
|
|
|
|
Deno.serve(async (req: Request) => {
|
|
// CORS preflight
|
|
if (req.method === 'OPTIONS') {
|
|
return new Response('ok', { headers: corsHeaders })
|
|
}
|
|
|
|
if (req.method !== 'POST') {
|
|
return new Response(
|
|
JSON.stringify({ error: 'Método não permitido' }),
|
|
{ status: 405, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
|
)
|
|
}
|
|
|
|
try {
|
|
const { tenant_id, owner_id } = await req.json()
|
|
|
|
if (!tenant_id || !owner_id) {
|
|
return new Response(
|
|
JSON.stringify({ error: 'tenant_id e owner_id são obrigatórios' }),
|
|
{ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
|
)
|
|
}
|
|
|
|
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 (GLOBAL → admin)
|
|
const { data: globals, error: globalsErr } = await admin
|
|
.from('email_templates_global')
|
|
.select('key, version')
|
|
.eq('is_active', true)
|
|
|
|
if (globalsErr) throw globalsErr
|
|
if (!globals || globals.length === 0) {
|
|
return new Response(
|
|
JSON.stringify({ synced: 0, updated: 0, message: 'Nenhum template global ativo' }),
|
|
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
|
)
|
|
}
|
|
|
|
// 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('owner_id', owner_id)
|
|
|
|
if (tenantErr) throw tenantErr
|
|
|
|
const tenantMap = new Map(
|
|
(tenantTemplates || []).map(t => [t.template_key, t.synced_version])
|
|
)
|
|
|
|
let synced = 0
|
|
let updated = 0
|
|
|
|
for (const global of globals) {
|
|
const existingVersion = tenantMap.get(global.key)
|
|
|
|
if (existingVersion === undefined) {
|
|
// 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({
|
|
owner_id,
|
|
template_key: global.key,
|
|
subject: null,
|
|
body_html: null,
|
|
body_text: null,
|
|
enabled: true,
|
|
synced_version: global.version,
|
|
})
|
|
|
|
if (insertErr) {
|
|
console.error(`[sync] Erro ao inserir ${global.key}:`, insertErr.message)
|
|
continue
|
|
}
|
|
synced++
|
|
} else if (existingVersion < global.version) {
|
|
// Existe mas desatualizado → UPDATE apenas synced_version (tenant → tdb)
|
|
const { error: updateErr } = await tdb
|
|
.from('email_templates_tenant')
|
|
.update({ synced_version: global.version })
|
|
.eq('owner_id', owner_id)
|
|
.eq('template_key', global.key)
|
|
|
|
if (updateErr) {
|
|
console.error(`[sync] Erro ao atualizar ${global.key}:`, updateErr.message)
|
|
continue
|
|
}
|
|
updated++
|
|
}
|
|
// Se synced_version >= global.version → já está em dia, skip
|
|
}
|
|
|
|
return new Response(
|
|
JSON.stringify({ synced, updated }),
|
|
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
|
)
|
|
} catch (err) {
|
|
console.error('[sync-email-templates] Erro:', err)
|
|
return new Response(
|
|
JSON.stringify({ error: err.message || 'Erro interno' }),
|
|
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
|
)
|
|
}
|
|
})
|