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:
Leonardo
2026-04-23 07:05:24 -03:00
parent 037ba3721f
commit 2644e60bb6
191 changed files with 38629 additions and 3756 deletions
+184 -2
View File
@@ -1,6 +1,6 @@
-- Indexes
-- Gerado automaticamente em 2026-04-17T12:23:05.235Z
-- Total: 270
-- Gerado automaticamente em 2026-04-21T23:16:34.961Z
-- Total: 361
CREATE INDEX agenda_bloqueios_owner_data_idx ON public.agenda_bloqueios USING btree (owner_id, data_inicio, data_fim);
@@ -166,10 +166,126 @@ CREATE INDEX idx_addon_tx_type ON public.addon_transactions USING btree (type);
CREATE INDEX idx_agenda_eventos_determined_commitment_id ON public.agenda_eventos USING btree (determined_commitment_id);
CREATE INDEX idx_agenda_eventos_titulo_custom_trgm ON public.agenda_eventos USING gin (titulo_custom public.gin_trgm_ops) WHERE (titulo_custom IS NOT NULL);
CREATE INDEX idx_agenda_eventos_titulo_trgm ON public.agenda_eventos USING gin (titulo public.gin_trgm_ops) WHERE (titulo IS NOT NULL);
CREATE INDEX idx_agenda_excecoes_owner_data ON public.agenda_excecoes USING btree (owner_id, data);
CREATE INDEX idx_agenda_slots_regras_owner_dia ON public.agenda_slots_regras USING btree (owner_id, dia_semana);
CREATE INDEX idx_audit_logs_changed_fields ON public.audit_logs USING gin (changed_fields);
CREATE INDEX idx_audit_logs_entity ON public.audit_logs USING btree (entity_type, entity_id);
CREATE INDEX idx_audit_logs_tenant_created ON public.audit_logs USING btree (tenant_id, created_at DESC);
CREATE INDEX idx_audit_logs_user_created ON public.audit_logs USING btree (user_id, created_at DESC) WHERE (user_id IS NOT NULL);
CREATE INDEX idx_autoreply_log_cooldown ON public.conversation_autoreply_log USING btree (tenant_id, thread_key, sent_at DESC);
CREATE INDEX idx_contact_email_types_tenant ON public.contact_email_types USING btree (tenant_id, "position");
CREATE INDEX idx_contact_emails_email ON public.contact_emails USING btree (tenant_id, email);
CREATE INDEX idx_contact_emails_entity ON public.contact_emails USING btree (tenant_id, entity_type, entity_id, "position");
CREATE INDEX idx_contact_phones_entity ON public.contact_phones USING btree (tenant_id, entity_type, entity_id, "position");
CREATE INDEX idx_contact_phones_number ON public.contact_phones USING btree (tenant_id, number);
CREATE INDEX idx_contact_types_tenant ON public.contact_types USING btree (tenant_id, "position");
CREATE INDEX idx_conv_msg_delivery_status ON public.conversation_messages USING btree (tenant_id, delivery_status) WHERE (direction = 'outbound'::text);
CREATE INDEX idx_conv_msg_from_number ON public.conversation_messages USING btree (tenant_id, from_number);
CREATE INDEX idx_conv_msg_kanban ON public.conversation_messages USING btree (tenant_id, kanban_status, priority DESC, created_at DESC);
CREATE INDEX idx_conv_msg_patient ON public.conversation_messages USING btree (patient_id, created_at DESC) WHERE (patient_id IS NOT NULL);
CREATE INDEX idx_conv_msg_provider_msg_id ON public.conversation_messages USING btree (provider_message_id) WHERE (provider_message_id IS NOT NULL);
CREATE INDEX idx_conv_msg_tenant_created ON public.conversation_messages USING btree (tenant_id, created_at DESC);
CREATE INDEX idx_conv_notes_created_by ON public.conversation_notes USING btree (created_by, created_at DESC) WHERE (deleted_at IS NULL);
CREATE INDEX idx_conv_notes_patient ON public.conversation_notes USING btree (patient_id, created_at DESC) WHERE ((deleted_at IS NULL) AND (patient_id IS NOT NULL));
CREATE INDEX idx_conv_notes_tenant_thread ON public.conversation_notes USING btree (tenant_id, thread_key, created_at DESC) WHERE (deleted_at IS NULL);
CREATE INDEX idx_conv_optout_kw_tenant ON public.conversation_optout_keywords USING btree (tenant_id) WHERE (enabled = true);
CREATE INDEX idx_conv_optouts_patient ON public.conversation_optouts USING btree (patient_id) WHERE (patient_id IS NOT NULL);
CREATE INDEX idx_conv_optouts_tenant_phone ON public.conversation_optouts USING btree (tenant_id, phone);
CREATE INDEX idx_conv_tags_tenant ON public.conversation_tags USING btree (tenant_id, "position");
CREATE INDEX idx_conv_thread_tags_tag ON public.conversation_thread_tags USING btree (tag_id);
CREATE INDEX idx_conv_thread_tags_tenant_thread ON public.conversation_thread_tags USING btree (tenant_id, thread_key);
CREATE INDEX idx_dev_auditoria_items_categoria ON public.dev_auditoria_items USING btree (categoria);
CREATE INDEX idx_dev_auditoria_items_ordem ON public.dev_auditoria_items USING btree (ordem);
CREATE INDEX idx_dev_auditoria_items_severidade ON public.dev_auditoria_items USING btree (severidade);
CREATE INDEX idx_dev_auditoria_items_status ON public.dev_auditoria_items USING btree (status);
CREATE INDEX idx_dev_ccs_comp ON public.dev_comparison_competitor_status USING btree (competitor_id);
CREATE INDEX idx_dev_ccs_comparison ON public.dev_comparison_competitor_status USING btree (comparison_id);
CREATE INDEX idx_dev_comparison_matrix_dominio ON public.dev_comparison_matrix USING btree (dominio);
CREATE INDEX idx_dev_comparison_matrix_status ON public.dev_comparison_matrix USING btree (nosso_status);
CREATE INDEX idx_dev_competitor_features_cat ON public.dev_competitor_features USING btree (categoria);
CREATE INDEX idx_dev_competitor_features_comp ON public.dev_competitor_features USING btree (competitor_id);
CREATE INDEX idx_dev_competitor_features_destaque ON public.dev_competitor_features USING btree (destaque);
CREATE INDEX idx_dev_competitor_features_ordem ON public.dev_competitor_features USING btree (competitor_id, ordem);
CREATE INDEX idx_dev_competitors_ativo ON public.dev_competitors USING btree (ativo);
CREATE INDEX idx_dev_competitors_pais ON public.dev_competitors USING btree (pais);
CREATE INDEX idx_dev_generation_log_created ON public.dev_generation_log USING btree (created_at DESC);
CREATE INDEX idx_dev_generation_log_tipo ON public.dev_generation_log USING btree (tipo);
CREATE INDEX idx_dev_roadmap_items_ordem ON public.dev_roadmap_items USING btree (phase_id, ordem);
CREATE INDEX idx_dev_roadmap_items_phase ON public.dev_roadmap_items USING btree (phase_id);
CREATE INDEX idx_dev_roadmap_items_prior ON public.dev_roadmap_items USING btree (prioridade);
CREATE INDEX idx_dev_roadmap_items_status ON public.dev_roadmap_items USING btree (status);
CREATE INDEX idx_dev_roadmap_phases_ordem ON public.dev_roadmap_phases USING btree (ordem);
CREATE INDEX idx_dev_roadmap_phases_status ON public.dev_roadmap_phases USING btree (status);
CREATE INDEX idx_dev_test_items_area ON public.dev_test_items USING btree (area);
CREATE INDEX idx_dev_test_items_ordem ON public.dev_test_items USING btree (area, ordem);
CREATE INDEX idx_dev_test_items_status ON public.dev_test_items USING btree (status);
CREATE INDEX idx_dev_verificacoes_area ON public.dev_verificacoes_items USING btree (area);
CREATE INDEX idx_dev_verificacoes_ordem ON public.dev_verificacoes_items USING btree (area, ordem);
CREATE INDEX idx_dev_verificacoes_severidade ON public.dev_verificacoes_items USING btree (severidade);
CREATE INDEX idx_dev_verificacoes_status ON public.dev_verificacoes_items USING btree (status);
CREATE INDEX idx_documents_content_sha256 ON public.documents USING btree (content_sha256) WHERE (content_sha256 IS NOT NULL);
CREATE INDEX idx_email_templates_global_domain ON public.email_templates_global USING btree (domain) WHERE (is_active = true);
CREATE INDEX idx_email_templates_global_key ON public.email_templates_global USING btree (key) WHERE (is_active = true);
@@ -178,6 +294,8 @@ CREATE INDEX idx_email_templates_tenant_lookup ON public.email_templates_tenant
CREATE INDEX idx_email_templates_tenant_owner ON public.email_templates_tenant USING btree (owner_id, template_key) WHERE ((enabled = true) AND (owner_id IS NOT NULL));
CREATE INDEX idx_features_is_active ON public.features USING btree (is_active) WHERE (is_active = false);
CREATE INDEX idx_financial_categories_user_id ON public.financial_categories USING btree (user_id);
CREATE INDEX idx_financial_records_active ON public.financial_records USING btree (owner_id, paid_at DESC) WHERE (deleted_at IS NULL);
@@ -216,6 +334,8 @@ CREATE INDEX idx_intakes_owner_status_created ON public.patient_intake_requests
CREATE INDEX idx_intakes_status_created ON public.patient_intake_requests USING btree (status, created_at DESC);
CREATE INDEX idx_mc_expires ON public.math_challenges USING btree (expires_at);
CREATE INDEX idx_notice_dismissals_user ON public.notice_dismissals USING btree (user_id, notice_id);
CREATE INDEX idx_notif_channels_owner_active ON public.notification_channels USING btree (owner_id, channel) WHERE ((is_active = true) AND (deleted_at IS NULL));
@@ -270,12 +390,28 @@ CREATE INDEX idx_patient_groups_owner ON public.patient_groups USING btree (owne
CREATE INDEX idx_patient_groups_owner_system_nome ON public.patient_groups USING btree (owner_id, is_system, nome);
CREATE INDEX idx_patient_intake_requests_nome_trgm ON public.patient_intake_requests USING gin (nome_completo public.gin_trgm_ops) WHERE (status = 'new'::text);
CREATE INDEX idx_patient_invite_attempts_created ON public.patient_invite_attempts USING btree (created_at DESC);
CREATE INDEX idx_patient_invite_attempts_ok ON public.patient_invite_attempts USING btree (ok) WHERE (ok = false);
CREATE INDEX idx_patient_invite_attempts_owner ON public.patient_invite_attempts USING btree (owner_id);
CREATE INDEX idx_patient_invite_attempts_token ON public.patient_invite_attempts USING btree (token);
CREATE INDEX idx_patient_tags_owner ON public.patient_tags USING btree (owner_id);
CREATE INDEX idx_patients_cpf_trgm ON public.patients USING gin (cpf public.gin_trgm_ops) WHERE (cpf IS NOT NULL);
CREATE INDEX idx_patients_created_at ON public.patients USING btree (created_at DESC);
CREATE INDEX idx_patients_email_trgm ON public.patients USING gin (email_principal public.gin_trgm_ops) WHERE (email_principal IS NOT NULL);
CREATE INDEX idx_patients_last_attended ON public.patients USING btree (last_attended_at DESC);
CREATE INDEX idx_patients_nome_trgm ON public.patients USING gin (nome_completo public.gin_trgm_ops);
CREATE INDEX idx_patients_origem ON public.patients USING btree (tenant_id, origem) WHERE (origem IS NOT NULL);
CREATE INDEX idx_patients_owner_email_principal ON public.patients USING btree (owner_id, email_principal);
@@ -304,6 +440,12 @@ CREATE INDEX idx_ppt_patient ON public.patient_patient_tag USING btree (patient_
CREATE INDEX idx_ppt_tag ON public.patient_patient_tag USING btree (tag_id);
CREATE INDEX idx_psa_endpoint_created ON public.public_submission_attempts USING btree (endpoint, created_at DESC);
CREATE INDEX idx_psa_failed ON public.public_submission_attempts USING btree (created_at DESC) WHERE (success = false);
CREATE INDEX idx_psa_ip_hash_created ON public.public_submission_attempts USING btree (ip_hash, created_at DESC) WHERE (ip_hash IS NOT NULL);
CREATE INDEX idx_psh_patient ON public.patient_status_history USING btree (patient_id, alterado_em DESC);
CREATE INDEX idx_psh_tenant ON public.patient_status_history USING btree (tenant_id, alterado_em DESC);
@@ -314,8 +456,16 @@ CREATE INDEX idx_pt_patient_ocorrido ON public.patient_timeline USING btree (pat
CREATE INDEX idx_pt_tenant ON public.patient_timeline USING btree (tenant_id, ocorrido_em DESC);
CREATE INDEX idx_services_name_trgm ON public.services USING gin (name public.gin_trgm_ops);
CREATE INDEX idx_session_reminder_tenant_sent ON public.session_reminder_logs USING btree (tenant_id, sent_at DESC);
CREATE INDEX idx_slots_bloq_owner_dia ON public.agenda_slots_bloqueados_semanais USING btree (owner_id, dia_semana);
CREATE INDEX idx_srl_blocked_until ON public.submission_rate_limits USING btree (blocked_until) WHERE (blocked_until IS NOT NULL);
CREATE INDEX idx_srl_endpoint ON public.submission_rate_limits USING btree (endpoint, last_attempt_at DESC);
CREATE INDEX idx_subscription_intents_plan_interval ON public.subscription_intents_legacy USING btree (plan_key, "interval");
CREATE INDEX idx_subscription_intents_status ON public.subscription_intents_legacy USING btree (status);
@@ -344,6 +494,18 @@ CREATE INDEX idx_twilio_usage_tenant_period ON public.twilio_subaccount_usage US
CREATE UNIQUE INDEX idx_twilio_usage_unique_period ON public.twilio_subaccount_usage USING btree (channel_id, period_start, period_end);
CREATE INDEX idx_wa_credit_packages_active ON public.whatsapp_credit_packages USING btree (is_active, "position", price_brl) WHERE (is_active = true);
CREATE INDEX idx_wa_credit_purchases_asaas_payment ON public.whatsapp_credit_purchases USING btree (asaas_payment_id) WHERE (asaas_payment_id IS NOT NULL);
CREATE INDEX idx_wa_credit_purchases_status ON public.whatsapp_credit_purchases USING btree (status, created_at DESC);
CREATE INDEX idx_wa_credit_purchases_tenant ON public.whatsapp_credit_purchases USING btree (tenant_id, created_at DESC);
CREATE INDEX idx_wa_credits_tx_kind ON public.whatsapp_credits_transactions USING btree (tenant_id, kind, created_at DESC);
CREATE INDEX idx_wa_credits_tx_tenant_created ON public.whatsapp_credits_transactions USING btree (tenant_id, created_at DESC);
CREATE INDEX insurance_plans_owner_idx ON public.insurance_plans USING btree (owner_id);
CREATE INDEX insurance_plans_tenant_idx ON public.insurance_plans USING btree (tenant_id);
@@ -522,6 +684,24 @@ CREATE INDEX tenant_modules_owner_idx ON public.tenant_modules USING btree (owne
CREATE UNIQUE INDEX unique_member_per_tenant ON public.tenant_members USING btree (tenant_id, user_id);
CREATE UNIQUE INDEX uq_contact_email_types_system_slug ON public.contact_email_types USING btree (slug) WHERE (tenant_id IS NULL);
CREATE UNIQUE INDEX uq_contact_email_types_tenant_slug ON public.contact_email_types USING btree (tenant_id, slug) WHERE (tenant_id IS NOT NULL);
CREATE UNIQUE INDEX uq_contact_emails_primary ON public.contact_emails USING btree (entity_type, entity_id) WHERE (is_primary = true);
CREATE UNIQUE INDEX uq_contact_phones_primary ON public.contact_phones USING btree (entity_type, entity_id) WHERE (is_primary = true);
CREATE UNIQUE INDEX uq_contact_types_system_slug ON public.contact_types USING btree (slug) WHERE (tenant_id IS NULL);
CREATE UNIQUE INDEX uq_contact_types_tenant_slug ON public.contact_types USING btree (tenant_id, slug) WHERE (tenant_id IS NOT NULL);
CREATE UNIQUE INDEX uq_conv_optouts_active ON public.conversation_optouts USING btree (tenant_id, phone) WHERE (opted_back_in_at IS NULL);
CREATE UNIQUE INDEX uq_conv_tags_system_slug ON public.conversation_tags USING btree (slug) WHERE (tenant_id IS NULL);
CREATE UNIQUE INDEX uq_conv_tags_tenant_slug ON public.conversation_tags USING btree (tenant_id, slug) WHERE (tenant_id IS NOT NULL);
CREATE UNIQUE INDEX uq_patient_contacts_primario ON public.patient_contacts USING btree (patient_id) WHERE ((is_primario = true) AND (ativo = true));
CREATE UNIQUE INDEX uq_patients_tenant_user ON public.patients USING btree (tenant_id, user_id) WHERE (user_id IS NOT NULL);
@@ -530,6 +710,8 @@ CREATE UNIQUE INDEX uq_plan_price_active ON public.plan_prices USING btree (plan
CREATE UNIQUE INDEX uq_plan_prices_active ON public.plan_prices USING btree (plan_id, "interval") WHERE (is_active = true);
CREATE UNIQUE INDEX uq_session_reminder_event_type ON public.session_reminder_logs USING btree (event_id, reminder_type);
CREATE UNIQUE INDEX uq_subscriptions_active_by_tenant ON public.subscriptions USING btree (tenant_id) WHERE ((tenant_id IS NOT NULL) AND (status = 'active'::text));
CREATE UNIQUE INDEX uq_subscriptions_active_personal_by_user ON public.subscriptions USING btree (user_id) WHERE ((tenant_id IS NULL) AND (status = 'active'::text));