Files
agenciapsilmno/supabase/functions/send-session-reminder-manual/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

245 lines
10 KiB
TypeScript

/*
|--------------------------------------------------------------------------
| Agência PSI — Edge: send-session-reminder-manual (8.2)
|--------------------------------------------------------------------------
| Dispara lembrete on-demand pra um evento específico, a partir do botão
| "Lembrar paciente" na agenda. Reusa template lembrete_sessao.
|
| Body: { event_id: "<uuid>" }
|
| Diferente do cron send-session-reminders:
| - Sem janela temporal (aceita evento em qualquer horário futuro)
| - Sem dedup (terapeuta pode disparar quantas vezes quiser — log entra
| como reminder_type='manual')
| - Permite disparar evento mesmo com status não 'agendado' (útil pra
| confirmar cancelamentos etc)
|--------------------------------------------------------------------------
*/
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 fmtDateDayMonth(iso: string): string {
try {
const d = new Date(iso)
return new Intl.DateTimeFormat('pt-BR', { timeZone: 'America/Sao_Paulo', day: '2-digit', month: 'long' }).format(d)
} catch { return iso }
}
function fmtTime(iso: string): string {
try {
const d = new Date(iso)
return new Intl.DateTimeFormat('pt-BR', { timeZone: 'America/Sao_Paulo', hour: '2-digit', minute: '2-digit', hour12: false }).format(d)
} catch { return '' }
}
function renderTemplate(tpl: string, vars: Record<string, string>): string {
return Object.entries(vars).reduce(
(acc, [k, v]) => acc.replaceAll(`{{${k}}}`, v ?? ''),
tpl
)
}
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 body = await req.json().catch(() => null) as { event_id?: string } | null
const eventId = body?.event_id
if (!eventId) return json({ ok: false, error: 'event_id_required' }, 400)
// Auth: precisa de user (qualquer membro do tenant do evento)
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
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)
// Autoriza: user deve ser membro ativo do tenant do evento
const { data: mem } = await supa
.from('tenant_members')
.select('id')
.eq('tenant_id', ev.tenant_id)
.eq('user_id', userId)
.eq('status', 'active')
.maybeSingle()
if (!mem) return json({ ok: false, error: 'forbidden' }, 403)
const pat = Array.isArray(ev.patients) ? ev.patients[0] : ev.patients
if (!pat || !pat.telefone) return json({ ok: false, error: 'no_phone' }, 400)
const phone = normalizePhoneBR(pat.telefone)
if (!/^\d{10,15}$/.test(phone)) return json({ ok: false, error: 'invalid_phone' }, 400)
// Canal WhatsApp ativo do tenant
const { data: channel } = await supa
.from('notification_channels')
.select('id, provider, credentials, is_active')
.eq('tenant_id', ev.tenant_id)
.eq('channel', 'whatsapp')
.eq('is_active', true)
.is('deleted_at', null)
.maybeSingle()
if (!channel) return json({ ok: false, error: 'no_active_channel' }, 400)
// Tenant name
const { data: tenant } = await supa.from('tenants').select('name').eq('id', ev.tenant_id).maybeSingle()
// Template lembrete_sessao — tenta custom do tenant, fallback pro default
const { data: tpl } = await supa
.from('notification_templates')
.select('body_text')
.eq('tenant_id', ev.tenant_id)
.eq('channel', 'whatsapp')
.eq('key', 'lembrete_sessao')
.is('deleted_at', null)
.eq('is_active', true)
.order('is_custom', { ascending: false })
.limit(1)
.maybeSingle()
let body_text = tpl?.body_text
if (!body_text) {
// Fallback: template default global
const { data: def } = await supa
.from('notification_templates')
.select('body_text')
.eq('channel', 'whatsapp')
.eq('key', 'lembrete_sessao')
.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: false, error: 'template_not_found' }, 400)
const text = renderTemplate(body_text, {
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 || ''
})
const providerKind = channel.provider === 'evolution_api' ? 'evolution' : channel.provider
if (providerKind === 'evolution') {
const creds = (channel.credentials ?? {}) as Record<string, string>
if (!creds.api_url || !creds.api_key || !creds.instance_name) {
return json({ ok: false, error: 'creds_missing' }, 400)
}
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 + log
const { data: msg } = 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: { reminder_type: 'manual', event_id: eventId, triggered_by: userId },
kanban_status: 'awaiting_patient',
responded_at: new Date().toISOString()
}).select('id').single()
// Upsert: permitir re-disparo manual. UNIQUE (event_id, reminder_type) — sobrescreve anterior.
await supa.from('session_reminder_logs').upsert({
event_id: eventId,
tenant_id: ev.tenant_id,
reminder_type: 'manual',
provider: 'evolution',
to_phone: phone,
provider_message_id: sendRes.messageId ?? null,
conversation_message_id: msg?.id ?? null,
sent_at: new Date().toISOString()
}, { onConflict: 'event_id,reminder_type' })
return json({ ok: true, sent: true, provider: 'evolution', to: phone, body_preview: text.slice(0, 100) })
}
// Twilio: implementação futura (escopo desta iteração é Evolution)
return json({ ok: false, error: `provider_not_supported_manual: ${channel.provider}` }, 400)
} catch (err) {
console.error('[send-session-reminder-manual] fatal:', err)
return json({ ok: false, error: (err as Error).message || 'unexpected' }, 500)
}
})