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>
111 lines
4.5 KiB
TypeScript
111 lines
4.5 KiB
TypeScript
/*
|
|
|--------------------------------------------------------------------------
|
|
| Agência PSI — Edge Function: deactivate-notification-channel
|
|
|--------------------------------------------------------------------------
|
|
| Desativa um canal de notificação (soft delete) usando service_role pra
|
|
| bypassar RLS. Usado pelo chooser de WhatsApp quando o tenant quer trocar
|
|
| de provedor mas o canal foi criado pelo SaaS admin (owner_id != tenant).
|
|
|
|
|
| Autoriza: apenas membros ativos do tenant dono do canal.
|
|
|--------------------------------------------------------------------------
|
|
*/
|
|
|
|
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
|
import { adminClient, listTenantSchemas } 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',
|
|
}
|
|
|
|
function json(body: unknown, status = 200) {
|
|
return new Response(JSON.stringify(body), {
|
|
status,
|
|
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
|
})
|
|
}
|
|
|
|
Deno.serve(async (req: Request) => {
|
|
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })
|
|
if (req.method !== 'POST') return json({ ok: false, error: 'method_not_allowed' }, 405)
|
|
|
|
try {
|
|
const body = await req.json().catch(() => null) as { channel_id?: string } | null
|
|
const channelId = body?.channel_id
|
|
if (!channelId) return json({ ok: false, error: 'channel_id ausente' }, 400)
|
|
|
|
// Auth: valida user via JWT
|
|
const authHeader = req.headers.get('Authorization')
|
|
if (!authHeader) return json({ ok: false, error: 'unauthorized' }, 401)
|
|
|
|
const supaAuth = createClient(
|
|
Deno.env.get('SUPABASE_URL')!,
|
|
Deno.env.get('SUPABASE_ANON_KEY')!,
|
|
{ global: { headers: { Authorization: authHeader } } }
|
|
)
|
|
const { data: authData, error: authErr } = await supaAuth.auth.getUser()
|
|
if (authErr || !authData?.user) return json({ ok: false, error: 'unauthorized' }, 401)
|
|
const userId = authData.user.id
|
|
|
|
// Service role pra bypass RLS
|
|
const supaSvc = adminClient()
|
|
|
|
// schema-per-tenant: notification_channels vive no schema do tenant (sem
|
|
// coluna tenant_id) e o caller só manda channel_id. Varremos os schemas
|
|
// provisionados pra localizar o canal e descobrir o tenant dono.
|
|
let tdb = null
|
|
let tenantId: string | null = null
|
|
for (const ref of await listTenantSchemas(supaSvc)) {
|
|
const candidate = supaSvc.schema(ref.schema)
|
|
const { data, error } = await candidate
|
|
.from('notification_channels')
|
|
.select('id')
|
|
.eq('id', channelId)
|
|
.is('deleted_at', null)
|
|
.maybeSingle()
|
|
if (error) {
|
|
console.warn('[deactivate] busca canal em', ref.schema, ':', error.message)
|
|
continue
|
|
}
|
|
if (data) { tdb = candidate; tenantId = ref.tenantId; break }
|
|
}
|
|
|
|
if (!tdb || !tenantId) return json({ ok: false, error: 'channel_not_found' }, 404)
|
|
|
|
// Autoriza: user deve ser saas_admin OU membro ativo do tenant dono do canal
|
|
const { data: isAdmin } = await supaSvc.rpc('is_saas_admin')
|
|
let authorized = !!isAdmin
|
|
if (!authorized) {
|
|
const { data: membership } = await supaSvc
|
|
.from('tenant_members')
|
|
.select('id')
|
|
.eq('tenant_id', tenantId)
|
|
.eq('user_id', userId)
|
|
.eq('status', 'active')
|
|
.maybeSingle()
|
|
authorized = !!membership
|
|
}
|
|
if (!authorized) return json({ ok: false, error: 'forbidden' }, 403)
|
|
|
|
// Desativa (soft-delete) — tabela tenant
|
|
const { error: updErr } = await tdb
|
|
.from('notification_channels')
|
|
.update({
|
|
is_active: false,
|
|
deleted_at: new Date().toISOString()
|
|
})
|
|
.eq('id', channelId)
|
|
|
|
if (updErr) {
|
|
console.error('[deactivate-notification-channel] update error:', updErr.message)
|
|
return json({ ok: false, error: updErr.message }, 500)
|
|
}
|
|
|
|
return json({ ok: true, channel_id: channelId })
|
|
} catch (err) {
|
|
console.error('[deactivate-notification-channel] fatal:', err)
|
|
return json({ ok: false, error: String(err) }, 500)
|
|
}
|
|
})
|