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>
This commit is contained in:
Leonardo
2026-04-23 22:25:33 -03:00
parent c2c42a1620
commit b8ea292ef1
9 changed files with 1005 additions and 0 deletions
@@ -0,0 +1,14 @@
-- ==========================================================================
-- Agencia PSI — Migracao: session_reminder_logs aceita tipo 'manual' (8.2)
-- ==========================================================================
-- Permite log de lembrete disparado manualmente pelo botao "Lembrar paciente"
-- na agenda. O UNIQUE (event_id, reminder_type) continua: disparar de novo
-- sobrescreve o log manual anterior do mesmo evento.
-- ==========================================================================
ALTER TABLE public.session_reminder_logs
DROP CONSTRAINT IF EXISTS session_reminder_logs_reminder_type_check;
ALTER TABLE public.session_reminder_logs
ADD CONSTRAINT session_reminder_logs_reminder_type_check
CHECK (reminder_type = ANY (ARRAY['24h'::text, '2h'::text, 'manual'::text]));
@@ -0,0 +1,84 @@
-- ==========================================================================
-- Agencia PSI — Migracao: Trigger agenda_eventos → notificacao WhatsApp (8.3)
-- ==========================================================================
-- Quando um agenda_evento muda de status (ex: agendado → cancelado), dispara
-- a edge send-session-status-notification que resolve template e envia
-- mensagem WhatsApp ao paciente.
--
-- Transicoes que disparam (controlado na propria edge via STATUS_TEMPLATE_MAP):
-- - cancelado → cancelamento_sessao
-- - remarcado → remarcacao_sessao
-- - confirmado → confirmacao_sessao
--
-- O trigger nao bloqueia o UPDATE (pg_net e assincrono). Se a edge falhar,
-- o evento ja foi salvo — so a notificacao sera perdida.
--
-- Pre-requisito: settings app.settings.supabase_url e app.settings.service_role_key
-- configuradas (mesmas usadas pelo cron do heartbeat e SLA).
-- ==========================================================================
CREATE OR REPLACE FUNCTION public.fn_notify_agenda_status_change()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_url TEXT;
v_key TEXT;
BEGIN
-- So dispara se status realmente mudou
IF NEW.status IS NOT DISTINCT FROM OLD.status THEN
RETURN NEW;
END IF;
-- So dispara pra status "interessantes". Outros sao silenciosamente ignorados
-- (a edge tambem tem essa logica, mas economizamos chamada HTTP aqui)
IF NEW.status NOT IN ('cancelado', 'remarcado', 'confirmado') THEN
RETURN NEW;
END IF;
-- Precisa de paciente vinculado (senao nao tem telefone)
IF NEW.patient_id IS NULL THEN
RETURN NEW;
END IF;
-- Busca settings
BEGIN
v_url := current_setting('app.settings.supabase_url', true);
v_key := current_setting('app.settings.service_role_key', true);
EXCEPTION WHEN OTHERS THEN
-- Settings nao configuradas — silencioso
RETURN NEW;
END;
IF v_url IS NULL OR v_key IS NULL THEN
RETURN NEW;
END IF;
-- Fire and forget (pg_net)
PERFORM net.http_post(
url := v_url || '/functions/v1/send-session-status-notification',
headers := jsonb_build_object(
'Authorization', 'Bearer ' || v_key,
'Content-Type', 'application/json'
),
body := jsonb_build_object(
'event_id', NEW.id,
'old_status', OLD.status,
'new_status', NEW.status
)
);
RETURN NEW;
END;
$$;
DROP TRIGGER IF EXISTS trg_agenda_status_notify ON public.agenda_eventos;
CREATE TRIGGER trg_agenda_status_notify
AFTER UPDATE OF status ON public.agenda_eventos
FOR EACH ROW
EXECUTE FUNCTION public.fn_notify_agenda_status_change();
COMMENT ON FUNCTION public.fn_notify_agenda_status_change() IS
'Dispara edge send-session-status-notification quando status de agenda_eventos muda. So pra status mapeados (cancelado/remarcado/confirmado). Nao bloqueia UPDATE.';
@@ -0,0 +1,159 @@
-- ==========================================================================
-- Agencia PSI — Migracao: Intake abandonado vira lead no CRM (8.4)
-- ==========================================================================
-- Quando paciente abre o link de cadastro externo e preenche dados parciais
-- (ex: nome + telefone) mas nao finaliza, rodamos um cron periodico que:
-- 1. Varre patient_intake_requests com status='in_progress' ha > N min
-- (default 30)
-- 2. Pra cada, cria uma mensagem outbound placeholder no CRM anunciando:
-- "Paciente X preencheu parcialmente o cadastro e abandonou" + dados
-- coletados (nome, telefone, motivo se tiver)
-- 3. Marca intake como status='abandoned_lead' pra nao reprocessar
--
-- Pre-requisito pro fluxo funcionar: o form de intake (CadastroPacienteExterno)
-- precisa chamar save-intake-progress em algum evento de progresso
-- (ex: ao preencher telefone). Sem isso, nenhum row fica 'in_progress'.
-- ==========================================================================
-- Expande CHECK de status pra incluir 'in_progress' e 'abandoned_lead'
ALTER TABLE public.patient_intake_requests
DROP CONSTRAINT IF EXISTS chk_intakes_status;
ALTER TABLE public.patient_intake_requests
ADD CONSTRAINT chk_intakes_status
CHECK (status = ANY (ARRAY[
'new'::text,
'in_progress'::text,
'converted'::text,
'rejected'::text,
'abandoned_lead'::text
]));
-- Timestamp da ultima atualizacao de progresso (autosave)
ALTER TABLE public.patient_intake_requests
ADD COLUMN IF NOT EXISTS last_progress_at TIMESTAMPTZ;
-- Referencia pra mensagem/thread criada como lead (evita duplicacao)
ALTER TABLE public.patient_intake_requests
ADD COLUMN IF NOT EXISTS lead_thread_key TEXT;
CREATE INDEX IF NOT EXISTS idx_intakes_progress_pending
ON public.patient_intake_requests (last_progress_at)
WHERE status = 'in_progress';
COMMENT ON COLUMN public.patient_intake_requests.last_progress_at IS
'Ultima vez que o form salvou dados parciais. Cron usa pra detectar abandonados.';
COMMENT ON COLUMN public.patient_intake_requests.lead_thread_key IS
'Thread key da conversa criada no CRM quando vira lead abandonado.';
-- ---------------------------------------------------------------------------
-- RPC: convert_abandoned_intake_to_lead
-- ---------------------------------------------------------------------------
-- Processa 1 intake abandonado: cria conversation_message (outbound placeholder)
-- + conversation_note + marca status. Retorna o thread_key gerado.
--
-- SECURITY DEFINER pra bypass RLS do conversation_messages/notes.
-- ---------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION public.convert_abandoned_intake_to_lead(p_intake_id UUID)
RETURNS UUID
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_intake RECORD;
v_tenant_id UUID;
v_thread_key TEXT;
v_phone TEXT;
v_note_body TEXT;
v_admin_id UUID;
v_msg_id BIGINT;
BEGIN
SELECT * INTO v_intake FROM public.patient_intake_requests WHERE id = p_intake_id;
IF NOT FOUND THEN RAISE EXCEPTION 'intake_not_found'; END IF;
IF v_intake.status = 'abandoned_lead' THEN RETURN v_intake.lead_thread_key::UUID; END IF;
-- Tenant_id vem via owner_id (tenant_members)
SELECT tenant_id INTO v_tenant_id
FROM public.tenant_members
WHERE user_id = v_intake.owner_id
ORDER BY CASE role WHEN 'tenant_admin' THEN 1 WHEN 'clinic_admin' THEN 2 ELSE 3 END
LIMIT 1;
IF v_tenant_id IS NULL THEN RAISE EXCEPTION 'tenant_not_resolved'; END IF;
-- Normaliza telefone pra thread_key
v_phone := regexp_replace(COALESCE(v_intake.telefone, ''), '\D', '', 'g');
IF length(v_phone) BETWEEN 10 AND 11 THEN v_phone := '55' || v_phone; END IF;
IF v_phone = '' THEN v_phone := 'unknown'; END IF;
v_thread_key := 'anon:' || v_phone;
-- Nota com dados coletados
v_note_body := format(
'📋 Lead abandonado (cadastro externo):%s%sNome: %s%sTelefone: %s%sE-mail: %s%sMotivo/Observacoes: %s%s%sIniciou em: %s · Ultima atualizacao: %s',
E'\n', E'\n',
COALESCE(v_intake.nome_completo, ''),
E'\n',
COALESCE(v_intake.telefone, ''),
E'\n',
COALESCE(v_intake.email_principal, ''),
E'\n',
COALESCE(v_intake.onde_nos_conheceu, ''),
E'\n', E'\n',
to_char(v_intake.created_at AT TIME ZONE 'America/Sao_Paulo', 'DD/MM HH24:MI'),
to_char(COALESCE(v_intake.last_progress_at, v_intake.updated_at) AT TIME ZONE 'America/Sao_Paulo', 'DD/MM HH24:MI')
);
-- Pega 1 admin do tenant pra preencher created_by da nota
SELECT user_id INTO v_admin_id
FROM public.tenant_members
WHERE tenant_id = v_tenant_id
AND role IN ('tenant_admin', 'clinic_admin')
AND status = 'active'
LIMIT 1;
IF v_admin_id IS NULL THEN
v_admin_id := v_intake.owner_id;
END IF;
-- Cria mensagem placeholder (outbound sistema — entra no thread do CRM)
INSERT INTO public.conversation_messages
(tenant_id, channel, direction, from_number, to_number, body, provider,
provider_raw, kanban_status)
VALUES (
v_tenant_id, 'whatsapp', 'inbound',
CASE WHEN v_phone = 'unknown' THEN NULL ELSE v_phone END,
NULL,
format('🧾 Cadastro externo iniciado e não finalizado. %s entrou em contato via link público mas abandonou o formulário — ver nota interna.',
COALESCE(v_intake.nome_completo, 'Visitante')),
'system',
jsonb_build_object('lead_from_abandoned_intake', true, 'intake_id', v_intake.id),
'awaiting_us'
) RETURNING id INTO v_msg_id;
-- Cria nota interna
INSERT INTO public.conversation_notes
(tenant_id, thread_key, contact_number, body, created_by)
VALUES (
v_tenant_id, v_thread_key,
CASE WHEN v_phone = 'unknown' THEN NULL ELSE v_phone END,
v_note_body, v_admin_id
);
-- Atualiza intake
UPDATE public.patient_intake_requests
SET status = 'abandoned_lead',
lead_thread_key = v_thread_key,
updated_at = now()
WHERE id = p_intake_id;
RETURN p_intake_id;
END;
$$;
REVOKE ALL ON FUNCTION public.convert_abandoned_intake_to_lead(UUID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.convert_abandoned_intake_to_lead(UUID) TO service_role;
COMMENT ON FUNCTION public.convert_abandoned_intake_to_lead(UUID) IS
'Transforma 1 intake abandonado em lead no CRM: cria mensagem placeholder + nota com dados + marca status.';
@@ -1512,6 +1512,43 @@ function onEncerrarSerie() {
}); });
} }
// ───── Lembrete manual WhatsApp (8.2) ─────
const sendingReminder = ref(false);
async function onSendManualReminder() {
if (!form.value?.id) return;
confirm.require({
header: 'Enviar lembrete WhatsApp?',
message: `Vou mandar o template "lembrete_sessao" pra ${form.value.paciente_nome || 'o paciente'} agora. Pode disparar?`,
icon: 'pi pi-whatsapp',
acceptLabel: 'Enviar',
rejectLabel: 'Cancelar',
accept: async () => {
sendingReminder.value = true;
try {
const { data, error } = await supabase.functions.invoke('send-session-reminder-manual', {
body: { event_id: form.value.id }
});
if (error || !data?.ok) {
const err = data?.error || error?.message || 'unknown_error';
let friendly = err;
if (err === 'no_phone') friendly = 'Paciente sem telefone cadastrado.';
else if (err === 'invalid_phone') friendly = 'Telefone do paciente inválido.';
else if (err === 'no_active_channel') friendly = 'Nenhum canal WhatsApp ativo. Configure em Configurações → WhatsApp.';
else if (err === 'template_not_found') friendly = 'Template "lembrete_sessao" não encontrado. Configure em Configurações → WhatsApp.';
else if (err === 'forbidden') friendly = 'Você não tem permissão pra enviar por este canal.';
else if (String(err).startsWith('send_failed')) friendly = 'Não conseguimos enviar. Verifique a conexão do WhatsApp.';
throw new Error(friendly);
}
toast.add({ severity: 'success', summary: 'Lembrete enviado', detail: data.to ? `Para ${data.to}` : undefined, life: 3500 });
} catch (e) {
toast.add({ severity: 'error', summary: 'Erro ao enviar lembrete', detail: e.message, life: 5000 });
} finally {
sendingReminder.value = false;
}
}
});
}
function onDelete() { function onDelete() {
if (!form.value.id) return; if (!form.value.id) return;
@@ -2439,6 +2476,19 @@ function statusExtraClass(v) {
<Button v-if="isEdit && hasSerie" label="Encerrar série" icon="pi pi-trash" severity="danger" outlined size="small" class="rounded-full text-xs h-8" @click="onEncerrarSerie" /> <Button v-if="isEdit && hasSerie" label="Encerrar série" icon="pi pi-trash" severity="danger" outlined size="small" class="rounded-full text-xs h-8" @click="onEncerrarSerie" />
<Button v-if="isEdit && !hasSerie" icon="pi pi-trash" severity="danger" outlined size="small" class="rounded-full h-9 w-9" v-tooltip.bottom="'Remover'" @click="onDelete" /> <Button v-if="isEdit && !hasSerie" icon="pi pi-trash" severity="danger" outlined size="small" class="rounded-full h-9 w-9" v-tooltip.bottom="'Remover'" @click="onDelete" />
<!-- Lembrar paciente (WhatsApp on-demand) -->
<Button
v-if="isEdit && isSessionEvent && form.paciente_id"
icon="pi pi-whatsapp"
severity="success"
outlined
size="small"
class="rounded-full h-9 w-9"
v-tooltip.bottom="'Enviar lembrete WhatsApp agora'"
:loading="sendingReminder"
@click="onSendManualReminder"
/>
<!-- Google Calendar link --> <!-- Google Calendar link -->
<a <a
v-if="isEdit && googleCalendarUrl" v-if="isEdit && googleCalendarUrl"
@@ -177,6 +177,41 @@ async function fetchInviteInfo() {
} }
} }
// Autosave de progresso (8.4) — backend marca status='in_progress' e, se
// paciente abandonar, job cron cria lead no CRM.
// Debounce pra não spammar: salva 1.5s após parar de digitar em campos chave.
let _progressTimer = null;
const progressDebounceMs = 1500;
function scheduleProgressSave() {
if (!tokenOk.value || sucesso.value) return;
if (_progressTimer) clearTimeout(_progressTimer);
_progressTimer = setTimeout(savePartialProgress, progressDebounceMs);
}
async function savePartialProgress() {
if (!tokenOk.value || sucesso.value) return;
const nome = String(form.nome_completo || '').trim();
const tel = digitsOnly(form.telefone || '');
// Só salva se já tem mínimo pra contato (nome OU telefone)
if (!nome && !tel) return;
try {
await supabase.functions.invoke('save-intake-progress', {
body: {
token: token.value,
nome_completo: nome || undefined,
telefone: tel || undefined,
email_principal: String(form.email_principal || '').trim() || undefined,
onde_nos_conheceu: String(form.onde_nos_conheceu || '').trim() || undefined
}
});
} catch { /* silencioso — autosave não é crítico */ }
}
watch(
() => [form.nome_completo, form.telefone, form.email_principal, form.onde_nos_conheceu],
scheduleProgressSave
);
// ---------------------------------------------------------------- // ----------------------------------------------------------------
// Helpers // Helpers
// ---------------------------------------------------------------- // ----------------------------------------------------------------
@@ -0,0 +1,91 @@
/*
|--------------------------------------------------------------------------
| Agência PSI — Edge: convert-abandoned-intakes (8.4)
|--------------------------------------------------------------------------
| Cron que varre patient_intake_requests com status='in_progress' e
| last_progress_at ha mais de IDLE_MINUTES (default 30). Chama a RPC
| convert_abandoned_intake_to_lead pra cada um — RPC cria mensagem
| placeholder + nota interna + marca status='abandoned_lead'.
|
| Body opcional: { idle_minutes?: number } (default 30)
|
| Retorna: { checked, converted, errors }
|--------------------------------------------------------------------------
*/
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, GET, OPTIONS',
}
function json(body: unknown, status = 200) {
return new Response(JSON.stringify(body), {
status,
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
})
}
const DEFAULT_IDLE_MINUTES = 30
Deno.serve(async (req: Request) => {
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })
try {
const body = await req.json().catch(() => ({})) as { idle_minutes?: number }
const idleMinutes = Math.max(5, Math.min(1440, Number(body.idle_minutes) || DEFAULT_IDLE_MINUTES))
const supa = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
)
const cutoff = new Date(Date.now() - idleMinutes * 60 * 1000).toISOString()
// Busca candidatos: in_progress, last_progress_at antigo, tem minimo nome OU telefone
const { data: candidates, error: fetchErr } = await supa
.from('patient_intake_requests')
.select('id, nome_completo, telefone, email_principal')
.eq('status', 'in_progress')
.lt('last_progress_at', cutoff)
if (fetchErr) return json({ error: fetchErr.message }, 500)
const eligible = (candidates || []).filter((c) => c.nome_completo || c.telefone)
if (eligible.length === 0) {
return json({ checked: candidates?.length || 0, converted: 0, errors: 0 })
}
let converted = 0
let errors = 0
const results: Array<{ intake_id: string; ok: boolean; error?: string }> = []
for (const row of eligible) {
const { error: rpcErr } = await supa.rpc('convert_abandoned_intake_to_lead', {
p_intake_id: row.id
})
if (rpcErr) {
errors++
results.push({ intake_id: row.id, ok: false, error: rpcErr.message })
} else {
converted++
results.push({ intake_id: row.id, ok: true })
}
}
return json({
checked: candidates?.length || 0,
eligible: eligible.length,
converted,
errors,
idle_minutes: idleMinutes,
results
})
} catch (err) {
console.error('[convert-abandoned-intakes] fatal:', err)
return json({ error: (err as Error).message || 'unexpected' }, 500)
}
})
@@ -0,0 +1,107 @@
/*
|--------------------------------------------------------------------------
| Agência PSI — Edge: save-intake-progress (8.4)
|--------------------------------------------------------------------------
| Autosave de campos parciais do form de cadastro externo. Chamada pelo
| CadastroPacienteExterno ao preencher campos chave (nome, telefone, etc)
| pra que a gente consiga detectar abandonos e converter em lead no CRM.
|
| Body:
| {
| token: "<invite_token>", // obrigatório
| nome_completo?: string,
| telefone?: string,
| email_principal?: string,
| onde_nos_conheceu?: string,
| ... qualquer campo do form
| }
|
| Lógica:
| - Busca intake por token (valida que ainda não foi convertido/rejeitado)
| - Se status='new', vira 'in_progress'
| - Atualiza campos enviados
| - Atualiza last_progress_at
|--------------------------------------------------------------------------
*/
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' }
})
}
// Whitelist de campos que o form pode autosavar. Protege contra POST malicioso
// tentando setar status/converted_patient_id/owner_id etc.
const ALLOWED_FIELDS = new Set([
'nome_completo', 'telefone', 'email_principal', 'cpf', 'rg', 'cep',
'pais', 'cidade', 'estado', 'endereco', 'numero', 'bairro', 'complemento',
'data_nascimento', 'naturalidade', 'genero', 'estado_civil', 'onde_nos_conheceu'
])
function sanitizeString(s: unknown, maxLen = 500): string | null {
if (s === null || s === undefined) return null
const v = String(s).trim()
if (!v) return null
return v.slice(0, maxLen)
}
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 Record<string, unknown> | null
const token = sanitizeString(payload?.token, 128)
if (!token) return json({ ok: false, error: 'token_required' }, 400)
const supa = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
)
// Busca intake pelo token
const { data: intake } = await supa
.from('patient_intake_requests')
.select('id, status')
.eq('token', token)
.maybeSingle()
if (!intake) return json({ ok: false, error: 'token_not_found' }, 404)
if (intake.status === 'converted' || intake.status === 'rejected') {
return json({ ok: false, error: 'intake_already_closed', status: intake.status }, 409)
}
// Monta patch com campos sanitizados
const patch: Record<string, unknown> = {
last_progress_at: new Date().toISOString(),
status: intake.status === 'new' ? 'in_progress' : intake.status
}
for (const key of Object.keys(payload || {})) {
if (!ALLOWED_FIELDS.has(key)) continue
const clean = sanitizeString((payload as Record<string, unknown>)[key])
if (clean !== null) patch[key] = clean
}
const { error: updErr } = await supa
.from('patient_intake_requests')
.update(patch)
.eq('id', intake.id)
if (updErr) return json({ ok: false, error: updErr.message }, 500)
return json({ ok: true, saved: Object.keys(patch).length - 2 })
} catch (err) {
console.error('[save-intake-progress] fatal:', err)
return json({ ok: false, error: (err as Error).message || 'unexpected' }, 500)
}
})
@@ -0,0 +1,244 @@
/*
|--------------------------------------------------------------------------
| 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)
}
})
@@ -0,0 +1,221 @@
/*
|--------------------------------------------------------------------------
| 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)
}
})