Files
agenciapsilmno/supabase/functions/send-session-status-notification/index.ts
T
Leonardo b8ea292ef1 Grupo 8: agenda ↔ WhatsApp completo (8.2 lembrar manual, 8.3 status→msg, 8.4 lead)
=== 8.2 Botão "Lembrar paciente" na agenda ===

Edge nova send-session-reminder-manual:
- Recebe {event_id}, autoriza (member ativo do tenant), resolve template
  lembrete_sessao (custom → default global), envia via Evolution, registra
  outbound em conversation_messages + log em session_reminder_logs com
  reminder_type='manual'.
- Reusa lógica do cron reminders (sanitização, fmt datas, render template)
  mas sem janela/dedup — terapeuta pode redisparar quantas vezes quiser
  (log usa UPSERT; UNIQUE (event_id, reminder_type) sobrescreve).

Migration 20260423000008 adiciona 'manual' ao CHECK constraint de
session_reminder_logs.reminder_type.

UI: botão verde pi-whatsapp no footer do AgendaEventDialog (só em edit
de sessão com paciente vinculado). Confirm dialog + toast + erros
amigáveis (no_phone, invalid_phone, no_active_channel, template_not_found,
forbidden, send_failed).

=== 8.3 Status sessão dispara mensagem ===

Migration 20260423000009 cria trigger AFTER UPDATE OF status em
agenda_eventos: quando status muda pra cancelado/remarcado/confirmado,
dispara edge send-session-status-notification via pg_net (não bloqueia
o UPDATE). Settings app.settings.supabase_url/service_role_key reusadas.

Edge nova send-session-status-notification:
- Body {event_id, old_status, new_status}
- STATUS_TEMPLATE_MAP: cancelado→cancelamento_sessao, remarcado→
  remarcacao_sessao, confirmado→confirmacao_sessao.
- Respeita opt-out (conversation_optouts), canal ativo, template
  existente (tenant-specific → global default). Skip silencioso em
  caso de falta de config.
- Insere outbound em conversation_messages (sem log unique — múltiplas
  mudanças de status geram múltiplas mensagens por design).

=== 8.4 Intake abandonado vira lead no CRM ===

Migration 20260423000010:
- Adiciona 'in_progress' e 'abandoned_lead' ao CHECK de
  patient_intake_requests.status. Colunas last_progress_at e
  lead_thread_key.
- RPC convert_abandoned_intake_to_lead(intake_id): cria mensagem
  placeholder inbound no CRM do tenant (thread_key anon:{phone}) +
  conversation_notes com resumo dos dados coletados + marca status.

Edge save-intake-progress:
- POST {token, nome_completo?, telefone?, email_principal?, ...}
- Whitelist de campos (ALLOWED_FIELDS) pra proteger contra POST
  malicioso tentar setar status/owner/etc.
- Busca por token, set status='in_progress' se era 'new', atualiza
  campos enviados + last_progress_at.

Edge convert-abandoned-intakes (cron):
- Body opcional {idle_minutes} (default 30).
- Varre patient_intake_requests status='in_progress' + last_progress_at
  mais antigo que cutoff. Filtra só os com nome_completo OU telefone
  (contato mínimo pra valer lead). Chama RPC pra cada um.

Hook no form público CadastroPacienteExterno:
- Watch em nome_completo, telefone, email_principal, onde_nos_conheceu
  dispara scheduleProgressSave() com debounce 1.5s.
- savePartialProgress só chama a edge se tem nome OU telefone.
- Silent fail — autosave não é crítico.

Cron do convert-abandoned-intakes NÃO ativado automaticamente (igual
heartbeat/SLA). Template comentado não está na migration — admin
descomenta SELECT cron.schedule manualmente quando quiser ligar.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 22:25:33 -03:00

222 lines
9.4 KiB
TypeScript

/*
|--------------------------------------------------------------------------
| Agência PSI — Edge: send-session-status-notification (8.3)
|--------------------------------------------------------------------------
| Disparada por trigger DB quando status de um agenda_evento muda.
| Envia WhatsApp pro paciente usando template apropriado do novo status.
|
| Body JSON:
| { event_id: "<uuid>", old_status: "agendado", new_status: "cancelado" }
|
| Mapa de template_key por new_status (configurável em notification_templates):
| - cancelado → cancelamento_sessao
| - remarcado → remarcacao_sessao
| - confirmado → confirmacao_sessao
| - realizado → pós-sessao (opcional; normalmente desligado)
| - em_agendamento → não envia (status intermediário)
|
| Respeita config conversation_bots.respect_optout e registros de opt-out.
| Se template não existe/está desativado pra aquele status, skipa sem erro.
|--------------------------------------------------------------------------
*/
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
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' }
})
}
function rewriteForContainer(apiUrl: string): string {
try {
const u = new URL(apiUrl)
if (u.hostname === 'localhost' || u.hostname === '127.0.0.1') {
u.hostname = 'host.docker.internal'
return u.toString().replace(/\/+$/, '')
}
return apiUrl.replace(/\/+$/, '')
} catch { return apiUrl }
}
function normalizePhoneBR(raw: string | null | undefined): string {
const digits = String(raw || '').replace(/\D/g, '')
if (digits.length === 10 || digits.length === 11) return '55' + digits
return digits
}
function fmtDate(iso: string): string {
try { return new Intl.DateTimeFormat('pt-BR', { timeZone: 'America/Sao_Paulo', day: '2-digit', month: 'long' }).format(new Date(iso)) } catch { return iso }
}
function fmtTime(iso: string): string {
try { return new Intl.DateTimeFormat('pt-BR', { timeZone: 'America/Sao_Paulo', hour: '2-digit', minute: '2-digit', hour12: false }).format(new Date(iso)) } catch { return '' }
}
function renderTemplate(tpl: string, vars: Record<string, string>): string {
return Object.entries(vars).reduce((acc, [k, v]) => acc.replaceAll(`{{${k}}}`, v ?? ''), tpl)
}
// Mapa de status → template key. Se der pra alguém customizar depois, basta
// criar template com esse key no banco; senão skip silencioso.
const STATUS_TEMPLATE_MAP: Record<string, string> = {
cancelado: 'cancelamento_sessao',
remarcado: 'remarcacao_sessao',
confirmado: 'confirmacao_sessao'
// realizado/em_agendamento não enviam por padrão
}
async function sendViaEvolution(apiUrl: string, apiKey: string, instance: string, phone: string, text: string) {
try {
const endpoint = `${rewriteForContainer(apiUrl)}/message/sendText/${encodeURIComponent(instance)}`
const resp = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json', apikey: apiKey },
body: JSON.stringify({ number: phone, text })
})
if (!resp.ok) {
const t = await resp.text()
return { ok: false, error: `HTTP ${resp.status}: ${t.slice(0, 200)}` }
}
const j = await resp.json().catch(() => ({} as Record<string, unknown>))
const msgId = (j as { key?: { id?: string } }).key?.id || null
return { ok: true, messageId: msgId }
} catch (err) {
return { ok: false, error: (err as Error).message || 'fetch_failed' }
}
}
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 payload = await req.json().catch(() => null) as { event_id?: string; old_status?: string; new_status?: string } | null
const eventId = payload?.event_id
const newStatus = String(payload?.new_status || '').toLowerCase()
if (!eventId || !newStatus) return json({ ok: false, error: 'invalid_payload' }, 400)
const templateKey = STATUS_TEMPLATE_MAP[newStatus]
if (!templateKey) return json({ ok: true, skipped: 'status_not_mapped', status: newStatus })
const supa = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
)
// Carrega evento + paciente
const { data: ev, error: evErr } = await supa
.from('agenda_eventos')
.select('id, tenant_id, inicio_em, modalidade, patient_id, status, patients:patient_id(id, nome_completo, telefone)')
.eq('id', eventId)
.maybeSingle()
if (evErr || !ev) return json({ ok: false, error: 'event_not_found' }, 404)
const pat = Array.isArray(ev.patients) ? ev.patients[0] : ev.patients
if (!pat?.telefone) return json({ ok: true, skipped: 'no_phone' })
const phone = normalizePhoneBR(pat.telefone)
if (!/^\d{10,15}$/.test(phone)) return json({ ok: true, skipped: 'invalid_phone' })
// Opt-out: respeita
const { data: optout } = await supa
.from('conversation_optouts')
.select('id')
.eq('tenant_id', ev.tenant_id)
.eq('contact_number', phone)
.is('opted_in_at', null)
.maybeSingle()
if (optout) return json({ ok: true, skipped: 'opt_out' })
// Canal WhatsApp ativo
const { data: channel } = await supa
.from('notification_channels')
.select('id, provider, credentials')
.eq('tenant_id', ev.tenant_id)
.eq('channel', 'whatsapp')
.eq('is_active', true)
.is('deleted_at', null)
.maybeSingle()
if (!channel) return json({ ok: true, skipped: 'no_active_channel' })
// Template (tenant-specific → global default)
const { data: tpl } = await supa
.from('notification_templates')
.select('body_text')
.eq('tenant_id', ev.tenant_id)
.eq('channel', 'whatsapp')
.eq('key', templateKey)
.is('deleted_at', null)
.eq('is_active', true)
.limit(1)
.maybeSingle()
let body_text = tpl?.body_text
if (!body_text) {
const { data: def } = await supa
.from('notification_templates')
.select('body_text')
.eq('channel', 'whatsapp')
.eq('key', templateKey)
.is('tenant_id', null)
.is('deleted_at', null)
.eq('is_active', true)
.limit(1)
.maybeSingle()
body_text = def?.body_text
}
if (!body_text) return json({ ok: true, skipped: 'template_not_found', template_key: templateKey })
const { data: tenant } = await supa.from('tenants').select('name').eq('id', ev.tenant_id).maybeSingle()
const text = renderTemplate(body_text, {
nome_paciente: pat.nome_completo || 'paciente',
data_sessao: fmtDate(ev.inicio_em),
hora_sessao: fmtTime(ev.inicio_em),
modalidade: ev.modalidade === 'online' ? 'online' : 'presencial',
nome_clinica: tenant?.name || '',
status: newStatus
})
const providerKind = channel.provider === 'evolution_api' ? 'evolution' : channel.provider
if (providerKind !== 'evolution') {
// Twilio fica pra depois (precisa de créditos + ack)
return json({ ok: true, skipped: 'provider_not_supported_yet', provider: channel.provider })
}
const creds = (channel.credentials ?? {}) as Record<string, string>
if (!creds.api_url || !creds.api_key || !creds.instance_name) {
return json({ ok: true, skipped: 'creds_missing' })
}
const sendRes = await sendViaEvolution(creds.api_url, creds.api_key, creds.instance_name, phone, text)
if (!sendRes.ok) return json({ ok: false, error: `send_failed: ${sendRes.error}` }, 500)
// Registra conversa (sem log unique — transições podem acontecer várias vezes)
await supa.from('conversation_messages').insert({
tenant_id: ev.tenant_id,
patient_id: pat.id,
channel: 'whatsapp',
direction: 'outbound',
from_number: null,
to_number: phone,
body: text,
provider: 'evolution',
provider_message_id: sendRes.messageId ?? null,
provider_raw: { status_change: true, event_id: eventId, old_status: payload?.old_status || null, new_status: newStatus },
kanban_status: 'awaiting_patient',
responded_at: new Date().toISOString()
})
return json({ ok: true, sent: true, template_key: templateKey, to: phone })
} catch (err) {
console.error('[send-session-status-notification] fatal:', err)
return json({ ok: false, error: (err as Error).message || 'unexpected' }, 500)
}
})