CRM WhatsApp Grupo 3 completo + Marco A/B (Asaas) + admin SaaS + refactors polimórficos
Sessão 11+: fechamento do CRM de WhatsApp com dois providers (Evolution/Twilio),
sistema de créditos com Asaas/PIX, polimorfismo de telefones/emails, e integração
admin SaaS no /saas/addons existente.
═══════════════════════════════════════════════════════════════════════════
GRUPO 3 — WORKFLOW / CRM (completo)
═══════════════════════════════════════════════════════════════════════════
3.1 Tags · migration conversation_tags + seed de 5 system tags · composable
useConversationTags.js · popover + pills no drawer e nos cards do Kanban.
3.2 Atribuição de conversa a terapeuta · migration 20260421000012 com PK
(tenant_id, thread_key), UPSERT, RLS que valida assignee como membro ativo
do mesmo tenant · view conversation_threads expandida com assigned_to +
assigned_at · composable useConversationAssignment.js · drawer com Select
filtrável + botão "Assumir" · inbox com filtro aside (Todas/Minhas/Não
atribuídas) e chip do responsável em cada card (destaca "Eu" em azul).
3.3 Notas internas · migration conversation_notes · composable + seção
colapsável no drawer · apenas o criador pode editar/apagar (RLS).
3.5 Converter desconhecido em paciente · botão + dialog quick-cadastro ·
"Vincular existente" com Select filter de até 500 pacientes · cria
telefone WhatsApp (vinculado) via upsertWhatsappForExisting.
3.6 Histórico de conversa no prontuário · nova aba "Conversas" em
PatientProntuario.vue · PatientConversationsTab.vue com stats (total /
recebidas / enviadas / primeira / última), SelectButton de filtro, timeline
com bolhas por direção, mídia inline (imagem/áudio/vídeo/doc via signed
URL), indicadores ✓ ✓✓ de delivery, botão "Abrir no CRM".
═══════════════════════════════════════════════════════════════════════════
MARCO A — UNIFICAÇÃO WHATSAPP (dois providers mutuamente exclusivos)
═══════════════════════════════════════════════════════════════════════════
- Página chooser ConfiguracoesWhatsappChooserPage.vue com 2 cards (Pessoal/
Oficial), deactivate via edge function deactivate-notification-channel
- send-whatsapp-message refatorada com roteamento por provider; Twilio deduz
1 crédito antes do envio e refunda em falha
- Paridade Twilio (novo): módulo compartilhado supabase/functions/_shared/
whatsapp-hooks.ts com lógica provider-agnóstica (opt-in, opt-out, auto-
reply, schedule helpers em TZ São Paulo, makeTwilioCreditedSendFn que
envolve envio em dedução atômica + rollback). Consumido por Evolution E
Twilio inbound. Evolution refatorado (~290 linhas duplicadas removidas).
- Bucket privado whatsapp-media · decrypt via Evolution getBase64From
MediaMessage · upload com path tenant/yyyy/mm · signed URLs on-demand
═══════════════════════════════════════════════════════════════════════════
MARCO B — SISTEMA DE CRÉDITOS WHATSAPP + ASAAS
═══════════════════════════════════════════════════════════════════════════
Banco:
- Migration 20260421000007_whatsapp_credits (4 tabelas: balance,
transactions, packages, purchases) + RPCs add_whatsapp_credits e
deduct_whatsapp_credits (atômicas com SELECT FOR UPDATE)
- Migration 20260421000013_tenant_cpf_cnpj (coluna em tenants com CHECK
de 11 ou 14 dígitos)
Edge functions:
- create-whatsapp-credit-charge · Asaas v3 (sandbox + prod) · PIX com
QR code · getOrCreateAsaasCustomer patcha customer existente com CPF
quando está faltando
- asaas-webhook · recebe PAYMENT_RECEIVED/CONFIRMED e credita balance
Frontend (tenant):
- Página /configuracoes/creditos-whatsapp com saldo + loja + histórico
- Dialog de confirmação com CPF/CNPJ (validação via isValidCPF/CNPJ de
utils/validators, formatação on-blur, pré-fill de tenants.cpf_cnpj,
persiste no primeiro uso) · fallback sandbox 24971563792 REMOVIDO
- Composable useWhatsappCredits extrai erros amigáveis via
error.context.json()
Frontend (SaaS admin):
- Em /saas/addons (reuso do pattern existente, não criou página paralela):
- Aba 4 "Pacotes WhatsApp" — CRUD whatsapp_credit_packages com DataTable,
toggle is_active inline, dialog de edição com validação
- Aba 5 "Topup WhatsApp" — tenant Select com saldo ao vivo · RPC
add_whatsapp_credits com p_admin_id = auth.uid() (auditoria) · histórico
das últimas 20 transações topup/adjustment/refund
═══════════════════════════════════════════════════════════════════════════
GRUPO 2 — AUTOMAÇÃO
═══════════════════════════════════════════════════════════════════════════
2.3 Auto-reply · conversation_autoreply_settings + conversation_autoreply_
log · 3 modos de schedule (agenda das regras semanais, business_hours
custom, custom_window) · cooldown por thread · respeita opt-out · agora
funciona em Evolution E Twilio (hooks compartilhados)
2.4 Lembretes de sessão · conversation_session_reminders_settings +
_logs · edge send-session-reminders (cron) · janelas 24h e 2h antes ·
Twilio deduz crédito com rollback em falha
═══════════════════════════════════════════════════════════════════════════
GRUPO 5 — COMPLIANCE (LGPD Art. 18 §2)
═══════════════════════════════════════════════════════════════════════════
5.2 Opt-out · conversation_optouts + conversation_optout_keywords (10 system
seed + custom por tenant) · detecção por regex word-boundary e normalização
(lowercase + strip acentos + pontuação) · ack automático (deduz crédito em
Twilio) · opt-in via "voltar", "retornar", "reativar", "restart" ·
página /configuracoes/conversas-optouts com CRUD de keywords
═══════════════════════════════════════════════════════════════════════════
REFACTOR POLIMÓRFICO — TELEFONES + EMAILS
═══════════════════════════════════════════════════════════════════════════
- contact_types + contact_phones (entity_type + entity_id) — migration
20260421000008 · contact_email_types + contact_emails — 20260421000011
- Componentes ContactPhonesEditor.vue e ContactEmailsEditor.vue (add/edit/
remove com confirm, primary selector, WhatsApp linked badge)
- Composables useContactPhones.js + useContactEmails.js com
unsetOtherPrimaries() e validação
- Trocado em PatientsCadastroPage.vue e MedicosPage.vue (removidos campos
legados telefone/telefone_alternativo e email_principal/email_alternativo)
- Migration retroativa v2 (20260421000010) detecta conversation_messages
e cria/atualiza phone como WhatsApp vinculado
═══════════════════════════════════════════════════════════════════════════
POLIMENTO VISUAL + INFRA
═══════════════════════════════════════════════════════════════════════════
- Skeletons simplificados no dashboard do terapeuta
- Animações fade-up com stagger via [--delay:Xms] (fix specificity sobre
.dash-card box-shadow transition)
- ConfirmDialog com group="conversation-drawer" (evita montagem duplicada)
- Image preview PrimeVue com botão de download injetado via MutationObserver
(fetch + blob para funcionar cross-origin)
- Áudio/vídeo com preload="metadata" e controles de velocidade do browser
- friendlySendError() mapeia códigos do edge pra mensagens pt-BR via
error.context.json()
- Teleport #cfg-page-actions para ações globais de Configurações
- Brotli/Gzip + auto-import Vue/PrimeVue + bundle analyzer
- AppLayout consolidado (removidas duplicatas por área) + RouterPassthrough
- Removido console.trace debug que estava em watch de router e queries
Supabase (degradava perf pra todos)
- Realtime em conversation_messages via publication supabase_realtime
- Notifier global flutuante com beep + toggle mute (4 camadas: badge +
sino + popup + browser notification)
═══════════════════════════════════════════════════════════════════════════
MIGRATIONS NOVAS (13)
═══════════════════════════════════════════════════════════════════════════
20260420000001_patient_intake_invite_info_rpc
20260420000002_audit_logs_lgpd
20260420000003_audit_logs_unified_view
20260420000004_lgpd_export_patient_rpc
20260420000005_conversation_messages
20260420000005_search_global_rpc
20260420000006_conv_messages_notifications
20260420000007_notif_channels_saas_admin_insert
20260420000008_conv_messages_realtime
20260420000009_conv_messages_delivery_status
20260421000001_whatsapp_media_bucket
20260421000002_conversation_notes
20260421000003_conversation_tags
20260421000004_conversation_autoreply
20260421000005_conversation_optouts
20260421000006_session_reminders
20260421000007_whatsapp_credits
20260421000008_contact_phones
20260421000009_retroactive_whatsapp_link
20260421000010_retroactive_whatsapp_link_v2
20260421000011_contact_emails
20260421000012_conversation_assignments
20260421000013_tenant_cpf_cnpj
═══════════════════════════════════════════════════════════════════════════
EDGE FUNCTIONS NOVAS / MODIFICADAS
═══════════════════════════════════════════════════════════════════════════
Novas:
- _shared/whatsapp-hooks.ts (módulo compartilhado)
- asaas-webhook
- create-whatsapp-credit-charge
- deactivate-notification-channel
- evolution-webhook-provision
- evolution-whatsapp-inbound
- get-intake-invite-info
- notification-webhook
- send-session-reminders
- send-whatsapp-message
- submit-patient-intake
- twilio-whatsapp-inbound
═══════════════════════════════════════════════════════════════════════════
FRONTEND — RESUMO
═══════════════════════════════════════════════════════════════════════════
Composables novos: useAddonExtrato, useAuditoria, useAutoReplySettings,
useClinicKPIs, useContactEmails, useContactPhones, useConversationAssignment,
useConversationNotes, useConversationOptouts, useConversationTags,
useConversations, useLgpdExport, useSessionReminders, useWhatsappCredits
Stores: conversationDrawerStore
Componentes novos: ConversationDrawer, GlobalInboundNotifier, GlobalSearch,
ContactEmailsEditor, ContactPhonesEditor
Páginas novas: CRMConversasPage, PatientConversationsTab, AddonsExtratoPage,
AuditoriaPage, NotificationsHistoryPage, ConfiguracoesWhatsappChooserPage,
ConfiguracoesConversasAutoreplyPage, ConfiguracoesConversasOptoutsPage,
ConfiguracoesConversasTagsPage, ConfiguracoesCreditosWhatsappPage,
ConfiguracoesLembretesSessaoPage
Utils novos: addonExtratoExport, auditoriaExport, excelExport,
lgpdExportFormats
Páginas existentes alteradas: ClinicDashboard, PatientsCadastroPage,
PatientCadastroDialog, PatientsListPage, MedicosPage, PatientProntuario,
ConfiguracoesWhatsappPage, SaasWhatsappPage, ConfiguracoesRecursosExtrasPage,
ConfiguracoesPage, AgendaTerapeutaPage, AgendaClinicaPage, NotificationItem,
NotificationDrawer, AppLayout, AppTopbar, useMenuBadges,
patientsRepository, SaasAddonsPage (aba 4 + 5 WhatsApp)
Routes: routes.clinic, routes.configs, routes.therapist atualizados
Menus: clinic.menu, therapist.menu, saas.menu atualizados
═══════════════════════════════════════════════════════════════════════════
NOTAS
- Após subir, rodar supabase functions serve --no-verify-jwt
--env-file supabase/functions/.env pra carregar o módulo _shared
- WHATSAPP_SETUP.md reescrito (~400 linhas) com setup completo dos 3
providers + troubleshooting + LGPD
- HANDOFF.md atualizado com estado atual e próximos passos
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,400 @@
|
||||
<!--
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI — Auto-reply fora do horário (CRM Grupo 2.3)
|
||||
|--------------------------------------------------------------------------
|
||||
| Configurações de resposta automática quando paciente manda mensagem fora
|
||||
| do horário de atendimento.
|
||||
|--------------------------------------------------------------------------
|
||||
-->
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch } from 'vue';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { useAutoReplySettings } from '@/composables/useAutoReplySettings';
|
||||
|
||||
const toast = useToast();
|
||||
const tenantStore = useTenantStore();
|
||||
const api = useAutoReplySettings();
|
||||
|
||||
const DIAS = [
|
||||
{ dow: 0, label: 'Dom' },
|
||||
{ dow: 1, label: 'Seg' },
|
||||
{ dow: 2, label: 'Ter' },
|
||||
{ dow: 3, label: 'Qua' },
|
||||
{ dow: 4, label: 'Qui' },
|
||||
{ dow: 5, label: 'Sex' },
|
||||
{ dow: 6, label: 'Sáb' }
|
||||
];
|
||||
|
||||
const agendaWindows = ref([]);
|
||||
|
||||
// ── Preview do status atual ─────────────────────────────────
|
||||
const now = ref(new Date());
|
||||
let _tick = null;
|
||||
|
||||
const currentWindows = computed(() => {
|
||||
if (api.settings.value.schedule_mode === 'agenda') return agendaWindows.value;
|
||||
if (api.settings.value.schedule_mode === 'business_hours') return api.settings.value.business_hours || [];
|
||||
if (api.settings.value.schedule_mode === 'custom') return api.settings.value.custom_window || [];
|
||||
return [];
|
||||
});
|
||||
|
||||
function hhmmToMin(s) {
|
||||
const m = String(s || '').match(/^(\d{1,2}):(\d{2})/);
|
||||
return m ? parseInt(m[1], 10) * 60 + parseInt(m[2], 10) : -1;
|
||||
}
|
||||
|
||||
const isWithinHoursNow = computed(() => {
|
||||
const d = now.value;
|
||||
// Hora de São Paulo
|
||||
const fmt = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone: 'America/Sao_Paulo',
|
||||
weekday: 'short',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false
|
||||
});
|
||||
const parts = fmt.formatToParts(d);
|
||||
const weekday = parts.find((p) => p.type === 'weekday')?.value || 'Sun';
|
||||
const h = parseInt(parts.find((p) => p.type === 'hour')?.value || '0', 10);
|
||||
const mm = parseInt(parts.find((p) => p.type === 'minute')?.value || '0', 10);
|
||||
const dowMap = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
|
||||
const dow = dowMap[weekday] ?? 0;
|
||||
const mins = h * 60 + mm;
|
||||
for (const w of currentWindows.value) {
|
||||
if (w.dow !== dow) continue;
|
||||
const s = hhmmToMin(w.start);
|
||||
const e = hhmmToMin(w.end);
|
||||
if (s < 0 || e < 0) continue;
|
||||
if (mins >= s && mins < e) return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
const nowLabel = computed(() => {
|
||||
return new Intl.DateTimeFormat('pt-BR', {
|
||||
timeZone: 'America/Sao_Paulo',
|
||||
weekday: 'long',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
}).format(now.value);
|
||||
});
|
||||
|
||||
// ── Editor de janelas (business_hours / custom_window) ──────
|
||||
function targetArrayKey() {
|
||||
if (api.settings.value.schedule_mode === 'business_hours') return 'business_hours';
|
||||
if (api.settings.value.schedule_mode === 'custom') return 'custom_window';
|
||||
return null;
|
||||
}
|
||||
|
||||
function addWindow(dow) {
|
||||
const key = targetArrayKey();
|
||||
if (!key) return;
|
||||
const arr = [...(api.settings.value[key] || [])];
|
||||
arr.push({ dow, start: '08:00', end: '18:00' });
|
||||
arr.sort((a, b) => a.dow - b.dow || hhmmToMin(a.start) - hhmmToMin(b.start));
|
||||
api.settings.value = { ...api.settings.value, [key]: arr };
|
||||
}
|
||||
|
||||
function updateWindow(idx, patch) {
|
||||
const key = targetArrayKey();
|
||||
if (!key) return;
|
||||
const arr = [...(api.settings.value[key] || [])];
|
||||
arr[idx] = { ...arr[idx], ...patch };
|
||||
api.settings.value = { ...api.settings.value, [key]: arr };
|
||||
}
|
||||
|
||||
function removeWindow(idx) {
|
||||
const key = targetArrayKey();
|
||||
if (!key) return;
|
||||
const arr = [...(api.settings.value[key] || [])];
|
||||
arr.splice(idx, 1);
|
||||
api.settings.value = { ...api.settings.value, [key]: arr };
|
||||
}
|
||||
|
||||
function applyDefaultWindow() {
|
||||
const key = targetArrayKey();
|
||||
if (!key) return;
|
||||
// Seg-Sex 09h-18h
|
||||
const arr = [1, 2, 3, 4, 5].map((dow) => ({ dow, start: '09:00', end: '18:00' }));
|
||||
api.settings.value = { ...api.settings.value, [key]: arr };
|
||||
}
|
||||
|
||||
function clearWindows() {
|
||||
const key = targetArrayKey();
|
||||
if (!key) return;
|
||||
api.settings.value = { ...api.settings.value, [key]: [] };
|
||||
}
|
||||
|
||||
const editableWindows = computed(() => {
|
||||
const key = targetArrayKey();
|
||||
if (!key) return [];
|
||||
return api.settings.value[key] || [];
|
||||
});
|
||||
|
||||
// ── Ações ───────────────────────────────────────────────────
|
||||
async function onSave() {
|
||||
const res = await api.save();
|
||||
if (res.ok) {
|
||||
toast.add({ severity: 'success', summary: 'Salvo', life: 2000 });
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshAgenda() {
|
||||
agendaWindows.value = await api.loadAgendaWindows();
|
||||
}
|
||||
|
||||
// ── Lifecycle ───────────────────────────────────────────────
|
||||
onMounted(async () => {
|
||||
await Promise.all([api.load(), refreshAgenda()]);
|
||||
_tick = setInterval(() => { now.value = new Date(); }, 30000);
|
||||
});
|
||||
|
||||
watch(() => tenantStore.activeTenantId, async () => {
|
||||
await Promise.all([api.load(), refreshAgenda()]);
|
||||
});
|
||||
|
||||
import { onBeforeUnmount } from 'vue';
|
||||
onBeforeUnmount(() => { if (_tick) clearInterval(_tick); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Ações no header do parent -->
|
||||
<Teleport to="#cfg-page-actions" defer>
|
||||
<Button
|
||||
label="Salvar"
|
||||
icon="pi pi-check"
|
||||
size="small"
|
||||
class="rounded-full"
|
||||
:loading="api.saving.value"
|
||||
:disabled="api.loading.value"
|
||||
@click="onSave"
|
||||
/>
|
||||
<Button
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="h-9 w-9 rounded-full"
|
||||
:loading="api.loading.value"
|
||||
v-tooltip.bottom="'Recarregar'"
|
||||
@click="api.load()"
|
||||
/>
|
||||
</Teleport>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- Preview de status atual -->
|
||||
<div
|
||||
class="rounded-md border p-3 flex items-center gap-3"
|
||||
:class="api.settings.value.enabled
|
||||
? (isWithinHoursNow
|
||||
? 'border-green-500/30 bg-green-500/5'
|
||||
: 'border-amber-500/30 bg-amber-500/5')
|
||||
: 'border-[var(--surface-border)] bg-[var(--surface-card)] opacity-80'"
|
||||
>
|
||||
<i
|
||||
class="pi text-lg shrink-0"
|
||||
:class="!api.settings.value.enabled
|
||||
? 'pi-pause-circle text-[var(--text-color-secondary)]'
|
||||
: isWithinHoursNow
|
||||
? 'pi-check-circle text-green-500'
|
||||
: 'pi-bolt text-amber-500'"
|
||||
/>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="text-sm font-semibold text-[var(--text-color)]">
|
||||
<template v-if="!api.settings.value.enabled">Auto-reply desabilitado</template>
|
||||
<template v-else-if="isWithinHoursNow">Dentro do horário — auto-reply NÃO disparará</template>
|
||||
<template v-else>Fora do horário — auto-reply disparará para novas mensagens</template>
|
||||
</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-0.5 capitalize">
|
||||
{{ nowLabel }} · fuso São Paulo
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Toggle + mensagem -->
|
||||
<div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-3">
|
||||
<div class="flex items-center gap-3 flex-wrap">
|
||||
<label class="flex items-center gap-2 cursor-pointer">
|
||||
<ToggleSwitch v-model="api.settings.value.enabled" />
|
||||
<span class="text-sm font-semibold">
|
||||
{{ api.settings.value.enabled ? 'Auto-reply ativado' : 'Auto-reply desativado' }}
|
||||
</span>
|
||||
</label>
|
||||
<span class="text-xs text-[var(--text-color-secondary)]">
|
||||
Envia resposta automática quando mensagem chega fora do horário configurado.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-[var(--text-color-secondary)] mb-1">Mensagem automática</label>
|
||||
<Textarea
|
||||
v-model="api.settings.value.message"
|
||||
rows="3"
|
||||
autoResize
|
||||
:maxlength="2000"
|
||||
class="w-full"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
/>
|
||||
<div class="text-[0.7rem] text-[var(--text-color-secondary)] mt-1">
|
||||
{{ (api.settings.value.message || '').length }} / 2000
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-[var(--text-color-secondary)] mb-1">
|
||||
Cooldown por paciente: <span class="text-[var(--text-color)]">{{ api.settings.value.cooldown_minutes }} min</span>
|
||||
</label>
|
||||
<div class="flex flex-col sm:flex-row sm:items-center gap-2">
|
||||
<InputNumber
|
||||
v-model="api.settings.value.cooldown_minutes"
|
||||
:min="0"
|
||||
:max="43200"
|
||||
suffix=" min"
|
||||
inputClass="!w-28"
|
||||
class="shrink-0"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
/>
|
||||
<span class="text-xs text-[var(--text-color-secondary)] flex-1 min-w-0 leading-snug">
|
||||
Tempo mínimo entre auto-replies para a mesma conversa (evita spam). Sugestão: 180 min (3h).
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modo de horário -->
|
||||
<div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<i class="pi pi-clock text-[var(--primary-color)]" />
|
||||
<span class="text-sm font-bold uppercase tracking-wide">Quando disparar</span>
|
||||
</div>
|
||||
|
||||
<SelectButton
|
||||
v-model="api.settings.value.schedule_mode"
|
||||
:options="[
|
||||
{ label: 'Seguir minha agenda', value: 'agenda' },
|
||||
{ label: 'Horário de funcionamento', value: 'business_hours' },
|
||||
{ label: 'Personalizado', value: 'custom' }
|
||||
]"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
:allowEmpty="false"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
/>
|
||||
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">
|
||||
<template v-if="api.settings.value.schedule_mode === 'agenda'">
|
||||
Usa automaticamente os horários da <strong>Agenda</strong> (agenda_regras_semanais) de todos os profissionais ativos do tenant. Se alguém está trabalhando agora, é considerado "dentro do horário".
|
||||
</template>
|
||||
<template v-else-if="api.settings.value.schedule_mode === 'business_hours'">
|
||||
Define um horário geral da clínica, reutilizável por outras automações. Independe das agendas individuais.
|
||||
</template>
|
||||
<template v-else>
|
||||
Define um horário exclusivo para este auto-reply. Útil se você quer que responda antes/depois do expediente normal.
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- Preview das janelas do modo 'agenda' (read-only) -->
|
||||
<div v-if="api.settings.value.schedule_mode === 'agenda'" class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-ground)] p-3">
|
||||
<div v-if="!agendaWindows.length" class="text-xs text-[var(--text-color-secondary)] italic">
|
||||
Nenhuma regra semanal ativa encontrada na agenda. Configure em <a href="/configuracoes/agenda" class="text-[var(--primary-color)] underline">Configurações → Agenda</a>.
|
||||
</div>
|
||||
<div v-else class="grid grid-cols-7 gap-1">
|
||||
<div v-for="d in DIAS" :key="d.dow" class="flex flex-col items-center gap-1">
|
||||
<div class="text-[0.7rem] font-semibold text-[var(--text-color-secondary)] uppercase">{{ d.label }}</div>
|
||||
<div class="flex flex-col gap-0.5 w-full">
|
||||
<div
|
||||
v-for="(w, i) in agendaWindows.filter(x => x.dow === d.dow)"
|
||||
:key="i"
|
||||
class="text-[0.65rem] text-center font-mono rounded bg-[var(--primary-color)]/10 text-[var(--primary-color)] px-1 py-0.5"
|
||||
>
|
||||
{{ w.start }}–{{ w.end }}
|
||||
</div>
|
||||
<div v-if="!agendaWindows.some(x => x.dow === d.dow)" class="text-[0.65rem] text-center text-[var(--text-color-secondary)] opacity-40">—</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Editor de janelas (business_hours / custom) -->
|
||||
<div v-else class="flex flex-col gap-2">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<Button
|
||||
label="Aplicar padrão Seg-Sex 09h-18h"
|
||||
icon="pi pi-calendar"
|
||||
size="small"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="rounded-full"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
@click="applyDefaultWindow"
|
||||
/>
|
||||
<Button
|
||||
label="Limpar"
|
||||
icon="pi pi-times"
|
||||
size="small"
|
||||
severity="danger"
|
||||
text
|
||||
:disabled="!api.settings.value.enabled || !editableWindows.length"
|
||||
@click="clearWindows"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-7 gap-1.5 border border-[var(--surface-border)] rounded-md bg-[var(--surface-ground)] p-2">
|
||||
<div v-for="d in DIAS" :key="d.dow" class="flex flex-col gap-1 min-h-[80px]">
|
||||
<div class="text-[0.7rem] font-bold text-[var(--text-color-secondary)] uppercase text-center">{{ d.label }}</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<div
|
||||
v-for="(w, idx) in editableWindows.map((x, i) => ({ ...x, _idx: i })).filter(x => x.dow === d.dow)"
|
||||
:key="w._idx"
|
||||
class="flex flex-col gap-0.5 bg-[var(--surface-card)] rounded p-1"
|
||||
>
|
||||
<input
|
||||
type="time"
|
||||
:value="w.start"
|
||||
class="text-[0.68rem] px-1 py-0.5 rounded border border-[var(--surface-border)] bg-[var(--surface-card)] w-full"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
@change="(e) => updateWindow(w._idx, { start: e.target.value })"
|
||||
/>
|
||||
<input
|
||||
type="time"
|
||||
:value="w.end"
|
||||
class="text-[0.68rem] px-1 py-0.5 rounded border border-[var(--surface-border)] bg-[var(--surface-card)] w-full"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
@change="(e) => updateWindow(w._idx, { end: e.target.value })"
|
||||
/>
|
||||
<button
|
||||
class="text-[0.6rem] text-red-500 hover:text-red-700 bg-transparent border-0 cursor-pointer p-0 leading-tight"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
@click="removeWindow(w._idx)"
|
||||
>
|
||||
<i class="pi pi-times text-[0.55rem]" /> remover
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
class="text-[0.65rem] text-[var(--text-color-secondary)] hover:text-[var(--primary-color)] bg-transparent border border-dashed border-[var(--surface-border)] rounded py-0.5 cursor-pointer"
|
||||
:disabled="!api.settings.value.enabled"
|
||||
@click="addWindow(d.dow)"
|
||||
>
|
||||
+ adicionar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Info sobre dependências -->
|
||||
<div class="rounded-md border border-sky-500/25 bg-sky-500/5 p-3 flex items-start gap-2 text-xs text-[var(--text-color)]">
|
||||
<i class="pi pi-info-circle text-sky-500 mt-0.5" />
|
||||
<div>
|
||||
<strong>Pré-requisito:</strong> o WhatsApp do tenant precisa estar conectado em
|
||||
<a href="/configuracoes/whatsapp" class="text-[var(--primary-color)] underline">Configurações → WhatsApp</a>.
|
||||
O auto-reply é enviado via o mesmo canal.
|
||||
<br/>
|
||||
Todas as datas/horas são tratadas no fuso <strong>America/Sao_Paulo</strong>.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
Reference in New Issue
Block a user