diff --git a/database-novo/migrations/20260423000008_session_reminder_manual.sql b/database-novo/migrations/20260423000008_session_reminder_manual.sql
new file mode 100644
index 0000000..3d1f55a
--- /dev/null
+++ b/database-novo/migrations/20260423000008_session_reminder_manual.sql
@@ -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]));
diff --git a/database-novo/migrations/20260423000009_session_status_trigger.sql b/database-novo/migrations/20260423000009_session_status_trigger.sql
new file mode 100644
index 0000000..a0afb3f
--- /dev/null
+++ b/database-novo/migrations/20260423000009_session_status_trigger.sql
@@ -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.';
diff --git a/database-novo/migrations/20260423000010_intake_abandoned_lead.sql b/database-novo/migrations/20260423000010_intake_abandoned_lead.sql
new file mode 100644
index 0000000..a81847d
--- /dev/null
+++ b/database-novo/migrations/20260423000010_intake_abandoned_lead.sql
@@ -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.';
diff --git a/src/features/agenda/components/AgendaEventDialog.vue b/src/features/agenda/components/AgendaEventDialog.vue
index 192dd82..f8854ea 100644
--- a/src/features/agenda/components/AgendaEventDialog.vue
+++ b/src/features/agenda/components/AgendaEventDialog.vue
@@ -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() {
if (!form.value.id) return;
@@ -2439,6 +2476,19 @@ function statusExtraClass(v) {
+
+
+
[form.nome_completo, form.telefone, form.email_principal, form.onde_nos_conheceu],
+ scheduleProgressSave
+);
+
// ----------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------
diff --git a/supabase/functions/convert-abandoned-intakes/index.ts b/supabase/functions/convert-abandoned-intakes/index.ts
new file mode 100644
index 0000000..0e828e3
--- /dev/null
+++ b/supabase/functions/convert-abandoned-intakes/index.ts
@@ -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)
+ }
+})
diff --git a/supabase/functions/save-intake-progress/index.ts b/supabase/functions/save-intake-progress/index.ts
new file mode 100644
index 0000000..9b4a81d
--- /dev/null
+++ b/supabase/functions/save-intake-progress/index.ts
@@ -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: "", // 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 | 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 = {
+ 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)[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)
+ }
+})
diff --git a/supabase/functions/send-session-reminder-manual/index.ts b/supabase/functions/send-session-reminder-manual/index.ts
new file mode 100644
index 0000000..90d8931
--- /dev/null
+++ b/supabase/functions/send-session-reminder-manual/index.ts
@@ -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: "" }
+|
+| 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 {
+ 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))
+ 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
+ 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)
+ }
+})
diff --git a/supabase/functions/send-session-status-notification/index.ts b/supabase/functions/send-session-status-notification/index.ts
new file mode 100644
index 0000000..4f1768f
--- /dev/null
+++ b/supabase/functions/send-session-status-notification/index.ts
@@ -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: "", 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 {
+ 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 = {
+ 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))
+ 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
+ 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)
+ }
+})