ZERADO
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -2,7 +2,6 @@
|
||||
import { computed } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
|
||||
import Button from 'primevue/button'
|
||||
|
||||
// Se você ainda usa o FloatingConfigurator no template de páginas públicas,
|
||||
// pode manter. Se não usa, pode remover tranquilamente.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,9 +0,0 @@
|
||||
<template>
|
||||
<div class="p-4">
|
||||
<h1>My Appointments</h1>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
// temporary placeholder
|
||||
</script>
|
||||
@@ -1,9 +0,0 @@
|
||||
<template>
|
||||
<div class="p-4">
|
||||
<h1>Add New Appointments</h1>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
// temporary placeholder
|
||||
</script>
|
||||
@@ -1,330 +0,0 @@
|
||||
<template>
|
||||
<div class="p-4 md:p-6">
|
||||
<Toast />
|
||||
|
||||
<!-- Header -->
|
||||
<div class="mb-4 overflow-hidden rounded-[2rem] border border-[var(--surface-border)] bg-[var(--surface-card)]">
|
||||
<div class="relative p-5 md:p-7">
|
||||
<!-- blobs sutis -->
|
||||
<div class="pointer-events-none absolute inset-0 opacity-80">
|
||||
<div class="absolute -top-16 -right-20 h-72 w-72 rounded-full bg-indigo-400/10 blur-3xl" />
|
||||
<div class="absolute top-10 -left-24 h-80 w-80 rounded-full bg-emerald-400/10 blur-3xl" />
|
||||
<div class="absolute -bottom-20 right-24 h-72 w-72 rounded-full bg-fuchsia-400/10 blur-3xl" />
|
||||
</div>
|
||||
|
||||
<div class="relative flex flex-col gap-2">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<h1 class="text-xl md:text-2xl font-semibold leading-tight">Módulos da Clínica</h1>
|
||||
<p class="mt-1 text-sm opacity-80">
|
||||
Ative/desative recursos por clínica. Isso controla menu, rotas (guard) e acesso no banco (RLS).
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 flex items-center gap-2">
|
||||
<Button
|
||||
label="Recarregar"
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
:loading="loading"
|
||||
@click="reload"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-2 flex flex-wrap items-center gap-2 text-xs opacity-80">
|
||||
<span class="inline-flex items-center gap-2 rounded-full border border-[var(--surface-border)] px-3 py-1">
|
||||
<i class="pi pi-building" />
|
||||
Tenant: <b class="font-mono">{{ tenantId || '—' }}</b>
|
||||
</span>
|
||||
<span class="inline-flex items-center gap-2 rounded-full border border-[var(--surface-border)] px-3 py-1">
|
||||
<i class="pi pi-user" />
|
||||
Role: <b>{{ role || '—' }}</b>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Presets -->
|
||||
<div class="mb-4 grid grid-cols-1 md:grid-cols-3 gap-3">
|
||||
<Card class="rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-semibold">Preset: Coworking</div>
|
||||
<div class="mt-1 text-xs opacity-80">
|
||||
Para aluguel de salas: sem pacientes, com salas.
|
||||
</div>
|
||||
</div>
|
||||
<Button size="small" label="Aplicar" severity="secondary" :loading="applyingPreset" @click="applyPreset('coworking')" />
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<Card class="rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-semibold">Preset: Clínica com recepção</div>
|
||||
<div class="mt-1 text-xs opacity-80">
|
||||
Para secretária gerenciar agenda (pacientes opcional).
|
||||
</div>
|
||||
</div>
|
||||
<Button size="small" label="Aplicar" severity="secondary" :loading="applyingPreset" @click="applyPreset('reception')" />
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<Card class="rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-semibold">Preset: Clínica completa</div>
|
||||
<div class="mt-1 text-xs opacity-80">
|
||||
Pacientes + recepção + salas (se quiser).
|
||||
</div>
|
||||
</div>
|
||||
<Button size="small" label="Aplicar" severity="secondary" :loading="applyingPreset" @click="applyPreset('full')" />
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<!-- Modules -->
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-3">
|
||||
<Card class="rounded-[2rem]">
|
||||
<template #content>
|
||||
<ModuleRow
|
||||
title="Pacientes"
|
||||
desc="Habilita gestão de pacientes por clínica. Todo paciente tem um responsável (therapist)."
|
||||
icon="pi pi-users"
|
||||
:enabled="isOn('patients')"
|
||||
:loading="savingKey === 'patients'"
|
||||
@toggle="toggle('patients')"
|
||||
/>
|
||||
<Divider class="my-4" />
|
||||
<div class="text-xs opacity-80 leading-relaxed">
|
||||
Quando desligado:
|
||||
<ul class="mt-2 list-disc pl-5 space-y-1">
|
||||
<li>Menu “Pacientes” some.</li>
|
||||
<li>Rotas com <span class="font-mono">meta.tenantFeature = 'patients'</span> redirecionam pra cá.</li>
|
||||
<li>RLS bloqueia acesso direto no banco.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<Card class="rounded-[2rem]">
|
||||
<template #content>
|
||||
<ModuleRow
|
||||
title="Recepção / Secretária"
|
||||
desc="Permite um papel de secretária gerenciar a agenda dos profissionais (sem precisar ver tudo do paciente)."
|
||||
icon="pi pi-briefcase"
|
||||
:enabled="isOn('shared_reception')"
|
||||
:loading="savingKey === 'shared_reception'"
|
||||
@toggle="toggle('shared_reception')"
|
||||
/>
|
||||
<Divider class="my-4" />
|
||||
<div class="text-xs opacity-80 leading-relaxed">
|
||||
Observação: este módulo é “produto” (UX + permissões). A base aqui é só o toggle.
|
||||
Depois a gente cria:
|
||||
<ul class="mt-2 list-disc pl-5 space-y-1">
|
||||
<li>role <span class="font-mono">secretary</span> em <span class="font-mono">tenant_members</span></li>
|
||||
<li>policies e telas para a secretária</li>
|
||||
<li>nível de visibilidade do paciente na agenda</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<Card class="rounded-[2rem]">
|
||||
<template #content>
|
||||
<ModuleRow
|
||||
title="Salas / Coworking"
|
||||
desc="Habilita cadastro e reserva de salas/recursos no agendamento."
|
||||
icon="pi pi-building"
|
||||
:enabled="isOn('rooms')"
|
||||
:loading="savingKey === 'rooms'"
|
||||
@toggle="toggle('rooms')"
|
||||
/>
|
||||
<Divider class="my-4" />
|
||||
<div class="text-xs opacity-80 leading-relaxed">
|
||||
Isso prepara o terreno para a clínica operar como locação de sala, com agenda vinculando sala + profissional.
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<Card class="rounded-[2rem]">
|
||||
<template #content>
|
||||
<ModuleRow
|
||||
title="Link externo de cadastro"
|
||||
desc="Libera fluxo público de intake/cadastro externo para a clínica."
|
||||
icon="pi pi-link"
|
||||
:enabled="isOn('intake_public')"
|
||||
:loading="savingKey === 'intake_public'"
|
||||
@toggle="toggle('intake_public')"
|
||||
/>
|
||||
<Divider class="my-4" />
|
||||
<div class="text-xs opacity-80 leading-relaxed">
|
||||
Você já tem páginas de link externo. Isso vira o controle fino: a clínica decide se usa ou não.
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
|
||||
import Toast from 'primevue/toast'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
import Card from 'primevue/card'
|
||||
import Button from 'primevue/button'
|
||||
import Divider from 'primevue/divider'
|
||||
import ToggleButton from 'primevue/togglebutton'
|
||||
|
||||
import { useTenantStore } from '@/stores/tenantStore'
|
||||
import { useTenantFeaturesStore } from '@/stores/tenantFeaturesStore'
|
||||
|
||||
const toast = useToast()
|
||||
const tenantStore = useTenantStore()
|
||||
const tf = useTenantFeaturesStore()
|
||||
|
||||
const loading = computed(() => tf.loading)
|
||||
const tenantId = computed(() => tenantStore.activeTenantId || null)
|
||||
const role = computed(() => tenantStore.activeRole || null)
|
||||
|
||||
const savingKey = ref(null)
|
||||
const applyingPreset = ref(false)
|
||||
|
||||
function isOn (key) {
|
||||
return tf.isEnabled(key)
|
||||
}
|
||||
|
||||
async function reload () {
|
||||
if (!tenantId.value) return
|
||||
await tf.fetchForTenant(tenantId.value, { force: true })
|
||||
}
|
||||
|
||||
async function toggle (key) {
|
||||
if (!tenantId.value) {
|
||||
toast.add({ severity: 'warn', summary: 'Sem tenant ativo', detail: 'Selecione/ative um tenant primeiro.', life: 2500 })
|
||||
return
|
||||
}
|
||||
|
||||
savingKey.value = key
|
||||
try {
|
||||
const next = !tf.isEnabled(key)
|
||||
await tf.setForTenant(tenantId.value, key, next)
|
||||
|
||||
toast.add({
|
||||
severity: 'success',
|
||||
summary: 'Atualizado',
|
||||
detail: `${labelOf(key)}: ${next ? 'Ativado' : 'Desativado'}`,
|
||||
life: 2500
|
||||
})
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao atualizar módulo', life: 3500 })
|
||||
} finally {
|
||||
savingKey.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function labelOf (key) {
|
||||
if (key === 'patients') return 'Pacientes'
|
||||
if (key === 'shared_reception') return 'Recepção / Secretária'
|
||||
if (key === 'rooms') return 'Salas / Coworking'
|
||||
if (key === 'intake_public') return 'Link externo de cadastro'
|
||||
return key
|
||||
}
|
||||
|
||||
async function applyPreset (preset) {
|
||||
if (!tenantId.value) return
|
||||
applyingPreset.value = true
|
||||
try {
|
||||
// Presets = sets mínimos (nada destrói dados; só liga/desliga acesso/UX)
|
||||
const map = {
|
||||
coworking: {
|
||||
patients: false,
|
||||
shared_reception: false,
|
||||
rooms: true,
|
||||
intake_public: false
|
||||
},
|
||||
reception: {
|
||||
patients: false,
|
||||
shared_reception: true,
|
||||
rooms: false,
|
||||
intake_public: false
|
||||
},
|
||||
full: {
|
||||
patients: true,
|
||||
shared_reception: true,
|
||||
rooms: true,
|
||||
intake_public: true
|
||||
}
|
||||
}
|
||||
|
||||
const cfg = map[preset]
|
||||
if (!cfg) return
|
||||
|
||||
// aplica sequencialmente (simples e previsível)
|
||||
for (const [k, v] of Object.entries(cfg)) {
|
||||
await tf.setForTenant(tenantId.value, k, v)
|
||||
}
|
||||
|
||||
toast.add({ severity: 'success', summary: 'Preset aplicado', detail: 'Configuração atualizada.', life: 2500 })
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao aplicar preset', life: 3500 })
|
||||
} finally {
|
||||
applyingPreset.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
if (!tenantStore.loaded && !tenantStore.loading) {
|
||||
await tenantStore.loadSessionAndTenant()
|
||||
}
|
||||
if (tenantId.value) {
|
||||
await tf.fetchForTenant(tenantId.value, { force: false })
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* Sub-componente local: linha de módulo
|
||||
* (mantive aqui pra você visualizar rápido sem criar pasta de components)
|
||||
*/
|
||||
const ModuleRow = {
|
||||
props: {
|
||||
title: String,
|
||||
desc: String,
|
||||
icon: String,
|
||||
enabled: Boolean,
|
||||
loading: Boolean
|
||||
},
|
||||
emits: ['toggle'],
|
||||
components: { ToggleButton },
|
||||
template: `
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-2">
|
||||
<i :class="icon" class="opacity-80" />
|
||||
<div class="text-base font-semibold">{{ title }}</div>
|
||||
</div>
|
||||
<div class="mt-1 text-sm opacity-80">{{ desc }}</div>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0">
|
||||
<ToggleButton
|
||||
:modelValue="enabled"
|
||||
onLabel="Ativo"
|
||||
offLabel="Inativo"
|
||||
:loading="loading"
|
||||
@update:modelValue="$emit('toggle')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
</script>
|
||||
@@ -2,15 +2,12 @@
|
||||
import FloatingConfigurator from '@/components/FloatingConfigurator.vue'
|
||||
import { useTenantStore } from '@/stores/tenantStore'
|
||||
|
||||
import { ref, onMounted, computed } from 'vue'
|
||||
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { supabase } from '../../../lib/supabase/client'
|
||||
|
||||
import InputText from 'primevue/inputtext'
|
||||
import Password from 'primevue/password'
|
||||
import Checkbox from 'primevue/checkbox'
|
||||
import Button from 'primevue/button'
|
||||
import Dialog from 'primevue/dialog'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
|
||||
// ✅ sessão (fonte de verdade p/ saas admin)
|
||||
@@ -33,6 +30,47 @@ const recoveryEmail = ref('')
|
||||
const loadingRecovery = ref(false)
|
||||
const recoverySent = ref(false)
|
||||
|
||||
// carrossel
|
||||
const slides = [
|
||||
{
|
||||
title: 'Gestão clínica simplificada',
|
||||
body: 'Agendamentos, prontuários e sessões em um único painel. Foco no que importa: seus pacientes.',
|
||||
icon: 'pi-calendar-clock',
|
||||
},
|
||||
{
|
||||
title: 'Múltiplos profissionais',
|
||||
body: 'Adicione terapeutas, gerencie vínculos e mantenha tudo organizado por clínica.',
|
||||
icon: 'pi-users',
|
||||
},
|
||||
{
|
||||
title: 'Agendamento online',
|
||||
body: 'Seus pacientes marcam sessões diretamente pelo portal, com confirmação automática.',
|
||||
icon: 'pi-globe',
|
||||
},
|
||||
{
|
||||
title: 'Seguro e privado',
|
||||
body: 'Dados protegidos com autenticação robusta e controle de acesso por perfil.',
|
||||
icon: 'pi-shield',
|
||||
},
|
||||
]
|
||||
|
||||
const currentSlide = ref(0)
|
||||
let slideInterval = null
|
||||
|
||||
function goToSlide (i) {
|
||||
currentSlide.value = i
|
||||
}
|
||||
|
||||
function startCarousel () {
|
||||
slideInterval = setInterval(() => {
|
||||
currentSlide.value = (currentSlide.value + 1) % slides.length
|
||||
}, 4500)
|
||||
}
|
||||
|
||||
function stopCarousel () {
|
||||
if (slideInterval) clearInterval(slideInterval)
|
||||
}
|
||||
|
||||
const canSubmit = computed(() => {
|
||||
return !!email.value?.trim() && !!password.value && !loading.value && !loadingRecovery.value
|
||||
})
|
||||
@@ -42,10 +80,11 @@ function isEmail (v) {
|
||||
}
|
||||
|
||||
function roleToPath (role) {
|
||||
// ✅ aceita os dois nomes (seu banco está devolvendo tenant_admin)
|
||||
if (role === 'clinic_admin' || role === 'tenant_admin' || role === 'admin') return '/admin'
|
||||
if (role === 'therapist') return '/therapist'
|
||||
if (role === 'patient') return '/portal'
|
||||
if (role === 'supervisor') return '/supervisor'
|
||||
if (role === 'portal_user' || role === 'patient') return '/portal'
|
||||
if (role === 'saas_admin') return '/saas'
|
||||
return '/'
|
||||
}
|
||||
|
||||
@@ -64,6 +103,14 @@ async function onSubmit () {
|
||||
loading.value = true
|
||||
|
||||
try {
|
||||
// 🔥 HARD RESET do contexto tenant ANTES de autenticar
|
||||
try { tenant.reset() } catch {}
|
||||
try {
|
||||
localStorage.removeItem('tenant_id')
|
||||
localStorage.removeItem('tenant')
|
||||
localStorage.removeItem('currentTenantId')
|
||||
} catch {}
|
||||
|
||||
const mail = String(email.value || '').trim()
|
||||
|
||||
const res = await supabase.auth.signInWithPassword({
|
||||
@@ -74,19 +121,14 @@ async function onSubmit () {
|
||||
if (res.error) throw res.error
|
||||
|
||||
// ✅ garante que sessionIsSaasAdmin esteja hidratado após login
|
||||
// (evita cair no fluxo de tenant quando o usuário é SaaS master)
|
||||
try {
|
||||
await initSession({ initial: false })
|
||||
} catch (e) {
|
||||
console.warn('[Login] initSession pós-login falhou:', e)
|
||||
// não aborta login por isso
|
||||
}
|
||||
|
||||
// lembrar e-mail (não senha)
|
||||
persistRememberedEmail()
|
||||
|
||||
// ✅ prioridade: redirect_after_login (se existir)
|
||||
// mas antes, se for SaaS admin, NÃO exigir tenant.
|
||||
const redirect = sessionStorage.getItem('redirect_after_login')
|
||||
if (sessionIsSaasAdmin.value) {
|
||||
if (redirect) {
|
||||
@@ -98,46 +140,94 @@ async function onSubmit () {
|
||||
return
|
||||
}
|
||||
|
||||
// ✅ agora que está autenticado, garante tenant pessoal (Modelo B)
|
||||
try {
|
||||
await supabase.rpc('ensure_personal_tenant')
|
||||
} catch (e) {
|
||||
console.warn('[Login] ensure_personal_tenant falhou:', e)
|
||||
// não aborta login por isso
|
||||
}
|
||||
// 🔥 identidade global (profiles.role) define área macro
|
||||
const { data: profile, error: pErr } = await supabase
|
||||
.from('profiles')
|
||||
.select('role')
|
||||
.eq('id', res.data.user.id)
|
||||
.single()
|
||||
|
||||
// ✅ fonte de verdade: tenant_members (rpc my_tenants)
|
||||
await tenant.loadSessionAndTenant()
|
||||
|
||||
console.log('[LOGIN] tenant.user', tenant.user)
|
||||
console.log('[LOGIN] memberships', tenant.memberships)
|
||||
console.log('[LOGIN] activeTenantId', tenant.activeTenantId)
|
||||
console.log('[LOGIN] activeRole', tenant.activeRole)
|
||||
if (pErr) throw pErr
|
||||
|
||||
if (!tenant.user) {
|
||||
authError.value = 'Não foi possível obter a sessão após login.'
|
||||
const globalRole = profile?.role || null
|
||||
if (!globalRole) {
|
||||
authError.value = 'Perfil não configurado corretamente.'
|
||||
return
|
||||
}
|
||||
|
||||
if (!tenant.activeRole) {
|
||||
authError.value = 'Sua conta não tem vínculo ativo com uma clínica (tenant_members).'
|
||||
await supabase.auth.signOut()
|
||||
return
|
||||
const safeRedirect = (path) => {
|
||||
const p = String(path || '')
|
||||
if (!p) return null
|
||||
if (globalRole === 'saas_admin') return (p === '/saas' || p.startsWith('/saas/')) ? p : '/saas'
|
||||
if (globalRole === 'portal_user') return (p === '/portal' || p.startsWith('/portal/')) ? p : '/portal'
|
||||
if (globalRole === 'tenant_member') {
|
||||
return (p.startsWith('/admin') || p.startsWith('/therapist') || p.startsWith('/supervisor')) ? p : null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
let tenantTarget = null
|
||||
|
||||
if (globalRole === 'tenant_member') {
|
||||
try {
|
||||
await supabase.rpc('ensure_personal_tenant')
|
||||
} catch (e) {
|
||||
console.warn('[Login] ensure_personal_tenant falhou:', e)
|
||||
}
|
||||
|
||||
await tenant.loadSessionAndTenant()
|
||||
|
||||
console.log('[LOGIN] tenant.user', tenant.user)
|
||||
console.log('[LOGIN] memberships', tenant.memberships)
|
||||
console.log('[LOGIN] activeTenantId', tenant.activeTenantId)
|
||||
console.log('[LOGIN] activeRole', tenant.activeRole)
|
||||
|
||||
if (!tenant.user) {
|
||||
authError.value = 'Não foi possível obter a sessão após login.'
|
||||
return
|
||||
}
|
||||
|
||||
if (!tenant.activeRole) {
|
||||
authError.value = 'Sua conta não tem vínculo ativo com uma clínica (tenant_members).'
|
||||
await supabase.auth.signOut()
|
||||
return
|
||||
}
|
||||
|
||||
tenantTarget = roleToPath(tenant.activeRole)
|
||||
} else {
|
||||
try {
|
||||
localStorage.removeItem('tenant_id')
|
||||
localStorage.removeItem('tenant')
|
||||
localStorage.removeItem('currentTenantId')
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// ✅ se havia redirect, vai pra ele
|
||||
if (redirect) {
|
||||
sessionStorage.removeItem('redirect_after_login')
|
||||
router.push(redirect)
|
||||
const sr = safeRedirect(redirect)
|
||||
|
||||
if (sr) {
|
||||
router.push(sr)
|
||||
return
|
||||
}
|
||||
if (globalRole === 'tenant_member' && tenantTarget) {
|
||||
router.push(tenantTarget)
|
||||
return
|
||||
}
|
||||
router.push(globalRole === 'portal_user' ? '/portal' : globalRole === 'saas_admin' ? '/saas' : '/')
|
||||
return
|
||||
}
|
||||
|
||||
const intended = sessionStorage.getItem('intended_area')
|
||||
sessionStorage.removeItem('intended_area')
|
||||
|
||||
const target = roleToPath(tenant.activeRole)
|
||||
let target = '/'
|
||||
|
||||
if (intended && intended !== tenant.activeRole) {
|
||||
if (globalRole === 'tenant_member') target = tenantTarget || '/therapist'
|
||||
else if (globalRole === 'portal_user') target = '/portal'
|
||||
else if (globalRole === 'saas_admin') target = '/saas'
|
||||
|
||||
if (intended && intended !== globalRole) {
|
||||
router.push(target)
|
||||
return
|
||||
}
|
||||
@@ -178,11 +268,9 @@ async function sendRecoveryEmail () {
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// legado: prefill via sessionStorage (mantive)
|
||||
const preEmail = sessionStorage.getItem('login_prefill_email')
|
||||
const prePass = sessionStorage.getItem('login_prefill_password')
|
||||
|
||||
// lembrar e-mail via localStorage (novo)
|
||||
let remembered = ''
|
||||
try {
|
||||
remembered = localStorage.getItem('remember_login_email') || ''
|
||||
@@ -197,287 +285,304 @@ onMounted(() => {
|
||||
|
||||
sessionStorage.removeItem('login_prefill_email')
|
||||
sessionStorage.removeItem('login_prefill_password')
|
||||
|
||||
startCarousel()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
stopCarousel()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<FloatingConfigurator />
|
||||
|
||||
<div class="relative min-h-screen w-full overflow-hidden bg-[var(--surface-ground)]">
|
||||
<!-- fundo conceitual -->
|
||||
<div class="pointer-events-none absolute inset-0">
|
||||
<!-- grid muito sutil -->
|
||||
<div class="min-h-screen w-full flex">
|
||||
|
||||
<!-- ===== ESQUERDA: CARROSSEL ===== -->
|
||||
<div class="hidden lg:flex lg:w-1/2 relative overflow-hidden flex-col">
|
||||
<!-- Fundo gradiente -->
|
||||
<div class="absolute inset-0 bg-gradient-to-br from-indigo-600 via-violet-600 to-purple-700" />
|
||||
|
||||
<!-- Grade decorativa -->
|
||||
<div
|
||||
class="absolute inset-0 opacity-70"
|
||||
style="
|
||||
background-image:
|
||||
linear-gradient(to right, rgba(255,255,255,.05) 1px, transparent 1px),
|
||||
linear-gradient(to bottom, rgba(255,255,255,.05) 1px, transparent 1px);
|
||||
background-size: 38px 38px;
|
||||
mask-image: radial-gradient(ellipse at 50% 20%, rgba(0,0,0,.95), transparent 70%);
|
||||
"
|
||||
class="absolute inset-0 opacity-[0.08]"
|
||||
style="background-image: linear-gradient(to right, white 1px, transparent 1px), linear-gradient(to bottom, white 1px, transparent 1px); background-size: 48px 48px;"
|
||||
/>
|
||||
<!-- halos -->
|
||||
<div class="absolute -top-28 -right-28 h-[26rem] w-[26rem] rounded-full blur-3xl bg-indigo-400/10" />
|
||||
<div class="absolute top-20 -left-28 h-[30rem] w-[30rem] rounded-full blur-3xl bg-emerald-400/10" />
|
||||
<div class="absolute -bottom-32 right-24 h-[26rem] w-[26rem] rounded-full blur-3xl bg-fuchsia-400/10" />
|
||||
</div>
|
||||
|
||||
<div class="relative grid min-h-screen place-items-center p-4 md:p-8">
|
||||
<div class="w-full max-w-5xl">
|
||||
<div class="relative overflow-hidden rounded-[2.75rem] border border-[var(--surface-border)] bg-[var(--surface-card)] shadow-2xl">
|
||||
<!-- header -->
|
||||
<div class="relative px-6 pt-7 pb-5 md:px-10 md:pt-10 md:pb-6">
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="grid h-12 w-12 place-items-center rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)]">
|
||||
<i class="pi pi-eye text-lg opacity-80" />
|
||||
</div>
|
||||
<!-- Orbs -->
|
||||
<div class="absolute -top-40 -left-40 h-[32rem] w-[32rem] rounded-full bg-white/10 blur-3xl pointer-events-none" />
|
||||
<div class="absolute bottom-0 right-0 h-80 w-80 rounded-full bg-violet-300/20 blur-3xl pointer-events-none" />
|
||||
<div class="absolute top-1/2 -right-20 h-64 w-64 rounded-full bg-indigo-300/10 blur-3xl pointer-events-none" />
|
||||
|
||||
<div class="min-w-0">
|
||||
<div class="text-2xl md:text-3xl font-semibold leading-tight text-[var(--text-color)]">
|
||||
Entrar
|
||||
</div>
|
||||
<div class="mt-1 text-sm md:text-base text-[var(--text-color-secondary)]">
|
||||
Acesso seguro ao seu painel.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Conteúdo -->
|
||||
<div class="relative z-10 flex flex-col h-full p-10 xl:p-14">
|
||||
|
||||
<div class="hidden md:flex items-center gap-2">
|
||||
<RouterLink
|
||||
to="/"
|
||||
class="inline-flex items-center gap-2 rounded-full border border-[var(--surface-border)] bg-[var(--surface-ground)] px-3 py-1 text-xs font-medium text-[var(--text-color-secondary)] hover:opacity-80"
|
||||
title="Atalho para a página de logins de desenvolvimento"
|
||||
>
|
||||
<i class="pi pi-code text-xs opacity-80" />
|
||||
Desenvolvedor Logins
|
||||
</RouterLink>
|
||||
|
||||
<RouterLink
|
||||
:to="{ name: 'resetPassword' }"
|
||||
class="inline-flex items-center gap-2 rounded-full border border-[var(--surface-border)] bg-[var(--surface-ground)] px-3 py-1 text-xs font-medium text-[var(--text-color-secondary)] hover:opacity-80"
|
||||
>
|
||||
<span class="h-1.5 w-1.5 rounded-full bg-emerald-400/70" />
|
||||
Trocar senha
|
||||
</RouterLink>
|
||||
</div>
|
||||
<div class="col-span-12 md:hidden">
|
||||
<RouterLink
|
||||
to="/"
|
||||
class="inline-flex w-full items-center justify-center gap-2 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] px-4 py-3 text-sm font-medium text-[var(--text-color-secondary)] hover:opacity-80"
|
||||
>
|
||||
<i class="pi pi-code opacity-80" />
|
||||
Desenvolvedor Logins
|
||||
</RouterLink>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- corpo -->
|
||||
<div class="relative px-6 pb-7 md:px-10 md:pb-10">
|
||||
<div class="grid grid-cols-12 gap-4 md:gap-6">
|
||||
<!-- FORM -->
|
||||
<div class="col-span-12 md:col-span-7">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] p-4 md:p-6">
|
||||
<form class="grid grid-cols-12 gap-4" @submit.prevent="onSubmit">
|
||||
<!-- email -->
|
||||
<div class="col-span-12">
|
||||
<label class="block text-sm font-semibold text-[var(--text-color)] mb-2">
|
||||
E-mail
|
||||
</label>
|
||||
<InputText
|
||||
v-model="email"
|
||||
class="w-full"
|
||||
placeholder="seuemail@dominio.com"
|
||||
autocomplete="email"
|
||||
:disabled="loading || loadingRecovery"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- senha -->
|
||||
<div class="col-span-12">
|
||||
<label class="block text-sm font-semibold text-[var(--text-color)] mb-2">
|
||||
Senha
|
||||
</label>
|
||||
<Password
|
||||
v-model="password"
|
||||
placeholder="Sua senha"
|
||||
toggleMask
|
||||
:feedback="false"
|
||||
class="w-full"
|
||||
inputClass="w-full"
|
||||
autocomplete="current-password"
|
||||
:disabled="loading || loadingRecovery"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- lembrar + esqueci -->
|
||||
<div class="col-span-12 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div class="flex items-center">
|
||||
<Checkbox
|
||||
v-model="checked"
|
||||
inputId="rememberme1"
|
||||
binary
|
||||
class="mr-2"
|
||||
:disabled="loading || loadingRecovery"
|
||||
/>
|
||||
<label for="rememberme1" class="text-sm text-[var(--text-color-secondary)]">
|
||||
Lembrar meu e-mail neste dispositivo
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="text-sm font-medium text-[var(--primary-color)] hover:opacity-80 text-left"
|
||||
:disabled="loading || loadingRecovery"
|
||||
@click="openForgot"
|
||||
>
|
||||
Esqueceu sua senha?
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- erro -->
|
||||
<div v-if="authError" class="col-span-12">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] px-4 py-3 text-sm text-red-500">
|
||||
<i class="pi pi-exclamation-triangle mr-2 opacity-80" />
|
||||
{{ authError }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- submit -->
|
||||
<div class="col-span-12">
|
||||
<Button
|
||||
type="submit"
|
||||
label="Entrar"
|
||||
class="w-full"
|
||||
icon="pi pi-sign-in"
|
||||
:loading="loading"
|
||||
:disabled="!canSubmit"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 text-xs text-[var(--text-color-secondary)]">
|
||||
Ao entrar, você será direcionado para sua área conforme seu perfil e vínculo com a clínica.
|
||||
</div>
|
||||
|
||||
<!-- detalhe minimalista -->
|
||||
<div class="col-span-12">
|
||||
<div class="h-px w-full bg-[var(--surface-border)] opacity-70" />
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 text-xs text-[var(--text-color-secondary)]">
|
||||
Se você estiver testando perfis e cair na mensagem de vínculo, é porque o acesso depende de <span class="font-semibold">tenant_members</span>.
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- LADO DIREITO: editorial / conceito -->
|
||||
<div class="col-span-12 md:col-span-5">
|
||||
<div class="h-full rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] p-4 md:p-6">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-sm font-semibold text-[var(--text-color)]">Acesso com lastro</div>
|
||||
<div class="mt-1 text-xs text-[var(--text-color-secondary)]">
|
||||
A sessão é validada e o vínculo com a clínica define sua área.
|
||||
</div>
|
||||
</div>
|
||||
<i class="pi pi-shield text-sm opacity-70" />
|
||||
</div>
|
||||
|
||||
<div class="mt-5 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] p-4">
|
||||
<div class="text-xs text-[var(--text-color-secondary)] leading-relaxed">
|
||||
<span class="font-semibold text-[var(--text-color)]">Como funciona:</span>
|
||||
você autentica, o sistema carrega seu tenant ativo e só então libera o painel correspondente.
|
||||
Isso evita acesso “solto” e organiza permissões no lugar certo.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul class="mt-5 space-y-2 text-xs text-[var(--text-color-secondary)]">
|
||||
<li class="flex gap-2">
|
||||
<span class="mt-1 h-1.5 w-1.5 rounded-full bg-emerald-400/70"></span>
|
||||
Recuperação de senha via link (e-mail).
|
||||
</li>
|
||||
<li class="flex gap-2">
|
||||
<span class="mt-1 h-1.5 w-1.5 rounded-full bg-indigo-400/70"></span>
|
||||
Se o link não chegar, cheque spam/lixo eletrônico.
|
||||
</li>
|
||||
<li class="flex gap-2">
|
||||
<span class="mt-1 h-1.5 w-1.5 rounded-full bg-fuchsia-400/70"></span>
|
||||
O redirecionamento depende da role ativa: admin/therapist/patient.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="mt-5 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 text-xs text-[var(--text-color-secondary)]">
|
||||
<i class="pi pi-info-circle mr-2 opacity-70" />
|
||||
Garanta que o Supabase tenha Redirect URLs incluindo
|
||||
<span class="font-semibold">/auth/reset-password</span>.
|
||||
</div>
|
||||
|
||||
<div class="mt-6 hidden md:flex items-center justify-between text-xs text-[var(--text-color-secondary)] opacity-80">
|
||||
<span class="inline-flex items-center gap-2">
|
||||
<span class="h-1.5 w-1.5 rounded-full bg-primary/60" />
|
||||
Agência Psi Quasar
|
||||
</span>
|
||||
<span class="opacity-80">Acesso clínico</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Dialog recovery -->
|
||||
<Dialog
|
||||
v-model:visible="openRecovery"
|
||||
modal
|
||||
header="Recuperar acesso"
|
||||
:draggable="false"
|
||||
:style="{ width: '28rem', maxWidth: '92vw' }"
|
||||
>
|
||||
<div class="space-y-3">
|
||||
<div class="text-sm text-[var(--text-color-secondary)]">
|
||||
Informe seu e-mail. Vamos enviar um link para redefinir sua senha.
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-semibold">E-mail</label>
|
||||
<InputText
|
||||
v-model="recoveryEmail"
|
||||
class="w-full"
|
||||
placeholder="seuemail@dominio.com"
|
||||
:disabled="loadingRecovery"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:justify-end pt-2">
|
||||
<Button
|
||||
label="Cancelar"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:disabled="loadingRecovery"
|
||||
@click="openRecovery = false"
|
||||
/>
|
||||
<Button
|
||||
label="Enviar link"
|
||||
icon="pi pi-envelope"
|
||||
:loading="loadingRecovery"
|
||||
@click="sendRecoveryEmail"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="recoverySent"
|
||||
class="rounded-xl border border-[var(--surface-border)] bg-[var(--surface-ground)] p-3 text-xs text-[var(--text-color-secondary)]"
|
||||
>
|
||||
<i class="pi pi-check mr-2 text-emerald-500"></i>
|
||||
Se o e-mail existir, você receberá o link em instantes. Verifique também spam/lixo eletrônico.
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
<!-- Brand -->
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="grid h-10 w-10 place-items-center rounded-xl bg-white/20 backdrop-blur-sm border border-white/20 shadow-lg">
|
||||
<i class="pi pi-heart-fill text-white text-sm" />
|
||||
</div>
|
||||
<span class="text-white font-bold text-lg tracking-tight">Agência PSI</span>
|
||||
</div>
|
||||
|
||||
<!-- Slides -->
|
||||
<div class="flex-1 flex flex-col justify-center">
|
||||
<Transition name="slide-fade" mode="out-in">
|
||||
<div :key="currentSlide" class="space-y-6">
|
||||
<div class="grid h-16 w-16 place-items-center rounded-2xl bg-white/15 backdrop-blur-sm border border-white/20 shadow-lg">
|
||||
<i :class="['pi', slides[currentSlide].icon, 'text-white text-2xl']" />
|
||||
</div>
|
||||
|
||||
<div class="space-y-4">
|
||||
<h2 class="text-3xl xl:text-4xl font-bold text-white leading-tight">
|
||||
{{ slides[currentSlide].title }}
|
||||
</h2>
|
||||
<p class="text-base xl:text-lg text-white/70 leading-relaxed max-w-sm">
|
||||
{{ slides[currentSlide].body }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</div>
|
||||
|
||||
<!-- Dots -->
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
v-for="(_, i) in slides"
|
||||
:key="i"
|
||||
class="transition-all duration-300 rounded-full focus:outline-none"
|
||||
:class="i === currentSlide ? 'w-7 h-2 bg-white shadow' : 'w-2 h-2 bg-white/35 hover:bg-white/60'"
|
||||
@click="goToSlide(i)"
|
||||
/>
|
||||
<span class="ml-3 text-xs text-white/40 tabular-nums">{{ currentSlide + 1 }}/{{ slides.length }}</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== DIREITA: FORMULÁRIO ===== -->
|
||||
<div class="flex-1 lg:w-1/2 flex flex-col min-h-screen bg-[var(--surface-ground)] overflow-y-auto relative">
|
||||
|
||||
<!-- Halos sutis de fundo -->
|
||||
<div class="pointer-events-none absolute inset-0">
|
||||
<div class="absolute top-10 right-10 h-64 w-64 rounded-full blur-3xl bg-indigo-400/5" />
|
||||
<div class="absolute bottom-10 left-10 h-56 w-56 rounded-full blur-3xl bg-violet-400/5" />
|
||||
</div>
|
||||
|
||||
<div class="relative flex flex-col flex-1 justify-center px-6 py-10 sm:px-10 lg:px-12 xl:px-16 w-full max-w-lg mx-auto">
|
||||
|
||||
<!-- Mobile: Brand -->
|
||||
<div class="flex lg:hidden items-center gap-2 mb-8">
|
||||
<div class="grid h-8 w-8 place-items-center rounded-lg bg-indigo-500/10 border border-indigo-500/20">
|
||||
<i class="pi pi-heart-fill text-indigo-500 text-xs" />
|
||||
</div>
|
||||
<span class="text-[var(--text-color)] font-bold text-base tracking-tight">Agência PSI</span>
|
||||
</div>
|
||||
|
||||
<!-- Cabeçalho -->
|
||||
<div class="mb-7">
|
||||
<h1 class="text-3xl font-bold text-[var(--text-color)] leading-tight">Bem-vindo de volta</h1>
|
||||
<p class="mt-1.5 text-sm text-[var(--text-color-secondary)]">Entre com sua conta para continuar</p>
|
||||
</div>
|
||||
|
||||
<!-- Login social (marcação — em breve) -->
|
||||
<div class="grid grid-cols-2 gap-3 mb-5">
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
title="Em breve"
|
||||
class="flex items-center justify-center gap-2 rounded-xl border border-[var(--surface-border)] bg-[var(--surface-card)] px-4 py-2.5 text-sm font-medium text-[var(--text-color-secondary)] opacity-50 cursor-not-allowed"
|
||||
>
|
||||
<svg class="h-4 w-4 flex-shrink-0" viewBox="0 0 24 24">
|
||||
<path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
|
||||
<path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
|
||||
<path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
|
||||
<path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
|
||||
</svg>
|
||||
Google
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
title="Em breve"
|
||||
class="flex items-center justify-center gap-2 rounded-xl border border-[var(--surface-border)] bg-[var(--surface-card)] px-4 py-2.5 text-sm font-medium text-[var(--text-color-secondary)] opacity-50 cursor-not-allowed"
|
||||
>
|
||||
<svg class="h-4 w-4 flex-shrink-0" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.8-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"/>
|
||||
</svg>
|
||||
Apple
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Divisor -->
|
||||
<div class="flex items-center gap-3 mb-5">
|
||||
<div class="h-px flex-1 bg-[var(--surface-border)]" />
|
||||
<span class="text-xs text-[var(--text-color-secondary)] font-medium whitespace-nowrap">ou continue com e-mail</span>
|
||||
<div class="h-px flex-1 bg-[var(--surface-border)]" />
|
||||
</div>
|
||||
|
||||
<!-- Formulário -->
|
||||
<form class="space-y-4" @submit.prevent="onSubmit">
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-semibold text-[var(--text-color)] mb-1.5">E-mail</label>
|
||||
<InputText
|
||||
v-model="email"
|
||||
class="w-full"
|
||||
placeholder="seuemail@dominio.com"
|
||||
autocomplete="email"
|
||||
:disabled="loading || loadingRecovery"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-semibold text-[var(--text-color)] mb-1.5">Senha</label>
|
||||
<Password
|
||||
v-model="password"
|
||||
placeholder="Sua senha"
|
||||
toggleMask
|
||||
:feedback="false"
|
||||
class="w-full"
|
||||
inputClass="w-full"
|
||||
autocomplete="current-password"
|
||||
:disabled="loading || loadingRecovery"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex items-center gap-2">
|
||||
<Checkbox
|
||||
v-model="checked"
|
||||
inputId="rememberme1"
|
||||
binary
|
||||
:disabled="loading || loadingRecovery"
|
||||
/>
|
||||
<label for="rememberme1" class="text-sm text-[var(--text-color-secondary)] cursor-pointer select-none">
|
||||
Lembrar e-mail
|
||||
</label>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="text-sm font-medium text-indigo-500 hover:text-indigo-600 transition-colors"
|
||||
:disabled="loading || loadingRecovery"
|
||||
@click="openForgot"
|
||||
>
|
||||
Esqueceu a senha?
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Erro -->
|
||||
<div
|
||||
v-if="authError"
|
||||
class="rounded-xl border border-red-200 bg-red-50 dark:border-red-900/30 dark:bg-red-950/20 px-4 py-3 text-sm text-red-600 dark:text-red-400 flex items-center gap-2"
|
||||
>
|
||||
<i class="pi pi-exclamation-triangle flex-shrink-0" />
|
||||
{{ authError }}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
label="Entrar"
|
||||
class="w-full"
|
||||
icon="pi pi-sign-in"
|
||||
:loading="loading"
|
||||
:disabled="!canSubmit"
|
||||
/>
|
||||
</form>
|
||||
|
||||
<!-- Rodapé -->
|
||||
<div class="mt-8 pt-6 border-t border-[var(--surface-border)] flex flex-wrap items-center justify-between gap-3 text-xs text-[var(--text-color-secondary)]">
|
||||
<RouterLink
|
||||
to="/"
|
||||
class="flex items-center gap-1.5 hover:text-[var(--text-color)] transition-colors"
|
||||
>
|
||||
<i class="pi pi-code text-[10px]" />
|
||||
Dev logins
|
||||
</RouterLink>
|
||||
|
||||
<RouterLink
|
||||
:to="{ name: 'resetPassword' }"
|
||||
class="flex items-center gap-1.5 hover:text-[var(--text-color)] transition-colors"
|
||||
>
|
||||
<span class="h-1.5 w-1.5 rounded-full bg-emerald-400 inline-block" />
|
||||
Trocar senha
|
||||
</RouterLink>
|
||||
|
||||
<span class="text-[var(--text-color-secondary)]/60">
|
||||
Agência PSI © {{ new Date().getFullYear() }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Dialog: Recuperar acesso -->
|
||||
<Dialog
|
||||
v-model:visible="openRecovery"
|
||||
modal
|
||||
header="Recuperar acesso"
|
||||
:draggable="false"
|
||||
:style="{ width: '28rem', maxWidth: '92vw' }"
|
||||
>
|
||||
<div class="space-y-3">
|
||||
<div class="text-sm text-[var(--text-color-secondary)]">
|
||||
Informe seu e-mail. Vamos enviar um link para redefinir sua senha.
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-semibold">E-mail</label>
|
||||
<InputText
|
||||
v-model="recoveryEmail"
|
||||
class="w-full"
|
||||
placeholder="seuemail@dominio.com"
|
||||
:disabled="loadingRecovery"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:justify-end pt-2">
|
||||
<Button
|
||||
label="Cancelar"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:disabled="loadingRecovery"
|
||||
@click="openRecovery = false"
|
||||
/>
|
||||
<Button
|
||||
label="Enviar link"
|
||||
icon="pi pi-envelope"
|
||||
:loading="loadingRecovery"
|
||||
@click="sendRecoveryEmail"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="recoverySent"
|
||||
class="rounded-xl border border-[var(--surface-border)] bg-[var(--surface-ground)] p-3 text-xs text-[var(--text-color-secondary)]"
|
||||
>
|
||||
<i class="pi pi-check mr-2 text-emerald-500" />
|
||||
Se o e-mail existir, você receberá o link em instantes. Verifique também spam/lixo eletrônico.
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.slide-fade-enter-active,
|
||||
.slide-fade-leave-active {
|
||||
transition: opacity 0.4s ease, transform 0.4s ease;
|
||||
}
|
||||
|
||||
.slide-fade-enter-from {
|
||||
opacity: 0;
|
||||
transform: translateY(18px);
|
||||
}
|
||||
|
||||
.slide-fade-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-12px);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,226 +1,110 @@
|
||||
<template>
|
||||
<div class="min-h-screen p-4 md:p-6 grid place-items-center">
|
||||
<div class="w-full max-w-lg">
|
||||
<Card class="overflow-hidden rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] shadow-sm">
|
||||
<template #title>
|
||||
<div class="relative">
|
||||
<!-- blobs sutis -->
|
||||
<div class="pointer-events-none absolute inset-0 opacity-90">
|
||||
<div class="absolute -top-20 -right-16 h-60 w-60 rounded-full bg-indigo-400/10 blur-3xl" />
|
||||
<div class="absolute top-10 -left-20 h-72 w-72 rounded-full bg-emerald-400/10 blur-3xl" />
|
||||
<div class="absolute -bottom-24 right-10 h-64 w-64 rounded-full bg-fuchsia-400/10 blur-3xl" />
|
||||
</div>
|
||||
|
||||
<div class="relative p-5 md:p-6">
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="grid h-10 w-10 place-items-center rounded-xl border border-[var(--surface-border)] bg-[var(--surface-ground)]"
|
||||
>
|
||||
<i class="pi pi-key text-lg opacity-80" />
|
||||
</div>
|
||||
|
||||
<div class="min-w-0">
|
||||
<div class="text-xl md:text-2xl font-semibold leading-tight">
|
||||
Redefinir senha
|
||||
</div>
|
||||
<div class="mt-1 text-sm text-[var(--text-color-secondary)]">
|
||||
Escolha uma nova senha para sua conta. Depois, você fará login novamente.
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="bannerText"
|
||||
class="mt-3 rounded-xl border border-[var(--surface-border)] bg-[var(--surface-ground)] px-3 py-2 text-xs text-[var(--text-color-secondary)]"
|
||||
>
|
||||
<i class="pi pi-info-circle mr-2 opacity-70" />
|
||||
{{ bannerText }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #content>
|
||||
<div class="p-5 md:p-6 pt-0">
|
||||
<div class="grid grid-cols-12 gap-4">
|
||||
<!-- Nova senha -->
|
||||
<div class="col-span-12">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] p-4">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-sm font-semibold">Nova senha</div>
|
||||
<div class="mt-1 text-xs text-[var(--text-color-secondary)]">
|
||||
Mínimo: 8 caracteres, maiúscula, minúscula e número.
|
||||
</div>
|
||||
</div>
|
||||
<i class="pi pi-lock text-sm opacity-70" />
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<Password
|
||||
v-model="newPassword"
|
||||
toggleMask
|
||||
:feedback="false"
|
||||
inputClass="w-full"
|
||||
:disabled="loading"
|
||||
placeholder="Crie uma nova senha"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-2 text-xs">
|
||||
<span v-if="!newPassword" class="text-[var(--text-color-secondary)]">
|
||||
Dica: use uma frase curta + número (ex.: “NoiteCalma7”).
|
||||
</span>
|
||||
<span v-else :class="strengthOk ? 'text-emerald-500' : 'text-yellow-500'">
|
||||
{{ strengthOk ? 'Senha forte o suficiente.' : 'Ainda está fraca — ajuste os critérios.' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Confirmar -->
|
||||
<div class="col-span-12">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] p-4">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-sm font-semibold">Confirmar nova senha</div>
|
||||
<div class="mt-1 text-xs text-[var(--text-color-secondary)]">
|
||||
Evita erro de digitação.
|
||||
</div>
|
||||
</div>
|
||||
<i class="pi pi-check-circle text-sm opacity-70" />
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<Password
|
||||
v-model="confirmPassword"
|
||||
toggleMask
|
||||
:feedback="false"
|
||||
inputClass="w-full"
|
||||
:disabled="loading"
|
||||
placeholder="Repita a nova senha"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-2 text-xs">
|
||||
<span v-if="!confirmPassword" class="text-[var(--text-color-secondary)]">
|
||||
Digite novamente para confirmar.
|
||||
</span>
|
||||
<span v-else :class="matchOk ? 'text-emerald-500' : 'text-yellow-500'">
|
||||
{{ matchOk ? 'Confere.' : 'Não confere com a nova senha.' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ações -->
|
||||
<div class="mt-5 flex flex-col gap-2">
|
||||
<Button
|
||||
class="w-full"
|
||||
label="Atualizar senha"
|
||||
icon="pi pi-check"
|
||||
:loading="loading"
|
||||
:disabled="loading"
|
||||
@click="submit"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="w-full rounded-xl border border-[var(--surface-border)] bg-[var(--surface-ground)] px-4 py-2.5 text-sm font-medium text-[var(--text-color-secondary)] hover:opacity-90"
|
||||
:disabled="loading"
|
||||
@click="goLogin"
|
||||
>
|
||||
Voltar para login
|
||||
</button>
|
||||
|
||||
<div class="mt-1 text-center text-xs text-[var(--text-color-secondary)]">
|
||||
Se você não solicitou essa redefinição, ignore o e-mail e faça logout em dispositivos desconhecidos.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import Card from 'primevue/card'
|
||||
import Password from 'primevue/password'
|
||||
import Button from 'primevue/button'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
import FloatingConfigurator from '@/components/FloatingConfigurator.vue'
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
import Password from 'primevue/password'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
|
||||
const toast = useToast()
|
||||
const router = useRouter()
|
||||
|
||||
const newPassword = ref('')
|
||||
const newPassword = ref('')
|
||||
const confirmPassword = ref('')
|
||||
const loading = ref(false)
|
||||
const bannerText = ref('')
|
||||
const loading = ref(false)
|
||||
const done = ref(false)
|
||||
|
||||
// estado do link de recovery
|
||||
const recoveryReady = ref(false)
|
||||
const linkInvalid = ref(false)
|
||||
|
||||
function isStrongEnough (p) {
|
||||
return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/.test(p || '')
|
||||
}
|
||||
|
||||
const strengthOk = computed(() => isStrongEnough(newPassword.value))
|
||||
const matchOk = computed(() => !!confirmPassword.value && newPassword.value === confirmPassword.value)
|
||||
const matchOk = computed(() => !!confirmPassword.value && newPassword.value === confirmPassword.value)
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
// 1) força leitura da sessão (supabase-js já captura hash automaticamente)
|
||||
const { data } = await supabase.auth.getSession()
|
||||
const canSubmit = computed(() =>
|
||||
recoveryReady.value && strengthOk.value && matchOk.value && !loading.value
|
||||
)
|
||||
|
||||
if (!data?.session) {
|
||||
bannerText.value =
|
||||
'Este link parece inválido ou expirado. Solicite um novo e-mail de redefinição.'
|
||||
} else {
|
||||
bannerText.value =
|
||||
'Link validado. Defina sua nova senha abaixo.'
|
||||
}
|
||||
|
||||
// 2) escuta evento específico de recovery
|
||||
const { data: listener } = supabase.auth.onAuthStateChange((event) => {
|
||||
if (event === 'PASSWORD_RECOVERY') {
|
||||
bannerText.value =
|
||||
'Link validado. Defina sua nova senha abaixo.'
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
listener?.subscription?.unsubscribe()
|
||||
}
|
||||
|
||||
} catch {
|
||||
bannerText.value =
|
||||
'Erro ao validar o link. Solicite um novo e-mail.'
|
||||
}
|
||||
// barra de força: 0–4
|
||||
const strengthScore = computed(() => {
|
||||
const p = newPassword.value
|
||||
if (!p) return 0
|
||||
let s = 0
|
||||
if (p.length >= 8) s++
|
||||
if (/[A-Z]/.test(p)) s++
|
||||
if (/[a-z]/.test(p)) s++
|
||||
if (/\d/.test(p)) s++
|
||||
return s
|
||||
})
|
||||
|
||||
const strengthLabel = computed(() => {
|
||||
if (!newPassword.value) return ''
|
||||
const labels = ['', 'Muito fraca', 'Fraca', 'Boa', 'Forte']
|
||||
return labels[strengthScore.value] || 'Forte'
|
||||
})
|
||||
|
||||
const strengthColor = computed(() => {
|
||||
const colors = ['', 'bg-red-500', 'bg-yellow-500', 'bg-blue-500', 'bg-emerald-500']
|
||||
return colors[strengthScore.value] || 'bg-emerald-500'
|
||||
})
|
||||
|
||||
let unsubscribeFn = null
|
||||
|
||||
async function syncRecoveryState () {
|
||||
try {
|
||||
const { data, error } = await supabase.auth.getSession()
|
||||
if (error) throw error
|
||||
if (data?.session) {
|
||||
recoveryReady.value = true
|
||||
} else {
|
||||
linkInvalid.value = true
|
||||
}
|
||||
} catch {
|
||||
linkInvalid.value = true
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await syncRecoveryState()
|
||||
|
||||
const { data: listener } = supabase.auth.onAuthStateChange((event) => {
|
||||
if (event === 'PASSWORD_RECOVERY' || event === 'SIGNED_IN') {
|
||||
recoveryReady.value = true
|
||||
linkInvalid.value = false
|
||||
}
|
||||
if (event === 'SIGNED_OUT') {
|
||||
recoveryReady.value = false
|
||||
}
|
||||
})
|
||||
|
||||
unsubscribeFn = () => listener?.subscription?.unsubscribe()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
try { unsubscribeFn?.() } catch {}
|
||||
})
|
||||
|
||||
function goLogin () {
|
||||
router.replace('/auth/login')
|
||||
}
|
||||
|
||||
async function submit () {
|
||||
if (!newPassword.value || !confirmPassword.value) {
|
||||
toast.add({ severity: 'warn', summary: 'Campos', detail: 'Preencha todos os campos.', life: 3000 })
|
||||
if (!recoveryReady.value) {
|
||||
toast.add({ severity: 'warn', summary: 'Link inválido', detail: 'Solicite um novo e-mail de redefinição.', life: 3500 })
|
||||
return
|
||||
}
|
||||
if (newPassword.value !== confirmPassword.value) {
|
||||
toast.add({ severity: 'warn', summary: 'Confirmação', detail: 'A confirmação não confere.', life: 3000 })
|
||||
if (!matchOk.value) {
|
||||
toast.add({ severity: 'warn', summary: 'Confirmação', detail: 'As senhas não conferem.', life: 3000 })
|
||||
return
|
||||
}
|
||||
if (!isStrongEnough(newPassword.value)) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Senha fraca',
|
||||
detail: 'Use no mínimo 8 caracteres com maiúscula, minúscula e número.',
|
||||
life: 4500
|
||||
})
|
||||
if (!strengthOk.value) {
|
||||
toast.add({ severity: 'warn', summary: 'Senha fraca', detail: 'Use no mínimo 8 caracteres com maiúscula, minúscula e número.', life: 4000 })
|
||||
return
|
||||
}
|
||||
|
||||
@@ -229,25 +113,254 @@ async function submit () {
|
||||
const { error } = await supabase.auth.updateUser({ password: newPassword.value })
|
||||
if (error) throw error
|
||||
|
||||
toast.add({
|
||||
severity: 'success',
|
||||
summary: 'Pronto',
|
||||
detail: 'Senha redefinida. Faça login novamente.',
|
||||
life: 3500
|
||||
})
|
||||
|
||||
// encerra sessão do recovery
|
||||
await supabase.auth.signOut()
|
||||
router.replace('/auth/login')
|
||||
done.value = true
|
||||
try { await supabase.auth.signOut({ scope: 'global' }) } catch {}
|
||||
} catch (e) {
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: 'Erro',
|
||||
detail: e?.message || 'Não foi possível redefinir a senha.',
|
||||
life: 4500
|
||||
})
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Não foi possível redefinir a senha.', life: 4500 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<FloatingConfigurator />
|
||||
|
||||
<div class="min-h-screen w-full flex">
|
||||
|
||||
<!-- ===== ESQUERDA: Painel de segurança ===== -->
|
||||
<div class="hidden lg:flex lg:w-1/2 relative overflow-hidden flex-col">
|
||||
<!-- Fundo gradiente -->
|
||||
<div class="absolute inset-0 bg-gradient-to-br from-indigo-600 via-violet-600 to-purple-700" />
|
||||
|
||||
<!-- Grade decorativa -->
|
||||
<div
|
||||
class="absolute inset-0 opacity-[0.08]"
|
||||
style="background-image: linear-gradient(to right, white 1px, transparent 1px), linear-gradient(to bottom, white 1px, transparent 1px); background-size: 48px 48px;"
|
||||
/>
|
||||
|
||||
<!-- Orbs -->
|
||||
<div class="absolute -top-40 -left-40 h-[32rem] w-[32rem] rounded-full bg-white/10 blur-3xl pointer-events-none" />
|
||||
<div class="absolute bottom-0 right-0 h-80 w-80 rounded-full bg-violet-300/20 blur-3xl pointer-events-none" />
|
||||
|
||||
<div class="relative z-10 flex flex-col h-full p-10 xl:p-14">
|
||||
|
||||
<!-- Brand -->
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="grid h-10 w-10 place-items-center rounded-xl bg-white/20 backdrop-blur-sm border border-white/20 shadow-lg">
|
||||
<i class="pi pi-heart-fill text-white text-sm" />
|
||||
</div>
|
||||
<span class="text-white font-bold text-lg tracking-tight">Agência PSI</span>
|
||||
</div>
|
||||
|
||||
<!-- Conteúdo central -->
|
||||
<div class="flex-1 flex flex-col justify-center space-y-8">
|
||||
<div class="grid h-16 w-16 place-items-center rounded-2xl bg-white/15 backdrop-blur-sm border border-white/20 shadow-lg">
|
||||
<i class="pi pi-lock text-white text-2xl" />
|
||||
</div>
|
||||
|
||||
<div class="space-y-3">
|
||||
<h2 class="text-3xl xl:text-4xl font-bold text-white leading-tight">
|
||||
Crie uma senha<br>que você não vai<br>esquecer.
|
||||
</h2>
|
||||
<p class="text-base text-white/70 leading-relaxed max-w-sm">
|
||||
Escolha algo único e seguro. Uma boa senha protege seus dados e os de seus pacientes.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Dicas -->
|
||||
<ul class="space-y-3">
|
||||
<li class="flex items-start gap-3 text-sm text-white/70">
|
||||
<span class="mt-1 h-1.5 w-1.5 rounded-full bg-emerald-400 flex-shrink-0" />
|
||||
Mínimo de 8 caracteres
|
||||
</li>
|
||||
<li class="flex items-start gap-3 text-sm text-white/70">
|
||||
<span class="mt-1 h-1.5 w-1.5 rounded-full bg-indigo-300 flex-shrink-0" />
|
||||
Combine letras maiúsculas, minúsculas e números
|
||||
</li>
|
||||
<li class="flex items-start gap-3 text-sm text-white/70">
|
||||
<span class="mt-1 h-1.5 w-1.5 rounded-full bg-fuchsia-300 flex-shrink-0" />
|
||||
Não reutilize a mesma senha de outros serviços
|
||||
</li>
|
||||
<li class="flex items-start gap-3 text-sm text-white/70">
|
||||
<span class="mt-1 h-1.5 w-1.5 rounded-full bg-amber-300 flex-shrink-0" />
|
||||
Exemplo seguro: <span class="font-semibold text-white/90">"Noite#Calma7"</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<!-- Rodapé esquerdo -->
|
||||
<div class="flex items-center justify-between text-xs text-white/40">
|
||||
<span>Agência PSI</span>
|
||||
<span>Acesso seguro</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== DIREITA: Formulário ===== -->
|
||||
<div class="flex-1 lg:w-1/2 flex flex-col min-h-screen bg-[var(--surface-ground)] overflow-y-auto relative">
|
||||
|
||||
<!-- Halos sutis -->
|
||||
<div class="pointer-events-none absolute inset-0">
|
||||
<div class="absolute top-10 right-10 h-64 w-64 rounded-full blur-3xl bg-indigo-400/5" />
|
||||
<div class="absolute bottom-10 left-10 h-56 w-56 rounded-full blur-3xl bg-violet-400/5" />
|
||||
</div>
|
||||
|
||||
<div class="relative flex flex-col flex-1 justify-center px-6 py-10 sm:px-10 lg:px-12 xl:px-16 w-full max-w-lg mx-auto">
|
||||
|
||||
<!-- Mobile: Brand -->
|
||||
<div class="flex lg:hidden items-center gap-2 mb-8">
|
||||
<div class="grid h-8 w-8 place-items-center rounded-lg bg-indigo-500/10 border border-indigo-500/20">
|
||||
<i class="pi pi-heart-fill text-indigo-500 text-xs" />
|
||||
</div>
|
||||
<span class="text-[var(--text-color)] font-bold text-base tracking-tight">Agência PSI</span>
|
||||
</div>
|
||||
|
||||
<!-- ── Estado: SUCESSO ── -->
|
||||
<template v-if="done">
|
||||
<div class="text-center space-y-6">
|
||||
<div class="mx-auto grid h-20 w-20 place-items-center rounded-full bg-emerald-500/10 border border-emerald-500/20">
|
||||
<i class="pi pi-check text-emerald-500 text-3xl" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 class="text-2xl font-bold text-[var(--text-color)]">Senha redefinida!</h1>
|
||||
<p class="mt-2 text-sm text-[var(--text-color-secondary)] leading-relaxed">
|
||||
Sua senha foi atualizada com sucesso.<br>Faça login novamente para continuar.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
label="Ir para o login"
|
||||
icon="pi pi-sign-in"
|
||||
class="w-full"
|
||||
@click="goLogin"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- ── Estado: LINK INVÁLIDO ── -->
|
||||
<template v-else-if="linkInvalid">
|
||||
<div class="text-center space-y-6">
|
||||
<div class="mx-auto grid h-20 w-20 place-items-center rounded-full bg-red-500/10 border border-red-500/20">
|
||||
<i class="pi pi-times text-red-500 text-3xl" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 class="text-2xl font-bold text-[var(--text-color)]">Link inválido</h1>
|
||||
<p class="mt-2 text-sm text-[var(--text-color-secondary)] leading-relaxed">
|
||||
Este link expirou ou já foi utilizado.<br>Solicite um novo e-mail de redefinição.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
label="Voltar para o login"
|
||||
icon="pi pi-arrow-left"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="w-full"
|
||||
@click="goLogin"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- ── Estado: FORMULÁRIO ── -->
|
||||
<template v-else>
|
||||
<!-- Cabeçalho -->
|
||||
<div class="mb-7">
|
||||
<h1 class="text-3xl font-bold text-[var(--text-color)] leading-tight">Redefinir senha</h1>
|
||||
<p class="mt-1.5 text-sm text-[var(--text-color-secondary)]">
|
||||
Escolha uma senha nova e segura para sua conta.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form class="space-y-5" @submit.prevent="submit">
|
||||
|
||||
<!-- Nova senha -->
|
||||
<div>
|
||||
<label class="block text-sm font-semibold text-[var(--text-color)] mb-1.5">Nova senha</label>
|
||||
<Password
|
||||
v-model="newPassword"
|
||||
placeholder="Mínimo 8 caracteres"
|
||||
toggleMask
|
||||
:feedback="false"
|
||||
class="w-full"
|
||||
inputClass="w-full"
|
||||
:disabled="loading"
|
||||
/>
|
||||
|
||||
<!-- Barra de força -->
|
||||
<div v-if="newPassword" class="mt-2 space-y-1">
|
||||
<div class="flex gap-1">
|
||||
<div
|
||||
v-for="i in 4"
|
||||
:key="i"
|
||||
class="h-1 flex-1 rounded-full transition-all duration-300"
|
||||
:class="i <= strengthScore ? strengthColor : 'bg-[var(--surface-border)]'"
|
||||
/>
|
||||
</div>
|
||||
<span class="text-xs" :class="{
|
||||
'text-red-500': strengthScore === 1,
|
||||
'text-yellow-500': strengthScore === 2,
|
||||
'text-blue-500': strengthScore === 3,
|
||||
'text-emerald-500': strengthScore === 4,
|
||||
}">
|
||||
{{ strengthLabel }}
|
||||
</span>
|
||||
</div>
|
||||
<p v-else class="mt-1.5 text-xs text-[var(--text-color-secondary)]">
|
||||
Dica: combine letras, números e símbolos.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Confirmar senha -->
|
||||
<div>
|
||||
<label class="block text-sm font-semibold text-[var(--text-color)] mb-1.5">Confirmar senha</label>
|
||||
<Password
|
||||
v-model="confirmPassword"
|
||||
placeholder="Repita a nova senha"
|
||||
toggleMask
|
||||
:feedback="false"
|
||||
class="w-full"
|
||||
inputClass="w-full"
|
||||
:disabled="loading"
|
||||
/>
|
||||
<div v-if="confirmPassword" class="mt-1.5 flex items-center gap-1.5 text-xs"
|
||||
:class="matchOk ? 'text-emerald-500' : 'text-yellow-500'"
|
||||
>
|
||||
<i :class="matchOk ? 'pi pi-check' : 'pi pi-times'" />
|
||||
{{ matchOk ? 'As senhas conferem.' : 'As senhas não conferem.' }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Botão -->
|
||||
<Button
|
||||
type="submit"
|
||||
label="Atualizar senha"
|
||||
icon="pi pi-check"
|
||||
class="w-full"
|
||||
:loading="loading"
|
||||
:disabled="!canSubmit"
|
||||
/>
|
||||
|
||||
</form>
|
||||
|
||||
<!-- Rodapé -->
|
||||
<div class="mt-8 pt-6 border-t border-[var(--surface-border)]">
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-2 text-sm text-[var(--text-color-secondary)] hover:text-[var(--text-color)] transition-colors"
|
||||
@click="goLogin"
|
||||
>
|
||||
<i class="pi pi-arrow-left text-xs" />
|
||||
Voltar para o login
|
||||
</button>
|
||||
|
||||
<p class="mt-4 text-xs text-[var(--text-color-secondary)] leading-relaxed">
|
||||
Se você não solicitou essa redefinição, ignore o e-mail e certifique-se de que sua conta está segura.
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,370 +1,142 @@
|
||||
<template>
|
||||
<div class="min-h-[calc(100vh-8rem)] p-4 md:p-6">
|
||||
<div class="mx-auto w-full max-w-4xl">
|
||||
<Card class="overflow-hidden rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] shadow-sm">
|
||||
<template #title>
|
||||
<div class="relative">
|
||||
<!-- blobs sutis -->
|
||||
<div class="pointer-events-none absolute inset-0 opacity-90">
|
||||
<div class="absolute -top-20 -right-16 h-60 w-60 rounded-full bg-indigo-400/10 blur-3xl" />
|
||||
<div class="absolute top-6 -left-20 h-72 w-72 rounded-full bg-emerald-400/10 blur-3xl" />
|
||||
<div class="absolute -bottom-24 right-10 h-64 w-64 rounded-full bg-fuchsia-400/10 blur-3xl" />
|
||||
</div>
|
||||
|
||||
<div class="relative flex flex-col gap-2 p-5 md:p-6">
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-3">
|
||||
<div
|
||||
class="grid h-10 w-10 place-items-center rounded-xl border border-[var(--surface-border)] bg-[var(--surface-ground)]"
|
||||
>
|
||||
<i class="pi pi-shield text-lg opacity-80" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="text-xl md:text-2xl font-semibold leading-tight">
|
||||
Segurança
|
||||
</div>
|
||||
<div class="mt-0.5 text-sm md:text-base text-[var(--text-color-secondary)]">
|
||||
Troque sua senha com cuidado. Depois, você será deslogado por segurança.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hidden md:flex items-center gap-2">
|
||||
<span
|
||||
class="inline-flex items-center gap-2 rounded-full border border-[var(--surface-border)] bg-[var(--surface-ground)] px-3 py-1 text-xs text-[var(--text-color-secondary)]"
|
||||
>
|
||||
<span class="h-1.5 w-1.5 rounded-full bg-emerald-400/70" />
|
||||
sessão ativa
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #content>
|
||||
<div class="p-5 md:p-6 pt-0">
|
||||
<!-- GRID -->
|
||||
<div class="grid grid-cols-12 gap-4">
|
||||
<!-- Senha atual -->
|
||||
<div class="col-span-12 md:col-span-6">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] p-4">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-sm font-semibold">Senha atual</div>
|
||||
<div class="mt-1 text-xs text-[var(--text-color-secondary)]">
|
||||
Necessária para confirmar que é você.
|
||||
</div>
|
||||
</div>
|
||||
<i class="pi pi-lock text-sm opacity-70" />
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<Password
|
||||
v-model="currentPassword"
|
||||
toggleMask
|
||||
:feedback="false"
|
||||
inputClass="w-full"
|
||||
:disabled="loading || loadingReset"
|
||||
placeholder="Digite sua senha atual"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Dica lateral -->
|
||||
<div class="col-span-12 md:col-span-6">
|
||||
<div class="h-full rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] p-4">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-sm font-semibold">Boas práticas</div>
|
||||
<div class="mt-1 text-xs text-[var(--text-color-secondary)]">
|
||||
Senhas fortes são menos “lembráveis”, mas mais seguras.
|
||||
</div>
|
||||
</div>
|
||||
<i class="pi pi-info-circle text-sm opacity-70" />
|
||||
</div>
|
||||
|
||||
<ul class="mt-3 space-y-2 text-xs text-[var(--text-color-secondary)]">
|
||||
<li class="flex gap-2">
|
||||
<span class="mt-1 h-1.5 w-1.5 rounded-full bg-indigo-400/70"></span>
|
||||
Use pelo menos 8 caracteres, com maiúscula, minúscula e número.
|
||||
</li>
|
||||
<li class="flex gap-2">
|
||||
<span class="mt-1 h-1.5 w-1.5 rounded-full bg-emerald-400/70"></span>
|
||||
Evite datas, nomes e padrões (1234, qwerty).
|
||||
</li>
|
||||
<li class="flex gap-2">
|
||||
<span class="mt-1 h-1.5 w-1.5 rounded-full bg-fuchsia-400/70"></span>
|
||||
Se estiver em computador público, finalize a sessão depois.
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Nova senha -->
|
||||
<div class="col-span-12 md:col-span-6">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] p-4">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-sm font-semibold">Nova senha</div>
|
||||
<div class="mt-1 text-xs text-[var(--text-color-secondary)]">
|
||||
Deve atender aos critérios mínimos.
|
||||
</div>
|
||||
</div>
|
||||
<i class="pi pi-key text-sm opacity-70" />
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<Password
|
||||
v-model="newPassword"
|
||||
toggleMask
|
||||
:feedback="false"
|
||||
inputClass="w-full"
|
||||
:disabled="loading || loadingReset"
|
||||
placeholder="Crie uma nova senha"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-2 text-xs">
|
||||
<span
|
||||
v-if="!newPassword"
|
||||
class="text-[var(--text-color-secondary)]"
|
||||
>
|
||||
Critérios: 8+ caracteres, maiúscula, minúscula e número.
|
||||
</span>
|
||||
<span
|
||||
v-else
|
||||
:class="passwordStrengthOk ? 'text-emerald-500' : 'text-yellow-500'"
|
||||
>
|
||||
{{ passwordStrengthOk ? 'Senha forte o suficiente.' : 'Ainda está fraca — ajuste os critérios.' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Confirmar -->
|
||||
<div class="col-span-12 md:col-span-6">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] p-4">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-sm font-semibold">Confirmar nova senha</div>
|
||||
<div class="mt-1 text-xs text-[var(--text-color-secondary)]">
|
||||
Evita erro de digitação.
|
||||
</div>
|
||||
</div>
|
||||
<i class="pi pi-check-circle text-sm opacity-70" />
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<Password
|
||||
v-model="confirmPassword"
|
||||
toggleMask
|
||||
:feedback="false"
|
||||
inputClass="w-full"
|
||||
:disabled="loading || loadingReset"
|
||||
placeholder="Repita a nova senha"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-2 text-xs">
|
||||
<span v-if="!confirmPassword" class="text-[var(--text-color-secondary)]">
|
||||
Digite novamente para confirmar.
|
||||
</span>
|
||||
<span
|
||||
v-else
|
||||
:class="passwordMatchOk ? 'text-emerald-500' : 'text-yellow-500'"
|
||||
>
|
||||
{{ passwordMatchOk ? 'Confere.' : 'Não confere com a nova senha.' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ações -->
|
||||
<div class="mt-5 flex flex-col-reverse gap-2 md:flex-row md:items-center md:justify-between">
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">
|
||||
Ao trocar sua senha, você será desconectado de forma global.
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:justify-end">
|
||||
<Button
|
||||
label="Esqueci minha senha"
|
||||
severity="secondary"
|
||||
outlined
|
||||
icon="pi pi-envelope"
|
||||
:loading="loadingReset"
|
||||
:disabled="loading || loadingReset"
|
||||
@click="sendResetEmail"
|
||||
/>
|
||||
<Button
|
||||
label="Trocar senha"
|
||||
icon="pi pi-check"
|
||||
:loading="loading"
|
||||
:disabled="loading || loadingReset"
|
||||
@click="changePassword"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue'
|
||||
import Card from 'primevue/card'
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
|
||||
|
||||
import Password from 'primevue/password'
|
||||
import Button from 'primevue/button'
|
||||
import Button from 'primevue/button'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
import { sessionUser, sessionRole } from '@/app/session'
|
||||
|
||||
const toast = useToast()
|
||||
|
||||
const currentPassword = ref('')
|
||||
const newPassword = ref('')
|
||||
const confirmPassword = ref('')
|
||||
const loading = ref(false)
|
||||
const loadingReset = ref(false)
|
||||
// ── Hero sticky ────────────────────────────────────────────
|
||||
const headerEl = ref(null)
|
||||
const headerSentinelRef = ref(null)
|
||||
const headerStuck = ref(false)
|
||||
let _observer = null
|
||||
|
||||
const currentPassword = ref('')
|
||||
const newPassword = ref('')
|
||||
const confirmPassword = ref('')
|
||||
const loading = ref(false)
|
||||
const loadingReset = ref(false)
|
||||
const done = ref(false)
|
||||
|
||||
// ── validações ────────────────────────────────────────────────────────────
|
||||
|
||||
function isStrongEnough (p) {
|
||||
return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/.test(p || '')
|
||||
}
|
||||
|
||||
const passwordStrengthOk = computed(() => isStrongEnough(newPassword.value))
|
||||
const passwordMatchOk = computed(() => !!confirmPassword.value && newPassword.value === confirmPassword.value)
|
||||
const strengthScore = computed(() => {
|
||||
const p = newPassword.value
|
||||
if (!p) return 0
|
||||
let s = 0
|
||||
if (p.length >= 8) s++
|
||||
if (/[A-Z]/.test(p)) s++
|
||||
if (/[a-z]/.test(p)) s++
|
||||
if (/\d/.test(p)) s++
|
||||
return s
|
||||
})
|
||||
|
||||
const strengthLabel = computed(() => {
|
||||
const labels = ['', 'Muito fraca', 'Fraca', 'Boa', 'Forte']
|
||||
return labels[strengthScore.value] || ''
|
||||
})
|
||||
|
||||
const strengthColor = computed(() => {
|
||||
const colors = ['', 'bg-red-500', 'bg-yellow-500', 'bg-blue-500', 'bg-emerald-500']
|
||||
return colors[strengthScore.value] || ''
|
||||
})
|
||||
|
||||
const strengthTextColor = computed(() => {
|
||||
const colors = ['', 'text-red-500', 'text-yellow-500', 'text-blue-500', 'text-emerald-500']
|
||||
return colors[strengthScore.value] || ''
|
||||
})
|
||||
|
||||
const strengthOk = computed(() => isStrongEnough(newPassword.value))
|
||||
const matchOk = computed(() => !!confirmPassword.value && newPassword.value === confirmPassword.value)
|
||||
|
||||
const canSubmit = computed(() =>
|
||||
!!currentPassword.value && strengthOk.value && matchOk.value && !loading.value && !loadingReset.value
|
||||
)
|
||||
|
||||
// ── ações ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function clearFields () {
|
||||
currentPassword.value = ''
|
||||
newPassword.value = ''
|
||||
newPassword.value = ''
|
||||
confirmPassword.value = ''
|
||||
}
|
||||
|
||||
async function hardLogout () {
|
||||
// 1) tenta logout normal (se falhar, seguimos)
|
||||
try { await supabase.auth.signOut({ scope: 'global' }) } catch {}
|
||||
try {
|
||||
// DEBUG LOGOUT
|
||||
console.log('ANTES', (await supabase.auth.getSession()).data.session)
|
||||
await supabase.auth.signOut({ scope: 'global' })
|
||||
console.log('DEPOIS', (await supabase.auth.getSession()).data.session)
|
||||
} catch (e) {
|
||||
console.warn('[signOut failed]', e)
|
||||
}
|
||||
|
||||
// 2) zera estado reativo global
|
||||
sessionUser.value = null
|
||||
sessionRole.value = null
|
||||
|
||||
// 3) remove token persistido do supabase-js v2 (sb-*-auth-token)
|
||||
try {
|
||||
const keysToRemove = []
|
||||
const keys = []
|
||||
for (let i = 0; i < localStorage.length; i++) {
|
||||
const k = localStorage.key(i)
|
||||
if (!k) continue
|
||||
if (k.startsWith('sb-') && k.includes('auth-token')) keysToRemove.push(k)
|
||||
if (k?.startsWith('sb-') && k.includes('auth-token')) keys.push(k)
|
||||
}
|
||||
keysToRemove.forEach((k) => localStorage.removeItem(k))
|
||||
} catch (e) {
|
||||
console.warn('[storage cleanup failed]', e)
|
||||
}
|
||||
|
||||
// 4) remove redirect pendente
|
||||
try {
|
||||
sessionStorage.removeItem('redirect_after_login')
|
||||
keys.forEach(k => localStorage.removeItem(k))
|
||||
} catch {}
|
||||
|
||||
// 5) redireciona de forma "hard"
|
||||
try { sessionStorage.removeItem('redirect_after_login') } catch {}
|
||||
window.location.replace('/auth/login')
|
||||
}
|
||||
|
||||
async function changePassword () {
|
||||
const user = sessionUser.value
|
||||
|
||||
if (!user?.email) {
|
||||
toast.add({ severity: 'error', summary: 'Sessão', detail: 'Usuário não encontrado na sessão.', life: 3500 })
|
||||
return
|
||||
}
|
||||
|
||||
if (!currentPassword.value || !newPassword.value || !confirmPassword.value) {
|
||||
toast.add({ severity: 'warn', summary: 'Campos', detail: 'Preencha todos os campos.', life: 3000 })
|
||||
return
|
||||
}
|
||||
|
||||
if (newPassword.value !== confirmPassword.value) {
|
||||
toast.add({ severity: 'warn', summary: 'Confirmação', detail: 'A confirmação não confere.', life: 3000 })
|
||||
return
|
||||
}
|
||||
|
||||
if (!isStrongEnough(newPassword.value)) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Senha fraca',
|
||||
detail: 'Use no mínimo 8 caracteres com maiúscula, minúscula e número.',
|
||||
life: 4500
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
// Reautentica (padrão mais previsível)
|
||||
const { error: signError } = await supabase.auth.signInWithPassword({
|
||||
email: user.email,
|
||||
password: currentPassword.value
|
||||
})
|
||||
if (signError) throw signError
|
||||
const { data: uData, error: uErr } = await supabase.auth.getUser()
|
||||
if (uErr) throw uErr
|
||||
|
||||
const { error: upError } = await supabase.auth.updateUser({
|
||||
password: newPassword.value
|
||||
})
|
||||
const email = uData?.user?.email
|
||||
if (!email) throw new Error('Sessão inválida. Faça login novamente.')
|
||||
|
||||
// reautentica para confirmar senha atual
|
||||
const { error: signError } = await supabase.auth.signInWithPassword({ email, password: currentPassword.value })
|
||||
if (signError) throw new Error('Senha atual incorreta.')
|
||||
|
||||
// atualiza
|
||||
const { error: upError } = await supabase.auth.updateUser({ password: newPassword.value })
|
||||
if (upError) throw upError
|
||||
|
||||
toast.add({
|
||||
severity: 'success',
|
||||
summary: 'Senha atualizada',
|
||||
detail: 'Por segurança, você será deslogado.',
|
||||
life: 2500
|
||||
})
|
||||
|
||||
clearFields()
|
||||
await hardLogout()
|
||||
done.value = true
|
||||
|
||||
toast.add({ severity: 'success', summary: 'Senha atualizada', detail: 'Por segurança, você será deslogado.', life: 2500 })
|
||||
setTimeout(() => hardLogout(), 2600)
|
||||
} catch (e) {
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: 'Erro',
|
||||
detail: e?.message || 'Não foi possível trocar a senha.',
|
||||
life: 4000
|
||||
})
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Não foi possível trocar a senha.', life: 4000 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function sendResetEmail () {
|
||||
const user = sessionUser.value
|
||||
if (!user?.email) {
|
||||
toast.add({ severity: 'error', summary: 'Sessão', detail: 'Usuário não encontrado na sessão.', life: 3500 })
|
||||
return
|
||||
}
|
||||
onMounted(() => {
|
||||
const rootMargin = `${document.querySelector('.l2-main') ? '0px' : '-56px'} 0px 0px 0px`
|
||||
_observer = new IntersectionObserver(
|
||||
([entry]) => { headerStuck.value = !entry.isIntersecting },
|
||||
{ threshold: 0, rootMargin }
|
||||
)
|
||||
if (headerSentinelRef.value) _observer.observe(headerSentinelRef.value)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => { _observer?.disconnect() })
|
||||
|
||||
async function sendResetEmail () {
|
||||
loadingReset.value = true
|
||||
try {
|
||||
const { data: uData, error: uErr } = await supabase.auth.getUser()
|
||||
if (uErr) throw uErr
|
||||
|
||||
const email = uData?.user?.email
|
||||
if (!email) throw new Error('Sessão inválida. Faça login novamente.')
|
||||
|
||||
const redirectTo = `${window.location.origin}/auth/reset-password`
|
||||
const { error } = await supabase.auth.resetPasswordForEmail(user.email, { redirectTo })
|
||||
const { error } = await supabase.auth.resetPasswordForEmail(email, { redirectTo })
|
||||
if (error) throw error
|
||||
|
||||
toast.add({
|
||||
severity: 'info',
|
||||
summary: 'E-mail enviado',
|
||||
detail: 'Verifique sua caixa de entrada para redefinir a senha.',
|
||||
life: 5000
|
||||
})
|
||||
toast.add({ severity: 'info', summary: 'E-mail enviado', detail: 'Verifique sua caixa de entrada para redefinir a senha.', life: 5000 })
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao enviar e-mail.', life: 4500 })
|
||||
} finally {
|
||||
@@ -372,3 +144,244 @@ async function sendResetEmail () {
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Toast />
|
||||
|
||||
<!-- Sentinel -->
|
||||
<div ref="headerSentinelRef" class="sec-sentinel" />
|
||||
|
||||
<!-- Hero sticky -->
|
||||
<div ref="headerEl" class="sec-hero w-full max-w-2xl mx-auto px-3 md:px-5 mb-4" :class="{ 'sec-hero--stuck': headerStuck }">
|
||||
<div class="sec-hero__blobs" aria-hidden="true">
|
||||
<div class="sec-hero__blob sec-hero__blob--1" />
|
||||
<div class="sec-hero__blob sec-hero__blob--2" />
|
||||
</div>
|
||||
|
||||
<div class="sec-hero__row1">
|
||||
<div class="sec-hero__brand">
|
||||
<div class="sec-hero__icon"><i class="pi pi-shield text-lg" /></div>
|
||||
<div class="min-w-0">
|
||||
<div class="sec-hero__title">Segurança</div>
|
||||
<div class="sec-hero__sub">Gerencie o acesso e a senha da sua conta</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<span class="hidden xl:inline-flex items-center gap-2 text-xs px-3 py-1.5 rounded-full border border-emerald-200 text-emerald-700 bg-emerald-50 shrink-0">
|
||||
<span class="h-2 w-2 rounded-full bg-emerald-500 animate-pulse" />
|
||||
Sessão ativa
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="px-3 md:px-5 pb-8 flex justify-center">
|
||||
<div class="w-full max-w-2xl space-y-4">
|
||||
|
||||
<!-- Card principal -->
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] overflow-hidden">
|
||||
|
||||
<!-- Seção: Trocar senha -->
|
||||
<div class="px-6 py-5 border-b border-[var(--surface-border)]">
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<p class="text-sm font-semibold text-[var(--text-color)]">Trocar senha</p>
|
||||
<p class="text-xs text-[var(--text-color-secondary)] mt-0.5">
|
||||
Confirme sua senha atual e defina uma nova.
|
||||
</p>
|
||||
</div>
|
||||
<span class="hidden sm:inline-flex items-center gap-1.5 rounded-full border border-[var(--surface-border)] bg-[var(--surface-ground)] px-3 py-1 text-xs text-[var(--text-color-secondary)]">
|
||||
<span class="h-1.5 w-1.5 rounded-full bg-emerald-400" />
|
||||
sessão ativa
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Estado: concluído -->
|
||||
<div v-if="done" class="px-6 py-10 text-center space-y-4">
|
||||
<div class="mx-auto grid h-16 w-16 place-items-center rounded-full bg-emerald-500/10 border border-emerald-500/20">
|
||||
<i class="pi pi-check text-emerald-500 text-2xl" />
|
||||
</div>
|
||||
<div>
|
||||
<p class="font-semibold text-[var(--text-color)]">Senha atualizada!</p>
|
||||
<p class="text-sm text-[var(--text-color-secondary)] mt-1">Redirecionando para o login…</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Estado: formulário -->
|
||||
<div v-else class="px-6 py-6 space-y-5">
|
||||
|
||||
<!-- Senha atual -->
|
||||
<div>
|
||||
<label class="block text-sm font-semibold text-[var(--text-color)] mb-1.5">
|
||||
Senha atual
|
||||
</label>
|
||||
<Password
|
||||
v-model="currentPassword"
|
||||
placeholder="Digite sua senha atual"
|
||||
toggleMask
|
||||
:feedback="false"
|
||||
class="w-full"
|
||||
inputClass="w-full"
|
||||
:disabled="loading || loadingReset"
|
||||
/>
|
||||
<p class="mt-1.5 text-xs text-[var(--text-color-secondary)]">
|
||||
Necessária para confirmar que é você.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="h-px bg-[var(--surface-border)]" />
|
||||
|
||||
<!-- Nova senha -->
|
||||
<div>
|
||||
<label class="block text-sm font-semibold text-[var(--text-color)] mb-1.5">
|
||||
Nova senha
|
||||
</label>
|
||||
<Password
|
||||
v-model="newPassword"
|
||||
placeholder="Mínimo 8 caracteres"
|
||||
toggleMask
|
||||
:feedback="false"
|
||||
class="w-full"
|
||||
inputClass="w-full"
|
||||
:disabled="loading || loadingReset"
|
||||
/>
|
||||
|
||||
<!-- Barra de força -->
|
||||
<div v-if="newPassword" class="mt-2 space-y-1">
|
||||
<div class="flex gap-1">
|
||||
<div
|
||||
v-for="i in 4"
|
||||
:key="i"
|
||||
class="h-1 flex-1 rounded-full transition-all duration-300"
|
||||
:class="i <= strengthScore ? strengthColor : 'bg-[var(--surface-border)]'"
|
||||
/>
|
||||
</div>
|
||||
<span class="text-xs" :class="strengthTextColor">{{ strengthLabel }}</span>
|
||||
</div>
|
||||
<p v-else class="mt-1.5 text-xs text-[var(--text-color-secondary)]">
|
||||
Critérios: 8+ caracteres, maiúscula, minúscula e número.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Confirmar senha -->
|
||||
<div>
|
||||
<label class="block text-sm font-semibold text-[var(--text-color)] mb-1.5">
|
||||
Confirmar nova senha
|
||||
</label>
|
||||
<Password
|
||||
v-model="confirmPassword"
|
||||
placeholder="Repita a nova senha"
|
||||
toggleMask
|
||||
:feedback="false"
|
||||
class="w-full"
|
||||
inputClass="w-full"
|
||||
:disabled="loading || loadingReset"
|
||||
/>
|
||||
<div v-if="confirmPassword" class="mt-1.5 flex items-center gap-1.5 text-xs"
|
||||
:class="matchOk ? 'text-emerald-500' : 'text-yellow-500'"
|
||||
>
|
||||
<i :class="matchOk ? 'pi pi-check' : 'pi pi-times'" />
|
||||
{{ matchOk ? 'As senhas conferem.' : 'As senhas não conferem.' }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Aviso -->
|
||||
<div class="rounded-xl border border-[var(--surface-border)] bg-[var(--surface-ground)] px-4 py-3 flex items-start gap-3">
|
||||
<i class="pi pi-info-circle text-[var(--text-color-secondary)] text-sm mt-0.5 flex-shrink-0" />
|
||||
<p class="text-xs text-[var(--text-color-secondary)] leading-relaxed">
|
||||
Ao trocar sua senha, você será desconectado de todos os dispositivos por segurança.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Ações -->
|
||||
<div class="flex flex-col-reverse gap-2 sm:flex-row sm:justify-between sm:items-center pt-1">
|
||||
<Button
|
||||
label="Enviar link por e-mail"
|
||||
severity="secondary"
|
||||
outlined
|
||||
icon="pi pi-envelope"
|
||||
:loading="loadingReset"
|
||||
:disabled="loading || loadingReset"
|
||||
@click="sendResetEmail"
|
||||
/>
|
||||
<Button
|
||||
label="Trocar senha"
|
||||
icon="pi pi-check"
|
||||
:loading="loading"
|
||||
:disabled="!canSubmit"
|
||||
@click="changePassword"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Card informativo: dicas -->
|
||||
<div class="mt-4 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] px-6 py-5">
|
||||
<div class="flex items-center gap-2 mb-3">
|
||||
<i class="pi pi-lightbulb text-sm text-[var(--text-color-secondary)]" />
|
||||
<span class="text-sm font-semibold text-[var(--text-color)]">Boas práticas</span>
|
||||
</div>
|
||||
<ul class="space-y-2">
|
||||
<li class="flex items-start gap-2.5 text-xs text-[var(--text-color-secondary)]">
|
||||
<span class="mt-1 h-1.5 w-1.5 rounded-full bg-indigo-400 flex-shrink-0" />
|
||||
Use pelo menos 8 caracteres com maiúscula, minúscula e número.
|
||||
</li>
|
||||
<li class="flex items-start gap-2.5 text-xs text-[var(--text-color-secondary)]">
|
||||
<span class="mt-1 h-1.5 w-1.5 rounded-full bg-emerald-400 flex-shrink-0" />
|
||||
Evite datas, nomes e sequências óbvias (1234, qwerty).
|
||||
</li>
|
||||
<li class="flex items-start gap-2.5 text-xs text-[var(--text-color-secondary)]">
|
||||
<span class="mt-1 h-1.5 w-1.5 rounded-full bg-fuchsia-400 flex-shrink-0" />
|
||||
Se estiver em computador compartilhado, encerre a sessão depois.
|
||||
</li>
|
||||
<li class="flex items-start gap-2.5 text-xs text-[var(--text-color-secondary)]">
|
||||
<span class="mt-1 h-1.5 w-1.5 rounded-full bg-amber-400 flex-shrink-0" />
|
||||
Não reutilize a mesma senha de outros serviços.
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.sec-sentinel { height: 1px; }
|
||||
|
||||
.sec-hero {
|
||||
position: sticky;
|
||||
top: var(--layout-sticky-top, 56px);
|
||||
z-index: 20;
|
||||
overflow: hidden;
|
||||
border-radius: 1.75rem;
|
||||
border: 1px solid var(--surface-border);
|
||||
background: var(--surface-card);
|
||||
padding: 1.25rem 1.5rem;
|
||||
}
|
||||
.sec-hero--stuck {
|
||||
border-top-left-radius: 0; border-top-right-radius: 0;
|
||||
}
|
||||
|
||||
.sec-hero__blobs { position: absolute; inset: 0; pointer-events: none; overflow: hidden; }
|
||||
.sec-hero__blob { position: absolute; border-radius: 50%; filter: blur(70px); }
|
||||
.sec-hero__blob--1 { width: 18rem; height: 18rem; top: -4rem; right: -3rem; background: rgba(99,102,241,0.10); }
|
||||
.sec-hero__blob--2 { width: 20rem; height: 20rem; top: 0.5rem; left: -5rem; background: rgba(16,185,129,0.08); }
|
||||
|
||||
.sec-hero__row1 {
|
||||
position: relative; z-index: 1;
|
||||
display: flex; align-items: center; gap: 1rem;
|
||||
}
|
||||
.sec-hero__brand {
|
||||
display: flex; align-items: center; gap: 0.75rem;
|
||||
flex: 1; min-width: 0;
|
||||
}
|
||||
.sec-hero__icon {
|
||||
display: grid; place-items: center;
|
||||
width: 2.5rem; height: 2.5rem; border-radius: 0.875rem; flex-shrink: 0;
|
||||
background: color-mix(in srgb, var(--p-primary-500, #6366f1) 12%, transparent);
|
||||
color: var(--p-primary-500, #6366f1);
|
||||
}
|
||||
.sec-hero__title { font-size: 1.1rem; font-weight: 700; letter-spacing: -0.02em; color: var(--text-color); }
|
||||
.sec-hero__sub { font-size: 0.78rem; color: var(--text-color-secondary); margin-top: 2px; }
|
||||
</style>
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
<!-- src/views/pages/auth/WelcomePage.vue -->
|
||||
<script setup>
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
|
||||
import Card from 'primevue/card'
|
||||
import Message from 'primevue/message'
|
||||
import Button from 'primevue/button'
|
||||
import Divider from 'primevue/divider'
|
||||
import Tag from 'primevue/tag'
|
||||
import Chip from 'primevue/chip'
|
||||
import ProgressSpinner from 'primevue/progressspinner'
|
||||
|
||||
@@ -20,7 +17,7 @@ const router = useRouter()
|
||||
const planFromQuery = computed(() => String(route.query.plan || '').trim().toLowerCase())
|
||||
const intervalFromQuery = computed(() => String(route.query.interval || '').trim().toLowerCase())
|
||||
|
||||
function normalizeInterval(v) {
|
||||
function normalizeInterval (v) {
|
||||
if (v === 'monthly') return 'month'
|
||||
if (v === 'annual' || v === 'yearly') return 'year'
|
||||
return v
|
||||
@@ -34,6 +31,22 @@ const intervalLabel = computed(() => {
|
||||
return ''
|
||||
})
|
||||
|
||||
const hasPlanQuery = computed(() => !!planFromQuery.value)
|
||||
|
||||
// ============================
|
||||
// Session (opcional para CTA melhor)
|
||||
// ============================
|
||||
const hasSession = ref(false)
|
||||
|
||||
async function checkSession () {
|
||||
try {
|
||||
const { data } = await supabase.auth.getSession()
|
||||
hasSession.value = !!data?.session
|
||||
} catch {
|
||||
hasSession.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ============================
|
||||
// Pricing
|
||||
// ============================
|
||||
@@ -43,29 +56,36 @@ const planRow = ref(null)
|
||||
const planName = computed(() => planRow.value?.public_name || planRow.value?.plan_name || null)
|
||||
const planDescription = computed(() => planRow.value?.public_description || null)
|
||||
|
||||
const amountCents = computed(() => {
|
||||
if (!planRow.value) return null
|
||||
return intervalNormalized.value === 'year'
|
||||
? planRow.value.yearly_cents
|
||||
: planRow.value.monthly_cents
|
||||
})
|
||||
function amountForInterval (row, interval) {
|
||||
if (!row) return null
|
||||
const cents = interval === 'year' ? row.yearly_cents : row.monthly_cents
|
||||
// fallback inteligente: se não houver preço nesse intervalo, tenta o outro
|
||||
if (cents == null) return interval === 'year' ? row.monthly_cents : row.yearly_cents
|
||||
return cents
|
||||
}
|
||||
|
||||
const currency = computed(() => {
|
||||
if (!planRow.value) return 'BRL'
|
||||
return intervalNormalized.value === 'year'
|
||||
? (planRow.value.yearly_currency || 'BRL')
|
||||
: (planRow.value.monthly_currency || 'BRL')
|
||||
})
|
||||
function currencyForInterval (row, interval) {
|
||||
if (!row) return 'BRL'
|
||||
const cur = interval === 'year' ? (row.yearly_currency || 'BRL') : (row.monthly_currency || 'BRL')
|
||||
return cur || 'BRL'
|
||||
}
|
||||
|
||||
const amountCents = computed(() => amountForInterval(planRow.value, intervalNormalized.value))
|
||||
const currency = computed(() => currencyForInterval(planRow.value, intervalNormalized.value))
|
||||
|
||||
const formattedPrice = computed(() => {
|
||||
if (amountCents.value == null) return null
|
||||
return new Intl.NumberFormat('pt-BR', {
|
||||
style: 'currency',
|
||||
currency: currency.value || 'BRL'
|
||||
}).format(amountCents.value / 100)
|
||||
try {
|
||||
return new Intl.NumberFormat('pt-BR', {
|
||||
style: 'currency',
|
||||
currency: currency.value || 'BRL'
|
||||
}).format(Number(amountCents.value) / 100)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
})
|
||||
|
||||
async function loadPlan() {
|
||||
async function loadPlan () {
|
||||
planRow.value = null
|
||||
if (!planFromQuery.value) return
|
||||
|
||||
@@ -99,16 +119,31 @@ async function loadPlan() {
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadPlan)
|
||||
watch(() => planFromQuery.value, () => loadPlan())
|
||||
|
||||
function goLogin() {
|
||||
function goLogin () {
|
||||
router.push('/auth/login')
|
||||
}
|
||||
|
||||
function goBackLanding() {
|
||||
function goBackLanding () {
|
||||
router.push('/lp')
|
||||
}
|
||||
|
||||
function goDashboard () {
|
||||
router.push('/admin')
|
||||
}
|
||||
|
||||
function goPricing () {
|
||||
router.push('/lp#pricing')
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await checkSession()
|
||||
await loadPlan()
|
||||
})
|
||||
|
||||
watch(
|
||||
() => planFromQuery.value,
|
||||
() => loadPlan()
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -123,7 +158,7 @@ function goBackLanding() {
|
||||
<div class="relative w-full max-w-6xl">
|
||||
<div class="rounded-3xl border border-[var(--surface-border)] bg-[var(--surface-card)] shadow-sm overflow-hidden">
|
||||
<div class="grid grid-cols-12">
|
||||
<!-- LEFT: boas-vindas (PrimeBlocks-like) -->
|
||||
<!-- LEFT -->
|
||||
<div
|
||||
class="col-span-12 lg:col-span-6 p-6 md:p-10 bg-[color-mix(in_srgb,var(--surface-card),transparent_6%)] border-b lg:border-b-0 lg:border-r border-[var(--surface-border)]"
|
||||
>
|
||||
@@ -145,8 +180,8 @@ function goBackLanding() {
|
||||
Bem-vindo(a).
|
||||
</div>
|
||||
|
||||
<div class="mt-3 text-sm md:text-base text-[var(--text-color-secondary)] max-w-lg">
|
||||
Sua conta foi criada e a sua intenção de assinatura foi registrada.
|
||||
<div class="mt-3 text-sm md:text-base text-[var(--text-color-secondary)] max-w-lg leading-relaxed">
|
||||
Sua conta foi criada e sua intenção de assinatura foi registrada.
|
||||
Agora o caminho é simples: instruções de pagamento → confirmação → ativação do plano.
|
||||
</div>
|
||||
|
||||
@@ -171,7 +206,9 @@ function goBackLanding() {
|
||||
<div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">3) Plano ativo</div>
|
||||
<div class="font-semibold mt-1">Recursos liberados</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">entitlements PRO quando pago</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">
|
||||
entitlements PRO quando confirmado
|
||||
</div>
|
||||
</div>
|
||||
<i class="pi pi-verified opacity-60" />
|
||||
</div>
|
||||
@@ -182,25 +219,25 @@ function goBackLanding() {
|
||||
<div class="mt-6 flex flex-wrap gap-2">
|
||||
<Tag severity="secondary" value="Sem cobrança automática" />
|
||||
<Tag severity="secondary" value="Ativação após confirmação" />
|
||||
<Tag severity="secondary" value="Fluxo pronto para gateway depois" />
|
||||
<Tag severity="secondary" value="Gateway depois, sem retrabalho" />
|
||||
</div>
|
||||
|
||||
<div class="mt-6 text-xs text-[var(--text-color-secondary)]">
|
||||
* Página de boas-vindas inspirada em layouts PrimeBlocks.
|
||||
* Boas-vindas inspirada em layouts PrimeBlocks.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- RIGHT: resumo + botões -->
|
||||
<!-- RIGHT -->
|
||||
<div class="col-span-12 lg:col-span-6 p-6 md:p-10">
|
||||
<div class="max-w-md mx-auto">
|
||||
<div class="text-2xl font-semibold">Conta criada 🎉</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1">
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1 leading-relaxed">
|
||||
Você já pode entrar. Se o seu plano for PRO, ele será ativado após confirmação do pagamento.
|
||||
</div>
|
||||
|
||||
<div class="mt-5">
|
||||
<Message severity="success" class="mb-3">
|
||||
Sua intenção de assinatura foi registrada.
|
||||
Intenção de assinatura registrada.
|
||||
</Message>
|
||||
|
||||
<div v-if="loading" class="flex items-center gap-2 text-sm text-[var(--text-color-secondary)]">
|
||||
@@ -208,13 +245,13 @@ function goBackLanding() {
|
||||
Carregando detalhes do plano…
|
||||
</div>
|
||||
|
||||
<Card v-else class="overflow-hidden">
|
||||
<Card v-else class="overflow-hidden rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">Resumo do plano</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">Resumo</div>
|
||||
|
||||
<div class="mt-1 flex items-center gap-2 flex-wrap">
|
||||
<div v-if="hasPlanQuery" class="mt-1 flex items-center gap-2 flex-wrap">
|
||||
<div class="text-lg font-semibold truncate">
|
||||
{{ planName || 'Plano' }}
|
||||
</div>
|
||||
@@ -223,18 +260,25 @@ function goBackLanding() {
|
||||
<Chip v-if="intervalLabel" :label="intervalLabel" />
|
||||
</div>
|
||||
|
||||
<div class="mt-2 text-2xl font-semibold leading-none">
|
||||
<div v-else class="mt-1">
|
||||
<div class="text-lg font-semibold">Sem plano selecionado</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1">
|
||||
Você pode escolher um plano agora ou seguir no FREE.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="hasPlanQuery" class="mt-2 text-2xl font-semibold leading-none">
|
||||
{{ formattedPrice || '—' }}
|
||||
<span v-if="intervalLabel" class="text-sm font-normal text-[var(--text-color-secondary)]">
|
||||
/{{ intervalNormalized === 'month' ? 'mês' : 'ano' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="planDescription" class="mt-2 text-sm text-[var(--text-color-secondary)]">
|
||||
<div v-if="planDescription" class="mt-2 text-sm text-[var(--text-color-secondary)] leading-relaxed">
|
||||
{{ planDescription }}
|
||||
</div>
|
||||
|
||||
<Message v-if="planFromQuery && !planRow" severity="warn" class="mt-3">
|
||||
<Message v-if="hasPlanQuery && !planRow" severity="warn" class="mt-3">
|
||||
Não encontrei esse plano na vitrine pública. Você pode continuar normalmente.
|
||||
</Message>
|
||||
</div>
|
||||
@@ -243,15 +287,40 @@ function goBackLanding() {
|
||||
<Divider class="my-4" />
|
||||
|
||||
<Message severity="info" class="mb-0">
|
||||
Próximo passo: você receberá instruções de pagamento (PIX ou boleto).
|
||||
Próximo passo: você receberá instruções de pagamento (PIX/boleto).
|
||||
Assim que confirmado, sua assinatura será ativada.
|
||||
</Message>
|
||||
|
||||
<div v-if="!hasPlanQuery" class="mt-3">
|
||||
<Button
|
||||
label="Escolher um plano"
|
||||
icon="pi pi-credit-card"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="w-full"
|
||||
@click="goPricing"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div class="mt-5 gap-2">
|
||||
<Button label="Ir para login" class="w-full mb-2" icon="pi pi-sign-in" @click="goLogin" />
|
||||
<Button
|
||||
v-if="hasSession"
|
||||
label="Ir para o painel"
|
||||
class="w-full mb-2"
|
||||
icon="pi pi-arrow-right"
|
||||
@click="goDashboard"
|
||||
/>
|
||||
<Button
|
||||
v-else
|
||||
label="Ir para login"
|
||||
class="w-full mb-2"
|
||||
icon="pi pi-sign-in"
|
||||
@click="goLogin"
|
||||
/>
|
||||
|
||||
<Button
|
||||
label="Voltar para a página inicial"
|
||||
severity="secondary"
|
||||
@@ -271,4 +340,4 @@ function goBackLanding() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
636
src/views/pages/billing/ClinicMeuPlanoPage.vue
Normal file
636
src/views/pages/billing/ClinicMeuPlanoPage.vue
Normal file
@@ -0,0 +1,636 @@
|
||||
<!-- src/views/pages/billing/ClinicMeuPlanoPage.vue -->
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
import { useTenantStore } from '@/stores/tenantStore'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const toast = useToast()
|
||||
const tenantStore = useTenantStore()
|
||||
|
||||
const loading = ref(false)
|
||||
|
||||
const subscription = ref(null)
|
||||
const plan = ref(null)
|
||||
const price = ref(null)
|
||||
|
||||
const features = ref([]) // [{ key, description }]
|
||||
const events = ref([]) // subscription_events
|
||||
|
||||
// ✅ para histórico auditável
|
||||
const plans = ref([]) // [{id,key,name}]
|
||||
const profiles = ref([]) // profiles de created_by
|
||||
|
||||
const tenantId = computed(() =>
|
||||
tenantStore.activeTenantId || tenantStore.tenantId || tenantStore.currentTenantId || null
|
||||
)
|
||||
|
||||
// -------------------------
|
||||
// helpers (format)
|
||||
// -------------------------
|
||||
function money (currency, amountCents) {
|
||||
if (amountCents == null) return null
|
||||
const value = Number(amountCents) / 100
|
||||
try {
|
||||
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: currency || 'BRL' }).format(value)
|
||||
} catch (_) {
|
||||
return `${value.toFixed(2)} ${currency || ''}`.trim()
|
||||
}
|
||||
}
|
||||
|
||||
function goUpgradeClinic () {
|
||||
// ✅ mantém caminho de retorno consistente
|
||||
const redirectTo = route?.fullPath || '/admin/meu-plano'
|
||||
router.push(`/upgrade?redirectTo=${encodeURIComponent(redirectTo)}`)
|
||||
}
|
||||
|
||||
function fmtDate (iso) {
|
||||
if (!iso) return '-'
|
||||
const d = new Date(iso)
|
||||
if (Number.isNaN(d.getTime())) return String(iso)
|
||||
return d.toLocaleString('pt-BR')
|
||||
}
|
||||
|
||||
function prettyMeta (meta) {
|
||||
if (!meta) return null
|
||||
try {
|
||||
if (typeof meta === 'string') return meta
|
||||
return JSON.stringify(meta, null, 2)
|
||||
} catch (_) {
|
||||
return String(meta)
|
||||
}
|
||||
}
|
||||
|
||||
function statusSeverity (st) {
|
||||
const s = String(st || '').toLowerCase()
|
||||
if (s === 'active') return 'success'
|
||||
if (s === 'trialing') return 'info'
|
||||
if (s === 'past_due') return 'warning'
|
||||
if (s === 'canceled' || s === 'cancelled') return 'danger'
|
||||
if (s === 'incomplete' || s === 'incomplete_expired' || s === 'unpaid') return 'warning'
|
||||
return 'secondary'
|
||||
}
|
||||
|
||||
function statusLabelPretty (st) {
|
||||
const s = String(st || '').toLowerCase()
|
||||
if (s === 'active') return 'Ativa'
|
||||
if (s === 'trialing') return 'Trial'
|
||||
if (s === 'past_due') return 'Pagamento pendente'
|
||||
if (s === 'canceled' || s === 'cancelled') return 'Cancelada'
|
||||
if (s === 'unpaid') return 'Não paga'
|
||||
if (s === 'incomplete') return 'Incompleta'
|
||||
if (s === 'incomplete_expired') return 'Incompleta (expirada)'
|
||||
return st || '-'
|
||||
}
|
||||
|
||||
function eventSeverity (t) {
|
||||
const k = String(t || '').toLowerCase()
|
||||
if (k === 'plan_changed') return 'info'
|
||||
if (k === 'canceled') return 'danger'
|
||||
if (k === 'reactivated') return 'success'
|
||||
if (k === 'created') return 'secondary'
|
||||
if (k === 'status_changed') return 'warning'
|
||||
return 'secondary'
|
||||
}
|
||||
|
||||
function eventLabel (t) {
|
||||
const k = String(t || '').toLowerCase()
|
||||
if (k === 'plan_changed') return 'Plano alterado'
|
||||
if (k === 'canceled') return 'Cancelada'
|
||||
if (k === 'reactivated') return 'Reativada'
|
||||
if (k === 'created') return 'Criada'
|
||||
if (k === 'status_changed') return 'Status alterado'
|
||||
return t || '-'
|
||||
}
|
||||
|
||||
// -------------------------
|
||||
// helpers (plans / profiles)
|
||||
// -------------------------
|
||||
const planById = computed(() => {
|
||||
const m = new Map()
|
||||
for (const p of plans.value || []) m.set(String(p.id), p)
|
||||
return m
|
||||
})
|
||||
|
||||
function planKeyOrName (planId) {
|
||||
if (!planId) return '—'
|
||||
const p = planById.value.get(String(planId))
|
||||
return p?.key || p?.name || String(planId)
|
||||
}
|
||||
|
||||
const profileById = computed(() => {
|
||||
const m = new Map()
|
||||
for (const p of profiles.value || []) m.set(String(p.id), p)
|
||||
return m
|
||||
})
|
||||
|
||||
function displayUser (userId) {
|
||||
if (!userId) return '—'
|
||||
const p = profileById.value.get(String(userId))
|
||||
if (!p) return String(userId)
|
||||
|
||||
const name = p.nome || p.name || p.full_name || p.display_name || p.username || null
|
||||
const email = p.email || p.email_principal || p.user_email || null
|
||||
|
||||
if (name && email) return `${name} <${email}>`
|
||||
if (name) return name
|
||||
if (email) return email
|
||||
return String(userId)
|
||||
}
|
||||
|
||||
// -------------------------
|
||||
// computed (header info)
|
||||
// -------------------------
|
||||
const planName = computed(() => plan.value?.name || subscription.value?.plan_key || '-')
|
||||
const statusLabel = computed(() => subscription.value?.status || '-')
|
||||
const statusLabelPrettyComputed = computed(() => statusLabelPretty(subscription.value?.status))
|
||||
|
||||
const intervalLabel = computed(() => {
|
||||
const i = subscription.value?.interval
|
||||
if (i === 'month') return 'mês'
|
||||
if (i === 'year') return 'ano'
|
||||
return i || '-'
|
||||
})
|
||||
|
||||
const priceLabel = computed(() => {
|
||||
if (!price.value) return null
|
||||
return `${money(price.value.currency, price.value.amount_cents)} / ${intervalLabel.value}`
|
||||
})
|
||||
|
||||
const periodLabel = computed(() => {
|
||||
const s = subscription.value
|
||||
if (!s?.current_period_start || !s?.current_period_end) return '-'
|
||||
return `${fmtDate(s.current_period_start)} → ${fmtDate(s.current_period_end)}`
|
||||
})
|
||||
|
||||
const cancelHint = computed(() => {
|
||||
const s = subscription.value
|
||||
if (!s) return null
|
||||
if (s.cancel_at_period_end) {
|
||||
const end = s.current_period_end ? fmtDate(s.current_period_end) : null
|
||||
return end ? `Cancelamento no fim do período (${end}).` : 'Cancelamento no fim do período.'
|
||||
}
|
||||
if (s.canceled_at) return `Cancelada em ${fmtDate(s.canceled_at)}.`
|
||||
return null
|
||||
})
|
||||
|
||||
// -------------------------
|
||||
// ✅ agrupamento de features por módulo (prefixo)
|
||||
// -------------------------
|
||||
function moduleFromKey (key) {
|
||||
const k = String(key || '').trim()
|
||||
if (!k) return 'Outros'
|
||||
|
||||
// tenta por "."
|
||||
if (k.includes('.')) {
|
||||
const head = k.split('.')[0]
|
||||
return head || 'Outros'
|
||||
}
|
||||
|
||||
// tenta por "_"
|
||||
if (k.includes('_')) {
|
||||
const head = k.split('_')[0]
|
||||
return head || 'Outros'
|
||||
}
|
||||
|
||||
return 'Outros'
|
||||
}
|
||||
|
||||
function moduleLabel (m) {
|
||||
const s = String(m || '').trim()
|
||||
if (!s) return 'Outros'
|
||||
return s.charAt(0).toUpperCase() + s.slice(1)
|
||||
}
|
||||
|
||||
const groupedFeatures = computed(() => {
|
||||
const list = features.value || []
|
||||
const map = new Map()
|
||||
|
||||
for (const f of list) {
|
||||
const mod = moduleFromKey(f.key)
|
||||
if (!map.has(mod)) map.set(mod, [])
|
||||
map.get(mod).push(f)
|
||||
}
|
||||
|
||||
// ordena módulos e itens
|
||||
const modules = Array.from(map.keys()).sort((a, b) => {
|
||||
if (a === 'Outros') return 1
|
||||
if (b === 'Outros') return -1
|
||||
return a.localeCompare(b)
|
||||
})
|
||||
|
||||
return modules.map(mod => {
|
||||
const items = map.get(mod) || []
|
||||
items.sort((a, b) => String(a.key || '').localeCompare(String(b.key || '')))
|
||||
return { module: mod, items }
|
||||
})
|
||||
})
|
||||
|
||||
// -------------------------
|
||||
// fetch
|
||||
// -------------------------
|
||||
async function fetchMeuPlanoClinic () {
|
||||
loading.value = true
|
||||
try {
|
||||
const tid = tenantId.value
|
||||
if (!tid) throw new Error('Tenant ativo não encontrado.')
|
||||
|
||||
// 1) assinatura do tenant (prioriza status "ativo" e afins; cai pro mais recente)
|
||||
// ✅ depois das mudanças: não assume só "active" (pode estar trialing/past_due etc.)
|
||||
const sRes = await supabase
|
||||
.from('subscriptions')
|
||||
.select('*')
|
||||
.eq('tenant_id', tid)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(10)
|
||||
|
||||
if (sRes.error) throw sRes.error
|
||||
|
||||
const list = sRes.data || []
|
||||
const priority = (st) => {
|
||||
const s = String(st || '').toLowerCase()
|
||||
if (s === 'active') return 1
|
||||
if (s === 'trialing') return 2
|
||||
if (s === 'past_due') return 3
|
||||
if (s === 'unpaid') return 4
|
||||
if (s === 'incomplete') return 5
|
||||
if (s === 'canceled' || s === 'cancelled') return 9
|
||||
return 8
|
||||
}
|
||||
|
||||
subscription.value = (list.slice().sort((a, b) => {
|
||||
const pa = priority(a?.status)
|
||||
const pb = priority(b?.status)
|
||||
if (pa !== pb) return pa - pb
|
||||
// empate: mais recente
|
||||
return new Date(b?.created_at || 0) - new Date(a?.created_at || 0)
|
||||
})[0]) || null
|
||||
|
||||
if (!subscription.value) {
|
||||
plan.value = null
|
||||
price.value = null
|
||||
features.value = []
|
||||
events.value = []
|
||||
plans.value = []
|
||||
profiles.value = []
|
||||
return
|
||||
}
|
||||
|
||||
// 2) plano (atual)
|
||||
if (subscription.value.plan_id) {
|
||||
const pRes = await supabase
|
||||
.from('plans')
|
||||
.select('id, key, name, description')
|
||||
.eq('id', subscription.value.plan_id)
|
||||
.maybeSingle()
|
||||
|
||||
if (pRes.error) throw pRes.error
|
||||
plan.value = pRes.data || null
|
||||
} else {
|
||||
plan.value = null
|
||||
}
|
||||
|
||||
// 3) preço vigente (intervalo atual)
|
||||
// ✅ robustez: tenta preço vigente por janela; se não achar, pega o último ativo do intervalo
|
||||
price.value = null
|
||||
if (subscription.value.plan_id && subscription.value.interval) {
|
||||
const nowIso = new Date().toISOString()
|
||||
|
||||
const ppRes = await supabase
|
||||
.from('plan_prices')
|
||||
.select('currency, interval, amount_cents, is_active, active_from, active_to')
|
||||
.eq('plan_id', subscription.value.plan_id)
|
||||
.eq('interval', subscription.value.interval)
|
||||
.eq('is_active', true)
|
||||
.lte('active_from', nowIso)
|
||||
.or(`active_to.is.null,active_to.gte.${nowIso}`)
|
||||
.order('active_from', { ascending: false })
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
|
||||
if (ppRes.error) throw ppRes.error
|
||||
price.value = ppRes.data || null
|
||||
|
||||
if (!price.value) {
|
||||
const ppFallback = await supabase
|
||||
.from('plan_prices')
|
||||
.select('currency, interval, amount_cents, is_active, active_from, active_to')
|
||||
.eq('plan_id', subscription.value.plan_id)
|
||||
.eq('interval', subscription.value.interval)
|
||||
.eq('is_active', true)
|
||||
.order('active_from', { ascending: false })
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
|
||||
if (ppFallback.error) throw ppFallback.error
|
||||
price.value = ppFallback.data || null
|
||||
}
|
||||
}
|
||||
|
||||
// 4) features do plano
|
||||
features.value = []
|
||||
if (subscription.value.plan_id) {
|
||||
const pfRes = await supabase
|
||||
.from('plan_features')
|
||||
.select('feature_id')
|
||||
.eq('plan_id', subscription.value.plan_id)
|
||||
|
||||
if (pfRes.error) throw pfRes.error
|
||||
|
||||
const featureIds = (pfRes.data || []).map(r => r.feature_id).filter(Boolean)
|
||||
if (featureIds.length) {
|
||||
const fRes = await supabase
|
||||
.from('features')
|
||||
.select('id, key, description, descricao')
|
||||
.in('id', featureIds)
|
||||
.order('key', { ascending: true })
|
||||
|
||||
if (fRes.error) throw fRes.error
|
||||
|
||||
features.value = (fRes.data || []).map(f => ({
|
||||
key: f.key,
|
||||
description: (f.descricao || f.description || '').trim()
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
// 5) histórico (50) — se existir subscription_id
|
||||
events.value = []
|
||||
if (subscription.value?.id) {
|
||||
const eRes = await supabase
|
||||
.from('subscription_events')
|
||||
.select('*')
|
||||
.eq('subscription_id', subscription.value.id)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(50)
|
||||
|
||||
if (eRes.error) throw eRes.error
|
||||
events.value = eRes.data || []
|
||||
}
|
||||
|
||||
// ✅ 6) pré-carrega planos citados em (old/new) + plano atual
|
||||
const planIds = new Set()
|
||||
if (subscription.value?.plan_id) planIds.add(String(subscription.value.plan_id))
|
||||
|
||||
for (const ev of events.value) {
|
||||
if (ev?.old_plan_id) planIds.add(String(ev.old_plan_id))
|
||||
if (ev?.new_plan_id) planIds.add(String(ev.new_plan_id))
|
||||
}
|
||||
|
||||
if (planIds.size) {
|
||||
const { data: pAll, error: epAll } = await supabase
|
||||
.from('plans')
|
||||
.select('id,key,name')
|
||||
.in('id', Array.from(planIds))
|
||||
|
||||
plans.value = epAll ? [] : (pAll || [])
|
||||
} else {
|
||||
plans.value = []
|
||||
}
|
||||
|
||||
// ✅ 7) perfis (created_by)
|
||||
const userIds = new Set()
|
||||
for (const ev of events.value) {
|
||||
const by = String(ev.created_by || '').trim()
|
||||
if (by) userIds.add(by)
|
||||
}
|
||||
|
||||
if (userIds.size) {
|
||||
const { data: pr, error: epr } = await supabase
|
||||
.from('profiles')
|
||||
.select('*')
|
||||
.in('id', Array.from(userIds))
|
||||
|
||||
profiles.value = epr ? [] : (pr || [])
|
||||
} else {
|
||||
profiles.value = []
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 5000 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(fetchMeuPlanoClinic)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="p-4 md:p-6">
|
||||
<Toast />
|
||||
|
||||
<!-- Topbar padrão -->
|
||||
<div class="mb-4 rounded-3xl border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 shadow-sm">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="flex flex-col">
|
||||
<div class="text-2xl font-semibold leading-none">Meu plano</div>
|
||||
<small class="text-color-secondary mt-1">
|
||||
Plano da clínica (tenant) e recursos habilitados.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2 flex-wrap justify-end">
|
||||
<Button
|
||||
label="Alterar plano"
|
||||
icon="pi pi-arrow-up-right"
|
||||
:loading="loading"
|
||||
@click="goUpgradeClinic"
|
||||
/>
|
||||
<Button
|
||||
label="Atualizar"
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:loading="loading"
|
||||
@click="fetchMeuPlanoClinic"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Card resumo -->
|
||||
<Card class="rounded-[2rem] overflow-hidden">
|
||||
<template #content>
|
||||
<div class="flex flex-wrap items-start justify-between gap-4">
|
||||
<div class="min-w-0">
|
||||
<div class="text-xl md:text-2xl font-semibold leading-tight">
|
||||
{{ planName }}
|
||||
</div>
|
||||
|
||||
<div class="text-sm text-color-secondary mt-1">
|
||||
<span v-if="priceLabel">{{ priceLabel }}</span>
|
||||
<span v-else>Preço não encontrado para este intervalo.</span>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
<Tag :value="statusLabelPrettyComputed" :severity="statusSeverity(subscription?.status)" />
|
||||
<Tag
|
||||
v-if="subscription?.cancel_at_period_end"
|
||||
severity="warning"
|
||||
value="Cancelamento agendado"
|
||||
rounded
|
||||
/>
|
||||
<Tag
|
||||
v-else-if="subscription"
|
||||
severity="success"
|
||||
value="Renovação automática"
|
||||
rounded
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 text-sm text-color-secondary">
|
||||
<b>Período:</b> {{ periodLabel }}
|
||||
</div>
|
||||
|
||||
<div v-if="cancelHint" class="mt-2 text-sm text-color-secondary">
|
||||
{{ cancelHint }}
|
||||
</div>
|
||||
|
||||
<div v-if="plan?.description" class="mt-3 text-sm opacity-80 max-w-3xl">
|
||||
{{ plan.description }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="subscription" class="flex flex-col items-end gap-2">
|
||||
<small class="text-color-secondary">subscription_id</small>
|
||||
<code class="text-xs opacity-80 break-all">
|
||||
{{ subscription.id }}
|
||||
</code>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!subscription" class="mt-4 rounded-2xl border border-[var(--surface-border)] p-4 text-sm text-color-secondary">
|
||||
Nenhuma assinatura encontrada para este tenant.
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<Divider class="my-6" />
|
||||
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
<!-- ✅ Features agrupadas -->
|
||||
<Card class="rounded-[2rem] overflow-hidden">
|
||||
<template #title>Seu plano inclui</template>
|
||||
<template #content>
|
||||
<div v-if="!subscription" class="text-color-secondary">
|
||||
Sem assinatura.
|
||||
</div>
|
||||
|
||||
<div v-else-if="!features.length" class="text-color-secondary">
|
||||
Nenhuma feature vinculada a este plano.
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-5">
|
||||
<div
|
||||
v-for="g in groupedFeatures"
|
||||
:key="g.module"
|
||||
class="rounded-2xl border border-[var(--surface-border)] overflow-hidden"
|
||||
>
|
||||
<div class="px-4 py-3 bg-[var(--surface-50)] border-b border-[var(--surface-border)] flex items-center justify-between">
|
||||
<div class="font-semibold">
|
||||
{{ moduleLabel(g.module) }}
|
||||
</div>
|
||||
<Tag :value="`${g.items.length}`" severity="secondary" rounded />
|
||||
</div>
|
||||
|
||||
<div class="p-4">
|
||||
<ul class="m-0 p-0 list-none space-y-3">
|
||||
<li
|
||||
v-for="f in g.items"
|
||||
:key="f.key"
|
||||
class="rounded-2xl border border-[var(--surface-border)] p-3"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<i class="pi pi-check mt-1 text-sm text-color-secondary"></i>
|
||||
<div class="min-w-0">
|
||||
<div class="font-medium break-words">{{ f.key }}</div>
|
||||
<div class="text-sm text-color-secondary mt-1" v-if="f.description">
|
||||
{{ f.description }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text-xs text-color-secondary">
|
||||
Agrupamento automático por prefixo da key (ex.: <b>agenda.*</b>, <b>patients.*</b>, etc.).
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<!-- ✅ Histórico auditável -->
|
||||
<Card class="rounded-[2rem] overflow-hidden">
|
||||
<template #title>Histórico</template>
|
||||
<template #content>
|
||||
<div v-if="!subscription" class="text-color-secondary">
|
||||
Sem histórico (não há assinatura).
|
||||
</div>
|
||||
|
||||
<div v-else-if="!events.length" class="text-color-secondary">
|
||||
Sem eventos registrados.
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-3">
|
||||
<div
|
||||
v-for="ev in events"
|
||||
:key="ev.id"
|
||||
class="rounded-2xl border border-[var(--surface-border)] p-3"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3 flex-wrap">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<Tag
|
||||
:value="eventLabel(ev.event_type)"
|
||||
:severity="eventSeverity(ev.event_type)"
|
||||
rounded
|
||||
/>
|
||||
<span class="text-sm text-color-secondary">
|
||||
por <b>{{ displayUser(ev.created_by) }}</b>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- De → Para (quando existir) -->
|
||||
<div v-if="ev.old_plan_id || ev.new_plan_id" class="mt-2 text-sm">
|
||||
<span class="text-color-secondary">Plano:</span>
|
||||
<span class="font-medium ml-2">{{ planKeyOrName(ev.old_plan_id) }}</span>
|
||||
<i class="pi pi-arrow-right text-color-secondary mx-2" />
|
||||
<span class="font-medium">{{ planKeyOrName(ev.new_plan_id) }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="ev.reason" class="mt-2 text-sm opacity-80">
|
||||
{{ ev.reason }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text-sm text-color-secondary">
|
||||
{{ fmtDate(ev.created_at) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-2 text-xs text-color-secondary" v-if="ev.metadata">
|
||||
<pre class="m-0 whitespace-pre-wrap break-words">{{ prettyMeta(ev.metadata) }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 text-xs text-color-secondary">
|
||||
Mostrando até 50 eventos (mais recentes).
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* (intencionalmente vazio) */
|
||||
</style>
|
||||
537
src/views/pages/billing/TherapistMeuPlanoPage.vue
Normal file
537
src/views/pages/billing/TherapistMeuPlanoPage.vue
Normal file
@@ -0,0 +1,537 @@
|
||||
<!-- src/views/pages/billing/TherapistMeuPlanoPage.vue -->
|
||||
<script setup>
|
||||
import { computed, onMounted, onBeforeUnmount, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
|
||||
const loading = ref(false)
|
||||
const subscription = ref(null)
|
||||
const plan = ref(null)
|
||||
const price = ref(null)
|
||||
const features = ref([])
|
||||
const events = ref([])
|
||||
const plans = ref([])
|
||||
const profiles = ref([])
|
||||
|
||||
// ── Hero sticky ────────────────────────────────────────────
|
||||
const headerEl = ref(null)
|
||||
const headerSentinelRef = ref(null)
|
||||
const headerStuck = ref(false)
|
||||
let _observer = null
|
||||
|
||||
// ── Formatters ─────────────────────────────────────────────
|
||||
function money(currency, amountCents) {
|
||||
if (amountCents == null) return null
|
||||
const value = Number(amountCents) / 100
|
||||
try {
|
||||
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: currency || 'BRL' }).format(value)
|
||||
} catch (_) {
|
||||
return `${value.toFixed(2)} ${currency || ''}`.trim()
|
||||
}
|
||||
}
|
||||
|
||||
function fmtDate(iso) {
|
||||
if (!iso) return '—'
|
||||
const d = new Date(iso)
|
||||
if (Number.isNaN(d.getTime())) return String(iso)
|
||||
return d.toLocaleString('pt-BR')
|
||||
}
|
||||
|
||||
function prettyMeta(meta) {
|
||||
if (!meta) return null
|
||||
try {
|
||||
if (typeof meta === 'string') return meta
|
||||
return JSON.stringify(meta, null, 2)
|
||||
} catch (_) { return String(meta) }
|
||||
}
|
||||
|
||||
function statusSeverity(st) {
|
||||
const s = String(st || '').toLowerCase()
|
||||
if (s === 'active') return 'success'
|
||||
if (s === 'trialing') return 'info'
|
||||
if (s === 'past_due') return 'warning'
|
||||
if (s === 'canceled' || s === 'cancelled') return 'danger'
|
||||
return 'secondary'
|
||||
}
|
||||
|
||||
function statusLabel(st) {
|
||||
const s = String(st || '').toLowerCase()
|
||||
if (s === 'active') return 'Ativo'
|
||||
if (s === 'trialing') return 'Trial'
|
||||
if (s === 'past_due') return 'Atrasado'
|
||||
if (s === 'canceled' || s === 'cancelled') return 'Cancelado'
|
||||
return st || '—'
|
||||
}
|
||||
|
||||
function eventSeverity(t) {
|
||||
const k = String(t || '').toLowerCase()
|
||||
if (k === 'plan_changed') return 'info'
|
||||
if (k === 'canceled') return 'danger'
|
||||
if (k === 'reactivated') return 'success'
|
||||
return 'secondary'
|
||||
}
|
||||
|
||||
function eventLabel(t) {
|
||||
const k = String(t || '').toLowerCase()
|
||||
if (k === 'plan_changed') return 'Plano alterado'
|
||||
if (k === 'canceled') return 'Cancelada'
|
||||
if (k === 'reactivated') return 'Reativada'
|
||||
return t || '—'
|
||||
}
|
||||
|
||||
// ── Computed ────────────────────────────────────────────────
|
||||
const planName = computed(() => plan.value?.name || subscription.value?.plan_key || '—')
|
||||
|
||||
const intervalLabel = computed(() => {
|
||||
const i = subscription.value?.interval
|
||||
if (i === 'month') return 'mês'
|
||||
if (i === 'year') return 'ano'
|
||||
return i || '—'
|
||||
})
|
||||
|
||||
const priceLabel = computed(() => {
|
||||
if (!price.value) return null
|
||||
return `${money(price.value.currency, price.value.amount_cents)} / ${intervalLabel.value}`
|
||||
})
|
||||
|
||||
const periodLabel = computed(() => {
|
||||
const s = subscription.value
|
||||
if (!s?.current_period_start || !s?.current_period_end) return '—'
|
||||
return `${fmtDate(s.current_period_start)} → ${fmtDate(s.current_period_end)}`
|
||||
})
|
||||
|
||||
// ── Features agrupadas ──────────────────────────────────────
|
||||
function moduleFromKey(key) {
|
||||
const k = String(key || '').trim()
|
||||
if (!k) return 'Outros'
|
||||
if (k.includes('.')) return k.split('.')[0] || 'Outros'
|
||||
if (k.includes('_')) return k.split('_')[0] || 'Outros'
|
||||
return 'Outros'
|
||||
}
|
||||
|
||||
function moduleLabel(m) {
|
||||
const s = String(m || '').trim()
|
||||
if (!s) return 'Outros'
|
||||
return s.charAt(0).toUpperCase() + s.slice(1)
|
||||
}
|
||||
|
||||
const groupedFeatures = computed(() => {
|
||||
const list = features.value || []
|
||||
const map = new Map()
|
||||
for (const f of list) {
|
||||
const mod = moduleFromKey(f.key)
|
||||
if (!map.has(mod)) map.set(mod, [])
|
||||
map.get(mod).push(f)
|
||||
}
|
||||
const modules = Array.from(map.keys()).sort((a, b) => {
|
||||
if (a === 'Outros') return 1
|
||||
if (b === 'Outros') return -1
|
||||
return a.localeCompare(b)
|
||||
})
|
||||
return modules.map(mod => {
|
||||
const items = map.get(mod) || []
|
||||
items.sort((a, b) => String(a.key || '').localeCompare(String(b.key || '')))
|
||||
return { module: mod, items }
|
||||
})
|
||||
})
|
||||
|
||||
// ── Histórico ───────────────────────────────────────────────
|
||||
const planById = computed(() => {
|
||||
const m = new Map()
|
||||
for (const p of plans.value || []) m.set(String(p.id), p)
|
||||
return m
|
||||
})
|
||||
|
||||
function planKeyOrName(planId) {
|
||||
if (!planId) return '—'
|
||||
const p = planById.value.get(String(planId))
|
||||
return p?.key || p?.name || String(planId)
|
||||
}
|
||||
|
||||
const profileById = computed(() => {
|
||||
const m = new Map()
|
||||
for (const p of profiles.value || []) m.set(String(p.id), p)
|
||||
return m
|
||||
})
|
||||
|
||||
function displayUser(userId) {
|
||||
if (!userId) return '—'
|
||||
const p = profileById.value.get(String(userId))
|
||||
if (!p) return String(userId)
|
||||
const name = p.nome || p.name || p.full_name || p.display_name || null
|
||||
const email = p.email || p.email_principal || null
|
||||
if (name && email) return `${name} <${email}>`
|
||||
return name || email || String(userId)
|
||||
}
|
||||
|
||||
// ── Actions ─────────────────────────────────────────────────
|
||||
function goUpgrade() {
|
||||
router.push('/therapist/upgrade?redirectTo=/therapist/meu-plano')
|
||||
}
|
||||
|
||||
// ── Fetch ───────────────────────────────────────────────────
|
||||
async function fetchMeuPlanoTherapist() {
|
||||
loading.value = true
|
||||
try {
|
||||
const { data: authData, error: authError } = await supabase.auth.getUser()
|
||||
if (authError) throw authError
|
||||
const uid = authData?.user?.id
|
||||
if (!uid) throw new Error('Sessão não encontrada.')
|
||||
|
||||
const sRes = await supabase
|
||||
.from('subscriptions')
|
||||
.select('*')
|
||||
.eq('user_id', uid)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(10)
|
||||
|
||||
if (sRes.error) throw sRes.error
|
||||
|
||||
const subList = sRes.data || []
|
||||
const priority = (st) => {
|
||||
const s = String(st || '').toLowerCase()
|
||||
if (s === 'active') return 1
|
||||
if (s === 'trialing') return 2
|
||||
if (s === 'past_due') return 3
|
||||
if (s === 'unpaid') return 4
|
||||
if (s === 'incomplete') return 5
|
||||
if (s === 'canceled' || s === 'cancelled') return 9
|
||||
return 8
|
||||
}
|
||||
subscription.value = subList.length
|
||||
? subList.slice().sort((a, b) => {
|
||||
const pa = priority(a?.status)
|
||||
const pb = priority(b?.status)
|
||||
if (pa !== pb) return pa - pb
|
||||
return new Date(b?.created_at || 0) - new Date(a?.created_at || 0)
|
||||
})[0]
|
||||
: null
|
||||
|
||||
if (!subscription.value) {
|
||||
plan.value = null; price.value = null
|
||||
features.value = []; events.value = []
|
||||
plans.value = []; profiles.value = []
|
||||
return
|
||||
}
|
||||
|
||||
const pRes = await supabase.from('plans').select('id, key, name, description').eq('id', subscription.value.plan_id).maybeSingle()
|
||||
if (pRes.error) throw pRes.error
|
||||
plan.value = pRes.data || null
|
||||
|
||||
const nowIso = new Date().toISOString()
|
||||
const ppRes = await supabase
|
||||
.from('plan_prices')
|
||||
.select('currency, interval, amount_cents, is_active, active_from, active_to')
|
||||
.eq('plan_id', subscription.value.plan_id)
|
||||
.eq('interval', subscription.value.interval)
|
||||
.eq('is_active', true)
|
||||
.lte('active_from', nowIso)
|
||||
.or(`active_to.is.null,active_to.gte.${nowIso}`)
|
||||
.order('active_from', { ascending: false })
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
if (ppRes.error) throw ppRes.error
|
||||
price.value = ppRes.data || null
|
||||
|
||||
const pfRes = await supabase.from('plan_features').select('feature_id').eq('plan_id', subscription.value.plan_id)
|
||||
if (pfRes.error) throw pfRes.error
|
||||
const featureIds = (pfRes.data || []).map(r => r.feature_id).filter(Boolean)
|
||||
|
||||
if (featureIds.length) {
|
||||
const fRes = await supabase.from('features').select('id, key, description, descricao').in('id', featureIds).order('key', { ascending: true })
|
||||
if (fRes.error) throw fRes.error
|
||||
features.value = (fRes.data || []).map(f => ({ key: f.key, description: (f.descricao || f.description || '').trim() }))
|
||||
} else {
|
||||
features.value = []
|
||||
}
|
||||
|
||||
const eRes = await supabase.from('subscription_events').select('*').eq('subscription_id', subscription.value.id).order('created_at', { ascending: false }).limit(50)
|
||||
if (eRes.error) throw eRes.error
|
||||
events.value = eRes.data || []
|
||||
|
||||
const planIds = new Set()
|
||||
if (subscription.value?.plan_id) planIds.add(String(subscription.value.plan_id))
|
||||
for (const ev of events.value) {
|
||||
if (ev?.old_plan_id) planIds.add(String(ev.old_plan_id))
|
||||
if (ev?.new_plan_id) planIds.add(String(ev.new_plan_id))
|
||||
}
|
||||
if (planIds.size) {
|
||||
const { data: pAll, error: epAll } = await supabase.from('plans').select('id,key,name').in('id', Array.from(planIds))
|
||||
plans.value = epAll ? [] : (pAll || [])
|
||||
} else {
|
||||
plans.value = []
|
||||
}
|
||||
|
||||
const userIds = new Set()
|
||||
for (const ev of events.value) {
|
||||
const by = String(ev.created_by || '').trim()
|
||||
if (by) userIds.add(by)
|
||||
}
|
||||
if (userIds.size) {
|
||||
const { data: pr, error: epr } = await supabase.from('profiles').select('*').in('id', Array.from(userIds))
|
||||
profiles.value = epr ? [] : (pr || [])
|
||||
} else {
|
||||
profiles.value = []
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 5000 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
const rootMargin = `${document.querySelector('.l2-main') ? '0px' : '-56px'} 0px 0px 0px`
|
||||
_observer = new IntersectionObserver(
|
||||
([entry]) => { headerStuck.value = !entry.isIntersecting },
|
||||
{ threshold: 0, rootMargin }
|
||||
)
|
||||
if (headerSentinelRef.value) _observer.observe(headerSentinelRef.value)
|
||||
fetchMeuPlanoTherapist()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => { _observer?.disconnect() })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Toast />
|
||||
|
||||
<!-- Sentinel -->
|
||||
<div ref="headerSentinelRef" class="mplan-sentinel" />
|
||||
|
||||
<!-- Hero sticky -->
|
||||
<div ref="headerEl" class="mplan-hero mx-3 md:mx-5 mb-4" :class="{ 'mplan-hero--stuck': headerStuck }">
|
||||
<div class="mplan-hero__blobs" aria-hidden="true">
|
||||
<div class="mplan-hero__blob mplan-hero__blob--1" />
|
||||
<div class="mplan-hero__blob mplan-hero__blob--2" />
|
||||
</div>
|
||||
|
||||
<!-- Row 1 -->
|
||||
<div class="mplan-hero__row1">
|
||||
<div class="mplan-hero__brand">
|
||||
<div class="mplan-hero__icon"><i class="pi pi-credit-card text-lg" /></div>
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<div class="mplan-hero__title">Meu Plano</div>
|
||||
<Tag v-if="subscription" :value="statusLabel(subscription.status)" :severity="statusSeverity(subscription.status)" />
|
||||
</div>
|
||||
<div class="mplan-hero__sub">Plano pessoal do terapeuta — gerencie sua assinatura</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Desktop (≥1200px) -->
|
||||
<div class="hidden xl:flex items-center gap-2 shrink-0">
|
||||
<Button icon="pi pi-refresh" severity="secondary" outlined class="h-9 w-9 rounded-full" :loading="loading" title="Atualizar" @click="fetchMeuPlanoTherapist" />
|
||||
<Button label="Alterar plano" icon="pi pi-arrow-up-right" class="rounded-full" @click="goUpgrade" />
|
||||
</div>
|
||||
|
||||
<!-- Mobile (<1200px) -->
|
||||
<div class="flex xl:hidden items-center gap-2 shrink-0">
|
||||
<Button icon="pi pi-refresh" severity="secondary" outlined class="h-9 w-9 rounded-full" :loading="loading" @click="fetchMeuPlanoTherapist" />
|
||||
<Button label="Alterar plano" icon="pi pi-arrow-up-right" size="small" class="rounded-full" @click="goUpgrade" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Divider -->
|
||||
<Divider class="mplan-hero__divider my-2" />
|
||||
|
||||
<!-- Row 2: resumo rápido (oculto no mobile) -->
|
||||
<div class="mplan-hero__row2">
|
||||
<div v-if="loading" class="flex items-center gap-2 text-sm text-[var(--text-color-secondary)]">
|
||||
<i class="pi pi-spin pi-spinner text-xs" /> Carregando…
|
||||
</div>
|
||||
<template v-else-if="subscription">
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<span class="font-semibold text-sm text-[var(--text-color)]">{{ planName }}</span>
|
||||
<span v-if="priceLabel" class="text-sm text-[var(--text-color-secondary)]">{{ priceLabel }}</span>
|
||||
<span class="text-xs text-[var(--text-color-secondary)] border border-[var(--surface-border)] rounded-full px-3 py-1">
|
||||
Período: {{ periodLabel }}
|
||||
</span>
|
||||
<Tag v-if="subscription.cancel_at_period_end" severity="warning" value="Cancelamento agendado" />
|
||||
<Tag v-else severity="success" value="Renovação automática" />
|
||||
</div>
|
||||
</template>
|
||||
<div v-else class="text-sm text-[var(--text-color-secondary)]">Nenhuma assinatura ativa.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Conteúdo -->
|
||||
<div class="px-3 md:px-5 mb-5 flex flex-col gap-4">
|
||||
|
||||
<!-- Sem assinatura -->
|
||||
<div v-if="!loading && !subscription" class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] p-10 text-center">
|
||||
<div class="mx-auto mb-3 grid h-12 w-12 place-items-center rounded-2xl bg-[var(--primary-color)]/10 text-[var(--primary-color)]">
|
||||
<i class="pi pi-credit-card text-xl" />
|
||||
</div>
|
||||
<div class="font-semibold">Nenhuma assinatura encontrada</div>
|
||||
<div class="mt-1 text-sm text-[var(--text-color-secondary)]">Escolha um plano para começar a usar todos os recursos.</div>
|
||||
<div class="mt-4">
|
||||
<Button label="Ver planos" icon="pi pi-arrow-up-right" class="rounded-full" @click="goUpgrade" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
|
||||
<!-- Seu plano inclui: features compactas -->
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] overflow-hidden">
|
||||
<div class="px-5 py-4 border-b border-[var(--surface-border)] flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<div class="font-semibold text-[var(--text-color)]">Seu plano inclui</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-0.5">Recursos disponíveis na sua assinatura atual</div>
|
||||
</div>
|
||||
<Tag v-if="features.length" :value="`${features.length}`" severity="secondary" />
|
||||
</div>
|
||||
|
||||
<div class="p-5">
|
||||
<div v-if="!subscription" class="text-sm text-[var(--text-color-secondary)]">Sem assinatura.</div>
|
||||
<div v-else-if="!features.length" class="text-sm text-[var(--text-color-secondary)]">Nenhuma feature vinculada a este plano.</div>
|
||||
|
||||
<div v-else class="space-y-5">
|
||||
<div v-for="g in groupedFeatures" :key="g.module">
|
||||
<!-- Cabeçalho do módulo -->
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
<span class="text-xs font-bold uppercase tracking-wider text-[var(--text-color-secondary)] opacity-50">
|
||||
{{ moduleLabel(g.module) }}
|
||||
</span>
|
||||
<div class="flex-1 h-px bg-[var(--surface-border)]" />
|
||||
<span class="text-xs text-[var(--text-color-secondary)]">{{ g.items.length }}</span>
|
||||
</div>
|
||||
|
||||
<!-- Grid compacto de features -->
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1">
|
||||
<div
|
||||
v-for="f in g.items"
|
||||
:key="f.key"
|
||||
class="flex items-start gap-2 py-1 px-2 rounded-lg hover:bg-[var(--surface-ground)] transition-colors"
|
||||
:title="f.description || f.key"
|
||||
>
|
||||
<i class="pi pi-check-circle text-emerald-500 text-sm mt-0.5 shrink-0" />
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-medium truncate text-[var(--text-color)]">{{ f.key }}</div>
|
||||
<div v-if="f.description" class="text-xs text-[var(--text-color-secondary)] leading-snug truncate">{{ f.description }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Histórico -->
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] overflow-hidden">
|
||||
<div class="px-5 py-4 border-b border-[var(--surface-border)] flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<div class="font-semibold text-[var(--text-color)]">Histórico</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-0.5">Últimos 50 eventos da assinatura</div>
|
||||
</div>
|
||||
<Tag v-if="events.length" :value="`${events.length}`" severity="secondary" />
|
||||
</div>
|
||||
|
||||
<div class="p-5">
|
||||
<div v-if="!subscription" class="text-sm text-[var(--text-color-secondary)]">Sem histórico (não há assinatura).</div>
|
||||
<div v-else-if="!events.length" class="py-8 text-center">
|
||||
<i class="pi pi-history text-2xl text-[var(--text-color-secondary)] opacity-30 mb-2 block" />
|
||||
<div class="text-sm text-[var(--text-color-secondary)]">Sem eventos registrados.</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-2">
|
||||
<div
|
||||
v-for="ev in events"
|
||||
:key="ev.id"
|
||||
class="rounded-xl border border-[var(--surface-border)] p-3 hover:bg-[var(--surface-ground)] transition-colors"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3 flex-wrap">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<Tag :value="eventLabel(ev.event_type)" :severity="eventSeverity(ev.event_type)" />
|
||||
<span class="text-xs text-[var(--text-color-secondary)]">
|
||||
por <b>{{ displayUser(ev.created_by) }}</b>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="ev.old_plan_id || ev.new_plan_id" class="mt-1.5 text-xs text-[var(--text-color-secondary)] flex items-center gap-1.5 flex-wrap">
|
||||
<span class="font-medium text-[var(--text-color)]">{{ planKeyOrName(ev.old_plan_id) }}</span>
|
||||
<i class="pi pi-arrow-right text-xs opacity-50" />
|
||||
<span class="font-medium text-[var(--text-color)]">{{ planKeyOrName(ev.new_plan_id) }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="ev.reason" class="mt-1 text-xs text-[var(--text-color-secondary)] opacity-70">{{ ev.reason }}</div>
|
||||
|
||||
<div v-if="ev.metadata" class="mt-1.5">
|
||||
<pre class="m-0 text-xs text-[var(--text-color-secondary)] whitespace-pre-wrap break-words opacity-60">{{ prettyMeta(ev.metadata) }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text-xs text-[var(--text-color-secondary)] shrink-0">{{ fmtDate(ev.created_at) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Rodapé: subscription ID -->
|
||||
<div v-if="subscription" class="text-xs text-[var(--text-color-secondary)] flex items-center gap-2 flex-wrap">
|
||||
<span>ID da assinatura:</span>
|
||||
<code class="font-mono select-all">{{ subscription.id }}</code>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.mplan-sentinel { height: 1px; }
|
||||
|
||||
.mplan-hero {
|
||||
position: sticky;
|
||||
top: var(--layout-sticky-top, 56px);
|
||||
z-index: 20;
|
||||
overflow: hidden;
|
||||
border-radius: 1.75rem;
|
||||
border: 1px solid var(--surface-border);
|
||||
background: var(--surface-card);
|
||||
padding: 1.25rem 1.5rem;
|
||||
}
|
||||
.mplan-hero--stuck {
|
||||
margin-left: 0; margin-right: 0;
|
||||
border-top-left-radius: 0; border-top-right-radius: 0;
|
||||
}
|
||||
|
||||
.mplan-hero__blobs { position: absolute; inset: 0; pointer-events: none; overflow: hidden; }
|
||||
.mplan-hero__blob { position: absolute; border-radius: 50%; filter: blur(70px); }
|
||||
.mplan-hero__blob--1 { width: 18rem; height: 18rem; top: -4rem; right: -3rem; background: rgba(99,102,241,0.10); }
|
||||
.mplan-hero__blob--2 { width: 20rem; height: 20rem; top: 0.5rem; left: -5rem; background: rgba(16,185,129,0.08); }
|
||||
|
||||
.mplan-hero__row1 {
|
||||
position: relative; z-index: 1;
|
||||
display: flex; align-items: center; gap: 1rem;
|
||||
}
|
||||
.mplan-hero__brand {
|
||||
display: flex; align-items: center; gap: 0.75rem;
|
||||
flex: 1; min-width: 0;
|
||||
}
|
||||
.mplan-hero__icon {
|
||||
display: grid; place-items: center;
|
||||
width: 2.5rem; height: 2.5rem; border-radius: 0.875rem; flex-shrink: 0;
|
||||
background: color-mix(in srgb, var(--p-primary-500, #6366f1) 12%, transparent);
|
||||
color: var(--p-primary-500, #6366f1);
|
||||
}
|
||||
.mplan-hero__title { font-size: 1.1rem; font-weight: 700; letter-spacing: -0.02em; color: var(--text-color); }
|
||||
.mplan-hero__sub { font-size: 0.78rem; color: var(--text-color-secondary); margin-top: 2px; }
|
||||
|
||||
.mplan-hero__row2 {
|
||||
position: relative; z-index: 1;
|
||||
display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.mplan-hero__divider,
|
||||
.mplan-hero__row2 { display: none; }
|
||||
}
|
||||
</style>
|
||||
422
src/views/pages/billing/TherapistUpgradePage.vue
Normal file
422
src/views/pages/billing/TherapistUpgradePage.vue
Normal file
@@ -0,0 +1,422 @@
|
||||
<!-- src/views/pages/billing/TherapistUpgradePage.vue -->
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
|
||||
const toast = useToast()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const isFetching = ref(false)
|
||||
|
||||
const uid = ref(null)
|
||||
const currentSub = ref(null)
|
||||
|
||||
const plans = ref([]) // plans (therapist)
|
||||
const prices = ref([]) // plan_prices ativos do momento
|
||||
|
||||
const q = ref('')
|
||||
|
||||
const billingInterval = ref('month') // 'month' | 'year'
|
||||
const intervalOptions = [
|
||||
{ label: 'Mensal', value: 'month' },
|
||||
{ label: 'Anual', value: 'year' }
|
||||
]
|
||||
|
||||
const redirectTo = computed(() => route.query.redirectTo || '/therapist/meu-plano')
|
||||
|
||||
function money (currency, amountCents) {
|
||||
if (amountCents == null) return null
|
||||
const value = Number(amountCents) / 100
|
||||
try {
|
||||
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: currency || 'BRL' }).format(value)
|
||||
} catch (_) {
|
||||
return `${value.toFixed(2)} ${currency || ''}`.trim()
|
||||
}
|
||||
}
|
||||
|
||||
function intervalLabel (i) {
|
||||
if (i === 'month') return 'mês'
|
||||
if (i === 'year') return 'ano'
|
||||
return i || '-'
|
||||
}
|
||||
|
||||
function priceFor (planId, interval) {
|
||||
return (prices.value || []).find(p => String(p.plan_id) === String(planId) && String(p.interval) === String(interval)) || null
|
||||
}
|
||||
|
||||
function priceLabelForCard (planRow) {
|
||||
const pp = priceFor(planRow?.id, billingInterval.value)
|
||||
if (!pp) return '—'
|
||||
return `${money(pp.currency, pp.amount_cents)} / ${intervalLabel(billingInterval.value)}`
|
||||
}
|
||||
|
||||
const filteredPlans = computed(() => {
|
||||
const term = String(q.value || '').trim().toLowerCase()
|
||||
if (!term) return plans.value || []
|
||||
return (plans.value || []).filter(p => {
|
||||
const a = String(p.key || '').toLowerCase()
|
||||
const b = String(p.name || '').toLowerCase()
|
||||
const c = String(p.description || '').toLowerCase()
|
||||
return a.includes(term) || b.includes(term) || c.includes(term)
|
||||
})
|
||||
})
|
||||
|
||||
async function loadData () {
|
||||
if (isFetching.value) return
|
||||
isFetching.value = true
|
||||
loading.value = true
|
||||
|
||||
try {
|
||||
const { data: authData, error: authError } = await supabase.auth.getUser()
|
||||
if (authError) throw authError
|
||||
|
||||
uid.value = authData?.user?.id
|
||||
if (!uid.value) throw new Error('Sessão não encontrada.')
|
||||
|
||||
// assinatura pessoal atual (Modelo A): busca por user_id, prioriza status ativo
|
||||
const sRes = await supabase
|
||||
.from('subscriptions')
|
||||
.select('*')
|
||||
.eq('user_id', uid.value)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(10)
|
||||
|
||||
if (sRes.error) throw sRes.error
|
||||
|
||||
const subList = sRes.data || []
|
||||
const subPriority = (st) => {
|
||||
const s = String(st || '').toLowerCase()
|
||||
if (s === 'active') return 1
|
||||
if (s === 'trialing') return 2
|
||||
if (s === 'past_due') return 3
|
||||
if (s === 'unpaid') return 4
|
||||
if (s === 'incomplete') return 5
|
||||
if (s === 'canceled' || s === 'cancelled') return 9
|
||||
return 8
|
||||
}
|
||||
currentSub.value = subList.length
|
||||
? subList.slice().sort((a, b) => {
|
||||
const pa = subPriority(a?.status)
|
||||
const pb = subPriority(b?.status)
|
||||
if (pa !== pb) return pa - pb
|
||||
return new Date(b?.created_at || 0) - new Date(a?.created_at || 0)
|
||||
})[0]
|
||||
: null
|
||||
|
||||
// planos do terapeuta (target = therapist)
|
||||
const pRes = await supabase
|
||||
.from('plans')
|
||||
.select('id, key, name, description, target, is_active')
|
||||
.eq('target', 'therapist')
|
||||
.order('created_at', { ascending: true })
|
||||
|
||||
if (pRes.error) throw pRes.error
|
||||
plans.value = (pRes.data || []).filter(p => p?.is_active !== false)
|
||||
|
||||
// preços ativos (janela de vigência)
|
||||
const nowIso = new Date().toISOString()
|
||||
const ppRes = await supabase
|
||||
.from('plan_prices')
|
||||
.select('plan_id, currency, interval, amount_cents, is_active, active_from, active_to')
|
||||
.eq('is_active', true)
|
||||
.lte('active_from', nowIso)
|
||||
.or(`active_to.is.null,active_to.gte.${nowIso}`)
|
||||
.order('active_from', { ascending: false })
|
||||
|
||||
if (ppRes.error) throw ppRes.error
|
||||
prices.value = ppRes.data || []
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 5000 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
isFetching.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function preflight (planRow, interval) {
|
||||
if (!uid.value) return { ok: false, msg: 'Sessão não encontrada.' }
|
||||
if (!planRow?.id) return { ok: false, msg: 'Plano inválido.' }
|
||||
if (!['month', 'year'].includes(String(interval))) return { ok: false, msg: 'Intervalo inválido.' }
|
||||
|
||||
const pp = priceFor(planRow.id, interval)
|
||||
if (!pp) {
|
||||
return { ok: false, msg: `Este plano não tem preço ativo para ${intervalLabel(interval)}.` }
|
||||
}
|
||||
|
||||
// se já estiver nesse plano+intervalo, evita ação
|
||||
if (currentSub.value?.plan_id === planRow.id && String(currentSub.value?.interval) === String(interval)) {
|
||||
return { ok: false, msg: 'Você já está nesse plano/intervalo.' }
|
||||
}
|
||||
|
||||
return { ok: true, msg: '' }
|
||||
}
|
||||
|
||||
/**
|
||||
* ✅ Fluxo seguro:
|
||||
* - se já existe subscription => chama RPC change_subscription_plan (audita + triggers)
|
||||
* - se não existe => cria subscription mínima e depois (opcional) roda rebuild_owner_entitlements
|
||||
*
|
||||
* Observação:
|
||||
* - aqui eu assumo que você tem `change_subscription_plan(p_subscription_id, p_new_plan_id)`
|
||||
* e que interval pode ser alterado por update simples ou outro RPC.
|
||||
* - se você tiver um RPC específico para intervalo, só troca abaixo.
|
||||
*/
|
||||
async function choosePlan (planRow, interval) {
|
||||
const pf = preflight(planRow, interval)
|
||||
if (!pf.ok) {
|
||||
toast.add({ severity: 'warn', summary: 'Atenção', detail: pf.msg, life: 4200 })
|
||||
return
|
||||
}
|
||||
|
||||
saving.value = true
|
||||
try {
|
||||
const nowIso = new Date().toISOString()
|
||||
|
||||
if (currentSub.value?.id) {
|
||||
// 1) troca plano via RPC (auditoria)
|
||||
const { error: e1 } = await supabase.rpc('change_subscription_plan', {
|
||||
p_subscription_id: currentSub.value.id,
|
||||
p_new_plan_id: planRow.id
|
||||
})
|
||||
if (e1) throw e1
|
||||
|
||||
// 2) atualiza intervalo (se o seu RPC já faz isso, pode remover)
|
||||
const { error: e2 } = await supabase
|
||||
.from('subscriptions')
|
||||
.update({
|
||||
interval,
|
||||
updated_at: nowIso,
|
||||
cancel_at_period_end: false,
|
||||
status: 'active'
|
||||
})
|
||||
.eq('id', currentSub.value.id)
|
||||
if (e2) throw e2
|
||||
} else {
|
||||
// cria subscription pessoal
|
||||
const { data: ins, error: eIns } = await supabase
|
||||
.from('subscriptions')
|
||||
.insert({
|
||||
user_id: uid.value,
|
||||
tenant_id: null,
|
||||
plan_id: planRow.id,
|
||||
plan_key: planRow.key,
|
||||
interval,
|
||||
status: 'active',
|
||||
cancel_at_period_end: false,
|
||||
provider: 'manual',
|
||||
source: 'therapist_upgrade',
|
||||
started_at: nowIso,
|
||||
current_period_start: nowIso
|
||||
})
|
||||
.select('*')
|
||||
.maybeSingle()
|
||||
|
||||
if (eIns) throw eIns
|
||||
currentSub.value = ins || null
|
||||
}
|
||||
|
||||
// (opcional) se sua regra de entitlements depende disso, você pode rebuildar aqui:
|
||||
// await supabase.rpc('rebuild_owner_entitlements', { p_owner_id: uid.value })
|
||||
|
||||
toast.add({
|
||||
severity: 'success',
|
||||
summary: 'Plano atualizado',
|
||||
detail: 'Seu plano foi atualizado com sucesso.',
|
||||
life: 3200
|
||||
})
|
||||
|
||||
// ✅ garante refletir estado real
|
||||
await loadData()
|
||||
|
||||
// redirect
|
||||
await router.push(String(redirectTo.value))
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 5000 })
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function goBack () {
|
||||
router.push(String(redirectTo.value))
|
||||
}
|
||||
|
||||
onMounted(loadData)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="p-4 md:p-6">
|
||||
<Toast />
|
||||
|
||||
<!-- ✅ Topbar padrão -->
|
||||
<div class="mb-4 rounded-3xl border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 shadow-sm">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="flex flex-col">
|
||||
<div class="text-2xl font-semibold leading-none">Upgrade do terapeuta</div>
|
||||
<small class="text-color-secondary mt-1">
|
||||
Escolha seu plano pessoal (Modelo A).
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2 flex-wrap justify-end">
|
||||
<Button
|
||||
label="Voltar"
|
||||
icon="pi pi-arrow-left"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:disabled="saving"
|
||||
@click="goBack"
|
||||
/>
|
||||
<Button
|
||||
label="Atualizar"
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:loading="loading"
|
||||
:disabled="saving"
|
||||
@click="loadData"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex flex-wrap items-center gap-3">
|
||||
<Tag
|
||||
v-if="currentSub"
|
||||
:value="`Plano atual: ${currentSub.plan_key} • ${intervalLabel(currentSub.interval)} • ${currentSub.status}`"
|
||||
severity="success"
|
||||
rounded
|
||||
/>
|
||||
<Tag
|
||||
v-else
|
||||
value="Você ainda não tem um plano pessoal."
|
||||
severity="warning"
|
||||
rounded
|
||||
/>
|
||||
|
||||
<div class="flex items-center gap-2 ml-auto">
|
||||
<small class="text-color-secondary">Exibição de preço</small>
|
||||
<SelectButton
|
||||
v-model="billingInterval"
|
||||
:options="intervalOptions"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
:disabled="loading || saving"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ✅ Busca padrão FloatLabel -->
|
||||
<Card class="rounded-[2rem] overflow-hidden mb-4">
|
||||
<template #content>
|
||||
<div class="flex flex-wrap items-center gap-3 justify-between">
|
||||
<div class="flex flex-col">
|
||||
<div class="font-semibold">Planos disponíveis</div>
|
||||
<small class="text-color-secondary">
|
||||
Filtre por nome/key/descrição e selecione.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="w-full md:w-[420px]">
|
||||
<FloatLabel variant="on" class="w-full">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-search" />
|
||||
<InputText v-model="q" id="therapist_upgrade_search" class="w-full pr-10" variant="filled" />
|
||||
</IconField>
|
||||
<label for="therapist_upgrade_search">Buscar plano...</label>
|
||||
</FloatLabel>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<Divider />
|
||||
|
||||
<!-- ✅ Cards estilo vitrine -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 mt-4">
|
||||
<Card
|
||||
v-for="p in filteredPlans"
|
||||
:key="p.id"
|
||||
:class="[
|
||||
'rounded-[2rem] overflow-hidden border border-[var(--surface-border)]',
|
||||
currentSub?.plan_id === p.id ? 'ring-1 ring-emerald-500/25 md:-translate-y-1 md:scale-[1.01]' : ''
|
||||
]"
|
||||
>
|
||||
<template #title>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<div class="min-w-0">
|
||||
<div class="font-semibold truncate">{{ p.name || p.key }}</div>
|
||||
<small class="text-color-secondary">{{ p.key }}</small>
|
||||
</div>
|
||||
|
||||
<Tag v-if="currentSub?.plan_id === p.id" severity="success" value="Atual" rounded />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #content>
|
||||
<div class="text-sm text-color-secondary" v-if="p.description">
|
||||
{{ p.description }}
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<div class="text-4xl font-semibold leading-none">
|
||||
{{ priceLabelForCard(p) }}
|
||||
</div>
|
||||
|
||||
<div class="text-xs text-color-secondary mt-1">
|
||||
Alternar mensal/anual no topo para comparar.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-5 flex gap-2 flex-wrap">
|
||||
<Button
|
||||
:label="billingInterval === 'month' ? 'Escolher mensal' : 'Escolher anual'"
|
||||
icon="pi pi-check"
|
||||
:loading="saving"
|
||||
:disabled="loading || saving"
|
||||
@click="choosePlan(p, billingInterval)"
|
||||
/>
|
||||
|
||||
<Button
|
||||
label="Mensal"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:disabled="loading || saving"
|
||||
@click="choosePlan(p, 'month')"
|
||||
/>
|
||||
|
||||
<Button
|
||||
label="Anual"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:disabled="loading || saving"
|
||||
@click="choosePlan(p, 'year')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 text-xs text-color-secondary">
|
||||
<span v-if="priceFor(p.id, billingInterval)">
|
||||
Preço ativo encontrado para {{ intervalLabel(billingInterval) }}.
|
||||
</span>
|
||||
<span v-else>
|
||||
Sem preço ativo para {{ intervalLabel(billingInterval) }}.
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div v-if="!filteredPlans.length && !loading" class="mt-4 text-sm text-color-secondary">
|
||||
Nenhum plano encontrado.
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,13 +1,8 @@
|
||||
<!-- src/views/pages/upgrade/UpgradePage.vue (ajuste o caminho conforme seu projeto) -->
|
||||
<!-- src/views/pages/upgrade/UpgradePage.vue -->
|
||||
<script setup>
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
|
||||
import Card from 'primevue/card'
|
||||
import Button from 'primevue/button'
|
||||
import Divider from 'primevue/divider'
|
||||
import Tag from 'primevue/tag'
|
||||
import Toast from 'primevue/toast'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
@@ -21,35 +16,54 @@ const router = useRouter()
|
||||
const tenantStore = useTenantStore()
|
||||
const entitlementsStore = useEntitlementsStore()
|
||||
|
||||
// ======================================================
|
||||
// ✅ Detecta contexto: terapeuta (personal) ou clínica (tenant)
|
||||
// O guard passa ?role=therapist ou ?role=clinic_admin na URL,
|
||||
// mas também fazemos fallback pelo activeRole do tenantStore.
|
||||
// ======================================================
|
||||
const activeRole = computed(() => {
|
||||
const fromQuery = route.query.role || ''
|
||||
const fromStore = tenantStore.activeRole || ''
|
||||
const r = String(fromQuery || fromStore).trim()
|
||||
if (r === 'therapist') return 'therapist'
|
||||
if (r === 'clinic_admin' || r === 'tenant_admin') return 'clinic_admin'
|
||||
return 'clinic_admin' // fallback seguro
|
||||
})
|
||||
|
||||
const isTherapist = computed(() => activeRole.value === 'therapist')
|
||||
const planTarget = computed(() => isTherapist.value ? 'therapist' : 'clinic')
|
||||
|
||||
// Feature que motivou o redirecionamento
|
||||
const requestedFeature = computed(() => route.query.feature || null)
|
||||
|
||||
// nomes amigáveis (fallback se não achar)
|
||||
const featureLabels = {
|
||||
'online_scheduling.manage': 'Agendamento Online',
|
||||
'online_scheduling.public': 'Página pública de agendamento',
|
||||
'advanced_reports': 'Relatórios avançados',
|
||||
'sms_reminder': 'Lembretes por SMS',
|
||||
'intakes_pro': 'Formulários PRO'
|
||||
// ✅ nome vem do banco (features.name), sem hardcode
|
||||
const featureNameMap = computed(() => {
|
||||
const m = new Map()
|
||||
for (const f of features.value) m.set(f.key, f.name || f.key)
|
||||
return m
|
||||
})
|
||||
|
||||
function friendlyFeatureLabel (key) {
|
||||
return featureNameMap.value.get(key) || key
|
||||
}
|
||||
|
||||
const requestedFeatureLabel = computed(() => {
|
||||
if (!requestedFeature.value) return null
|
||||
return featureLabels[requestedFeature.value] || requestedFeature.value
|
||||
return featureNameMap.value.get(requestedFeature.value) || requestedFeature.value
|
||||
})
|
||||
|
||||
// estado
|
||||
const loading = ref(false)
|
||||
const loading = ref(false)
|
||||
const upgrading = ref(false)
|
||||
|
||||
const plans = ref([]) // plans reais
|
||||
const features = ref([]) // features reais
|
||||
const planFeatures = ref([]) // links reais plan_features
|
||||
const plans = ref([])
|
||||
const features = ref([])
|
||||
const planFeatures = ref([])
|
||||
const prices = ref([])
|
||||
const subscription = ref(null)
|
||||
|
||||
const subscription = ref(null) // subscription ativa do tenant
|
||||
|
||||
// ✅ Modelo B: plano é do TENANT
|
||||
const tenantId = computed(() => tenantStore.activeTenantId || null)
|
||||
// IDs de contexto — dependem do role
|
||||
const tenantId = computed(() => isTherapist.value ? null : (tenantStore.activeTenantId || null))
|
||||
const userId = computed(() => isTherapist.value ? (tenantStore.user?.id || null) : null)
|
||||
|
||||
const planById = computed(() => {
|
||||
const m = new Map()
|
||||
@@ -58,7 +72,6 @@ const planById = computed(() => {
|
||||
})
|
||||
|
||||
const enabledFeatureIdsByPlanId = computed(() => {
|
||||
// Map planId -> Set(featureId)
|
||||
const m = new Map()
|
||||
for (const row of planFeatures.value) {
|
||||
const set = m.get(row.plan_id) || new Set()
|
||||
@@ -68,145 +81,161 @@ const enabledFeatureIdsByPlanId = computed(() => {
|
||||
return m
|
||||
})
|
||||
|
||||
const currentPlanId = computed(() => subscription.value?.plan_id || null)
|
||||
const currentPlanId = computed(() => subscription.value?.plan_id || null)
|
||||
const currentPlanKey = computed(() => planById.value.get(currentPlanId.value)?.key || subscription.value?.plan_key || null)
|
||||
|
||||
function planKeyById (id) {
|
||||
return planById.value.get(id)?.key || null
|
||||
}
|
||||
|
||||
const currentPlanKey = computed(() => {
|
||||
// ✅ fallback: se não carregou plans ainda, usa o plan_key da subscription
|
||||
return planKeyById(currentPlanId.value) || subscription.value?.plan_key || null
|
||||
})
|
||||
|
||||
function friendlyFeatureLabel (featureKey) {
|
||||
return featureLabels[featureKey] || featureKey
|
||||
|
||||
const billingInterval = ref('month')
|
||||
const intervalOptions = [
|
||||
{ label: 'Mensal', value: 'month' },
|
||||
{ label: 'Anual', value: 'year' }
|
||||
]
|
||||
|
||||
const q = ref('')
|
||||
|
||||
function intervalLabel (i) {
|
||||
return i === 'month' ? 'mês' : i === 'year' ? 'ano' : (i || '-')
|
||||
}
|
||||
|
||||
function money (currency, amountCents) {
|
||||
if (amountCents == null) return null
|
||||
const value = Number(amountCents) / 100
|
||||
try {
|
||||
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: currency || 'BRL' }).format(value)
|
||||
} catch {
|
||||
return `${value.toFixed(2)} ${currency || ''}`.trim()
|
||||
}
|
||||
}
|
||||
|
||||
function priceFor (planId, interval) {
|
||||
return (prices.value || []).find(p =>
|
||||
String(p.plan_id) === String(planId) && String(p.interval) === String(interval)
|
||||
) || null
|
||||
}
|
||||
|
||||
function priceLabelForPlan (planId) {
|
||||
const pp = priceFor(planId, billingInterval.value)
|
||||
if (!pp) return '—'
|
||||
return `${money(pp.currency, pp.amount_cents)} / ${intervalLabel(billingInterval.value)}`
|
||||
}
|
||||
|
||||
const sortedPlans = computed(() => {
|
||||
// ordena free primeiro, pro segundo, resto por key
|
||||
const arr = [...plans.value]
|
||||
const rank = (k) => (k === 'free' ? 0 : k === 'pro' ? 1 : 10)
|
||||
arr.sort((a, b) => {
|
||||
const ra = rank(a.key), rb = rank(b.key)
|
||||
if (ra !== rb) return ra - rb
|
||||
return String(a.key).localeCompare(String(b.key))
|
||||
})
|
||||
const term = String(q.value || '').trim().toLowerCase()
|
||||
let arr = [...plans.value]
|
||||
if (term) {
|
||||
arr = arr.filter(p =>
|
||||
[p.key, p.name, p.description].some(s => String(s || '').toLowerCase().includes(term))
|
||||
)
|
||||
}
|
||||
const rank = k => String(k).toLowerCase() === 'pro' ? 0 : String(k).toLowerCase() === 'free' ? 5 : 10
|
||||
arr.sort((a, b) => rank(a.key) - rank(b.key) || String(a.key).localeCompare(String(b.key)))
|
||||
return arr
|
||||
})
|
||||
|
||||
function planBenefits (planId) {
|
||||
const set = enabledFeatureIdsByPlanId.value.get(planId) || new Set()
|
||||
const list = features.value.map((f) => ({
|
||||
ok: set.has(f.id),
|
||||
key: f.key,
|
||||
text: friendlyFeatureLabel(f.key)
|
||||
}))
|
||||
// coloca as “ok” em cima
|
||||
list.sort((a, b) => Number(b.ok) - Number(a.ok) || a.text.localeCompare(b.text))
|
||||
return list
|
||||
return features.value
|
||||
.map(f => ({ ok: set.has(f.id), key: f.key, text: friendlyFeatureLabel(f.key) }))
|
||||
.sort((a, b) => Number(b.ok) - Number(a.ok) || a.text.localeCompare(b.text))
|
||||
}
|
||||
|
||||
function goBack () {
|
||||
router.back()
|
||||
}
|
||||
function goBack () { router.back() }
|
||||
function goBilling () { router.push(isTherapist.value ? '/therapist/meu-plano' : '/admin/meu-plano') }
|
||||
function contactSupport () { goBilling() }
|
||||
|
||||
function goBilling () {
|
||||
router.push('/admin/billing')
|
||||
}
|
||||
|
||||
function contactSupport () {
|
||||
router.push('/admin/billing')
|
||||
}
|
||||
|
||||
// ✅ revalida a rota atual para o guard reavaliar features após troca de plano
|
||||
async function revalidateCurrentRoute () {
|
||||
// tenta respeitar um redirectTo (quando usuário veio por recurso bloqueado)
|
||||
const redirectTo = route.query.redirectTo ? String(route.query.redirectTo) : null
|
||||
|
||||
// se existe redirectTo, tente ir para ele (guard decide se entra ou volta ao upgrade)
|
||||
if (redirectTo) {
|
||||
try {
|
||||
await router.replace(redirectTo)
|
||||
return
|
||||
} catch (_) {
|
||||
// se falhar, cai no refresh da rota atual
|
||||
}
|
||||
try { await router.replace(redirectTo); return } catch {}
|
||||
}
|
||||
|
||||
// força o vue-router a reprocessar a rota (dispara beforeEach)
|
||||
try {
|
||||
await router.replace(router.currentRoute.value.fullPath)
|
||||
} catch (_) {}
|
||||
try { await router.replace(router.currentRoute.value.fullPath) } catch {}
|
||||
}
|
||||
|
||||
async function fetchAll () {
|
||||
loading.value = true
|
||||
try {
|
||||
const tid = tenantId.value
|
||||
if (!tid) throw new Error('Tenant ativo não encontrado.')
|
||||
if (!tenantStore.loaded) await tenantStore.loadSessionAndTenant()
|
||||
|
||||
const [pRes, fRes, pfRes, sRes] = await Promise.all([
|
||||
supabase.from('plans').select('*').eq('is_active', true).order('key', { ascending: true }),
|
||||
supabase.from('features').select('*').order('key', { ascending: true }),
|
||||
supabase.from('plan_features').select('plan_id, feature_id'),
|
||||
supabase
|
||||
const nowIso = new Date().toISOString()
|
||||
|
||||
// ✅ busca planos do target correto (therapist ou clinic)
|
||||
const pQuery = supabase
|
||||
.from('plans')
|
||||
.select('*')
|
||||
.eq('is_active', true)
|
||||
.eq('target', planTarget.value)
|
||||
.order('key', { ascending: true })
|
||||
|
||||
// ✅ busca subscription do contexto correto
|
||||
let sQuery = supabase
|
||||
.from('subscriptions')
|
||||
.select(`id, tenant_id, user_id, plan_id, plan_key, interval, status,
|
||||
provider, source, started_at, current_period_start,
|
||||
current_period_end, created_at, updated_at`)
|
||||
.eq('status', 'active')
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
|
||||
if (isTherapist.value) {
|
||||
const uid = userId.value
|
||||
if (!uid) throw new Error('Usuário não identificado.')
|
||||
sQuery = supabase
|
||||
.from('subscriptions')
|
||||
// ✅ pega mais campos úteis e faz join do plano (ajuda a exibir e debugar)
|
||||
.select(`
|
||||
id,
|
||||
tenant_id,
|
||||
user_id,
|
||||
plan_id,
|
||||
plan_key,
|
||||
"interval",
|
||||
status,
|
||||
provider,
|
||||
source,
|
||||
started_at,
|
||||
current_period_start,
|
||||
current_period_end,
|
||||
created_at,
|
||||
updated_at,
|
||||
plan:plan_id (
|
||||
id,
|
||||
key,
|
||||
name,
|
||||
description,
|
||||
price_cents,
|
||||
currency,
|
||||
billing_interval,
|
||||
is_active
|
||||
)
|
||||
`)
|
||||
.eq('tenant_id', tid)
|
||||
.select(`id, tenant_id, user_id, plan_id, plan_key, interval, status,
|
||||
provider, source, started_at, current_period_start,
|
||||
current_period_end, created_at, updated_at`)
|
||||
.eq('user_id', uid)
|
||||
.is('tenant_id', null)
|
||||
.eq('status', 'active')
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
} else {
|
||||
const tid = tenantId.value
|
||||
if (!tid) throw new Error('Tenant ativo não encontrado.')
|
||||
sQuery = supabase
|
||||
.from('subscriptions')
|
||||
.select(`id, tenant_id, user_id, plan_id, plan_key, interval, status,
|
||||
provider, source, started_at, current_period_start,
|
||||
current_period_end, created_at, updated_at`)
|
||||
.eq('tenant_id', tid)
|
||||
.eq('status', 'active')
|
||||
// ✅ created_at é mais confiável que updated_at em assinaturas manuais
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
])
|
||||
|
||||
if (pRes.error) throw pRes.error
|
||||
if (fRes.error) throw fRes.error
|
||||
if (pfRes.error) throw pfRes.error
|
||||
|
||||
// ✅ subscription pode ser null sem quebrar a página
|
||||
if (sRes.error) {
|
||||
console.warn('[Upgrade] erro ao buscar subscription:', sRes.error)
|
||||
}
|
||||
|
||||
plans.value = pRes.data || []
|
||||
features.value = fRes.data || []
|
||||
planFeatures.value = pfRes.data || []
|
||||
subscription.value = sRes.data || null
|
||||
const [pRes, fRes, pfRes, sRes, ppRes] = await Promise.all([
|
||||
pQuery,
|
||||
supabase.from('features').select('id, key, name, descricao').order('key', { ascending: true }),
|
||||
supabase.from('plan_features').select('plan_id, feature_id'),
|
||||
sQuery,
|
||||
supabase
|
||||
.from('plan_prices')
|
||||
.select('plan_id, currency, interval, amount_cents, is_active, active_from, active_to')
|
||||
.eq('is_active', true)
|
||||
.lte('active_from', nowIso)
|
||||
.or(`active_to.is.null,active_to.gte.${nowIso}`)
|
||||
.order('active_from', { ascending: false })
|
||||
])
|
||||
|
||||
// pode remover esses logs depois
|
||||
console.groupCollapsed('[Upgrade] fetchAll')
|
||||
console.log('tenantId:', tid)
|
||||
console.log('subscription:', subscription.value)
|
||||
console.log('currentPlanKey:', currentPlanKey.value)
|
||||
console.groupEnd()
|
||||
if (pRes.error) throw pRes.error
|
||||
if (fRes.error) throw fRes.error
|
||||
if (pfRes.error) throw pfRes.error
|
||||
if (ppRes.error) throw ppRes.error
|
||||
if (sRes.error) console.warn('[Upgrade] erro ao buscar subscription:', sRes.error)
|
||||
|
||||
plans.value = pRes.data || []
|
||||
features.value = fRes.data || []
|
||||
planFeatures.value = pfRes.data || []
|
||||
subscription.value = sRes.data || null
|
||||
prices.value = ppRes.data || []
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 5000 })
|
||||
@@ -216,46 +245,42 @@ async function fetchAll () {
|
||||
}
|
||||
|
||||
async function changePlan (targetPlanId) {
|
||||
if (!targetPlanId || upgrading.value) return
|
||||
|
||||
if (!subscription.value?.id) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Sem assinatura ativa',
|
||||
detail: 'Não encontrei uma assinatura ativa para este tenant. Ative via pagamento manual primeiro.',
|
||||
life: 4500
|
||||
detail: 'Não encontrei uma assinatura ativa. Vá em "Assinatura" para ativar/criar um plano.',
|
||||
life: 5200
|
||||
})
|
||||
return
|
||||
}
|
||||
if (!targetPlanId) return
|
||||
if (upgrading.value) return
|
||||
|
||||
upgrading.value = true
|
||||
try {
|
||||
const tid = tenantId.value
|
||||
if (!tid) throw new Error('Tenant ativo não encontrado.')
|
||||
if (String(subscription.value.plan_id) === String(targetPlanId)) return
|
||||
|
||||
const current = subscription.value.plan_id
|
||||
if (current === targetPlanId) return
|
||||
|
||||
// ✅ usa o mesmo RPC do seu painel SaaS (transação + histórico)
|
||||
const { data, error } = await supabase.rpc('change_subscription_plan', {
|
||||
p_subscription_id: subscription.value.id,
|
||||
p_new_plan_id: targetPlanId
|
||||
})
|
||||
if (error) throw error
|
||||
|
||||
// atualiza estado local
|
||||
subscription.value.plan_id = data?.plan_id || targetPlanId
|
||||
subscription.value.plan_id = data?.plan_id || targetPlanId
|
||||
subscription.value.plan_key = data?.plan_key || planKeyById(subscription.value.plan_id) || subscription.value.plan_key
|
||||
|
||||
// ✅ recarrega entitlements (sem reload)
|
||||
// (importante pra refletir o plano imediatamente)
|
||||
entitlementsStore.clear?.()
|
||||
|
||||
// seu store tem loadForTenant no guard; se existir aqui também, use primeiro
|
||||
if (typeof entitlementsStore.loadForTenant === 'function') {
|
||||
await entitlementsStore.loadForTenant(tid, { force: true })
|
||||
} else if (typeof entitlementsStore.fetch === 'function') {
|
||||
await entitlementsStore.fetch(tid, { force: true })
|
||||
// ✅ recarrega entitlements do contexto correto
|
||||
if (isTherapist.value) {
|
||||
const uid = userId.value
|
||||
if (uid && typeof entitlementsStore.loadForUser === 'function') {
|
||||
await entitlementsStore.loadForUser(uid, { force: true })
|
||||
}
|
||||
} else {
|
||||
const tid = tenantId.value
|
||||
if (tid && typeof entitlementsStore.loadForTenant === 'function') {
|
||||
await entitlementsStore.loadForTenant(tid, { force: true })
|
||||
}
|
||||
}
|
||||
|
||||
toast.add({
|
||||
@@ -265,11 +290,7 @@ async function changePlan (targetPlanId) {
|
||||
life: 3000
|
||||
})
|
||||
|
||||
// ✅ garante consistência (principalmente se RPC mexer em mais campos)
|
||||
await fetchAll()
|
||||
|
||||
// ✅ dispara o guard novamente: se o usuário perdeu acesso a uma rota PRO,
|
||||
// ele deve ser redirecionado automaticamente.
|
||||
await revalidateCurrentRoute()
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 5000 })
|
||||
@@ -279,28 +300,21 @@ async function changePlan (targetPlanId) {
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
// ✅ garante que o tenant já foi carregado antes de buscar planos
|
||||
if (!tenantStore.loaded) await tenantStore.loadSessionAndTenant()
|
||||
await fetchAll()
|
||||
})
|
||||
|
||||
// se trocar tenant ativo, recarrega
|
||||
watch(
|
||||
() => tenantId.value,
|
||||
() => {
|
||||
if (tenantId.value) fetchAll()
|
||||
}
|
||||
)
|
||||
watch(() => tenantStore.activeTenantId, () => { fetchAll() })
|
||||
watch(() => tenantStore.user?.id, () => { fetchAll() })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Toast />
|
||||
|
||||
<div class="p-4 md:p-6 lg:p-8">
|
||||
<!-- HERO CONCEITUAL -->
|
||||
<div class="mb-6 overflow-hidden rounded-[2rem] border border-[var(--surface-border)] bg-[var(--surface-card)]">
|
||||
<!-- HERO -->
|
||||
<div class="mb-5 overflow-hidden rounded-[2rem] border border-[var(--surface-border)] bg-[var(--surface-card)]">
|
||||
<div class="relative p-5 md:p-7">
|
||||
<!-- blobs sutis -->
|
||||
<div class="pointer-events-none absolute inset-0 opacity-80">
|
||||
<div class="absolute -top-20 -right-24 h-80 w-80 rounded-full bg-indigo-400/10 blur-3xl" />
|
||||
<div class="absolute top-12 -left-24 h-96 w-96 rounded-full bg-emerald-400/10 blur-3xl" />
|
||||
@@ -308,116 +322,112 @@ watch(
|
||||
</div>
|
||||
|
||||
<div class="relative flex flex-col gap-4">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="flex items-start justify-between gap-3 flex-wrap">
|
||||
<div class="min-w-0">
|
||||
<div class="text-2xl md:text-3xl font-semibold leading-tight">
|
||||
Atualize seu plano
|
||||
</div>
|
||||
<div class="text-2xl md:text-3xl font-semibold leading-tight">Atualize seu plano</div>
|
||||
<div class="mt-1 text-sm md:text-base text-[var(--text-color-secondary)]">
|
||||
Tenant ativo:
|
||||
<b>{{ tenantId || '—' }}</b>
|
||||
Contexto: <b>{{ isTherapist ? 'Terapeuta' : 'Clínica' }}</b>
|
||||
<span class="mx-2 opacity-50">•</span>
|
||||
Você está no plano:
|
||||
<b>{{ currentPlanKey || '—' }}</b>
|
||||
Plano atual: <b>{{ currentPlanKey || '—' }}</b>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<Button label="Voltar" icon="pi pi-arrow-left" severity="secondary" outlined @click="goBack" />
|
||||
<Button label="Assinatura" icon="pi pi-credit-card" severity="secondary" outlined @click="goBilling" />
|
||||
<Button label="Recarregar" icon="pi pi-refresh" severity="secondary" outlined :loading="loading" @click="fetchAll" />
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<Button label="Voltar" icon="pi pi-arrow-left" severity="secondary" outlined :disabled="upgrading" @click="goBack" />
|
||||
<Button label="Assinatura" icon="pi pi-credit-card" severity="secondary" outlined :disabled="upgrading" @click="goBilling" />
|
||||
<Button label="Recarregar" icon="pi pi-refresh" severity="secondary" outlined :loading="loading" :disabled="upgrading" @click="fetchAll" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- BLOCO: RECURSO BLOQUEADO -->
|
||||
<!-- recurso bloqueado -->
|
||||
<div
|
||||
v-if="requestedFeatureLabel"
|
||||
class="relative overflow-hidden rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] p-4"
|
||||
>
|
||||
<div class="absolute inset-0 opacity-60 pointer-events-none">
|
||||
<div class="absolute -top-10 -right-12 h-40 w-40 rounded-full bg-amber-400/10 blur-2xl" />
|
||||
<div class="absolute -bottom-10 left-16 h-40 w-40 rounded-full bg-rose-400/10 blur-2xl" />
|
||||
</div>
|
||||
|
||||
<div class="relative flex flex-col md:flex-row md:items-center md:justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-2">
|
||||
<Tag severity="warning" value="Recurso bloqueado" />
|
||||
<div class="font-semibold truncate">
|
||||
{{ requestedFeatureLabel }}
|
||||
</div>
|
||||
<div class="font-semibold truncate">{{ requestedFeatureLabel }}</div>
|
||||
</div>
|
||||
<div class="mt-1 text-sm text-[var(--text-color-secondary)]">
|
||||
Esse recurso depende do plano que inclui a feature <b>{{ requestedFeature }}</b>.
|
||||
Esse recurso depende da feature <b>{{ requestedFeature }}</b>.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<Button
|
||||
label="Ver planos"
|
||||
icon="pi pi-arrow-down"
|
||||
severity="secondary"
|
||||
outlined
|
||||
@click="() => document.getElementById('plans-grid')?.scrollIntoView({ behavior: 'smooth', block: 'start' })"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
label="Ver planos"
|
||||
icon="pi pi-arrow-down"
|
||||
severity="secondary"
|
||||
outlined
|
||||
@click="() => document.getElementById('plans-grid')?.scrollIntoView({ behavior: 'smooth', block: 'start' })"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text-xs md:text-sm text-[var(--text-color-secondary)]">
|
||||
A diferença entre “ter uma agenda” e “ter um sistema” mora nos detalhes.
|
||||
<!-- busca + intervalo -->
|
||||
<div class="flex flex-col md:flex-row md:items-end md:justify-between gap-3">
|
||||
<div class="w-full md:w-[420px]">
|
||||
<FloatLabel variant="on" class="w-full">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-search" />
|
||||
<InputText v-model="q" id="upgrade_search" class="w-full pr-10" variant="filled" :disabled="loading || upgrading" />
|
||||
</IconField>
|
||||
<label for="upgrade_search">Buscar plano...</label>
|
||||
</FloatLabel>
|
||||
</div>
|
||||
<div class="flex flex-col items-start md:items-end gap-2">
|
||||
<small class="text-[var(--text-color-secondary)]">Exibição de preço</small>
|
||||
<SelectButton v-model="billingInterval" :options="intervalOptions" optionLabel="label" optionValue="value" :disabled="loading || upgrading" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- PLANOS (DINÂMICOS) -->
|
||||
<!-- PLANOS -->
|
||||
<div id="plans-grid" class="grid grid-cols-12 gap-4 md:gap-6">
|
||||
<div v-for="p in sortedPlans" :key="p.id" class="col-span-12 lg:col-span-6">
|
||||
<!-- card destaque pro PRO -->
|
||||
<div
|
||||
:id="p.key === 'pro' ? 'plan-pro' : null"
|
||||
:class="p.key === 'pro'
|
||||
:class="String(p.key).toLowerCase() === 'pro'
|
||||
? 'relative overflow-hidden rounded-[1.75rem] border border-primary/40 bg-[var(--surface-card)]'
|
||||
: ''"
|
||||
: 'relative overflow-hidden rounded-[1.75rem] border border-[var(--surface-border)] bg-[var(--surface-card)]'"
|
||||
>
|
||||
<div v-if="p.key === 'pro'" class="pointer-events-none absolute inset-0 opacity-80">
|
||||
<div v-if="String(p.key).toLowerCase() === 'pro'" class="pointer-events-none absolute inset-0 opacity-80">
|
||||
<div class="absolute -top-24 -right-28 h-96 w-96 rounded-full bg-primary/10 blur-3xl" />
|
||||
<div class="absolute -bottom-28 left-12 h-96 w-96 rounded-full bg-emerald-400/10 blur-3xl" />
|
||||
</div>
|
||||
|
||||
<Card :class="p.key === 'pro' ? 'relative border-0' : 'overflow-hidden'">
|
||||
<Card class="relative border-0">
|
||||
<template #title>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<i :class="p.key === 'pro' ? 'pi pi-sparkles opacity-80' : 'pi pi-leaf opacity-70'" />
|
||||
<i :class="String(p.key).toLowerCase() === 'pro' ? 'pi pi-sparkles opacity-80' : 'pi pi-leaf opacity-70'" />
|
||||
<span class="text-xl font-semibold">Plano {{ String(p.key || '').toUpperCase() }}</span>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<Tag v-if="currentPlanId === p.id" value="Atual" severity="secondary" />
|
||||
<Tag v-else-if="p.key === 'pro'" value="Recomendado" severity="success" />
|
||||
<Tag v-else-if="String(p.key).toLowerCase() === 'pro'" value="Recomendado" severity="success" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #subtitle>
|
||||
<span v-if="p.key === 'free'">O essencial para começar, sem travar seu fluxo.</span>
|
||||
<span v-else-if="p.key === 'pro'">Para quem quer automatizar, reduzir ruído e ganhar previsibilidade.</span>
|
||||
<span v-else>Plano personalizado: {{ p.key }}</span>
|
||||
<div class="flex items-center justify-between gap-3 flex-wrap">
|
||||
<span class="text-[var(--text-color-secondary)]">
|
||||
<template v-if="String(p.key).toLowerCase() === 'free'">O essencial para começar, sem travar seu fluxo.</template>
|
||||
<template v-else-if="String(p.key).toLowerCase() === 'pro'">Para automatizar, reduzir ruído e ganhar previsibilidade.</template>
|
||||
<template v-else>Plano: {{ p.key }}</template>
|
||||
</span>
|
||||
<span class="text-sm font-semibold">{{ priceLabelForPlan(p.id) }}</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #content>
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] p-4">
|
||||
<ul class="list-none p-0 m-0 flex flex-col gap-3">
|
||||
<li v-for="(b, i) in planBenefits(p.id)" :key="i" class="flex items-start gap-2">
|
||||
<i
|
||||
:class="b.ok ? 'pi pi-check-circle text-emerald-500' : 'pi pi-times-circle opacity-50'"
|
||||
class="mt-0.5"
|
||||
/>
|
||||
<span :class="b.ok ? '' : 'text-[var(--text-color-secondary)]'">
|
||||
{{ b.text }}
|
||||
</span>
|
||||
<i :class="b.ok ? 'pi pi-check-circle text-emerald-500' : 'pi pi-times-circle opacity-50'" class="mt-0.5" />
|
||||
<span :class="b.ok ? '' : 'text-[var(--text-color-secondary)]'">{{ b.text }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
@@ -434,7 +444,6 @@ watch(
|
||||
:disabled="upgrading || loading"
|
||||
@click="changePlan(p.id)"
|
||||
/>
|
||||
|
||||
<Button
|
||||
v-else
|
||||
label="Você já está neste plano"
|
||||
@@ -444,20 +453,22 @@ watch(
|
||||
class="w-full"
|
||||
disabled
|
||||
/>
|
||||
|
||||
<Button
|
||||
v-if="p.key !== 'free'"
|
||||
v-if="String(p.key).toLowerCase() !== 'free'"
|
||||
label="Falar com suporte"
|
||||
icon="pi pi-comments"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="w-full"
|
||||
:disabled="upgrading"
|
||||
@click="contactSupport"
|
||||
/>
|
||||
|
||||
<div class="text-center text-xs text-[var(--text-color-secondary)]">
|
||||
Cancele quando quiser. Sem burocracia.
|
||||
</div>
|
||||
<div v-if="!subscription?.id" class="text-center text-xs text-amber-500">
|
||||
⚠ Sem assinatura ativa — clique em <b>Assinatura</b> para ativar/criar.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -467,7 +478,7 @@ watch(
|
||||
</div>
|
||||
|
||||
<div class="mt-6 text-xs text-[var(--text-color-secondary)]">
|
||||
Observação: alguns recursos PRO podem depender de configuração inicial (ex.: SMS exige provedor).
|
||||
Alguns recursos PRO podem depender de configuração inicial (ex.: SMS exige provedor).
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
591
src/views/pages/clinic/clinic/ClinicFeaturesPage.vue
Normal file
591
src/views/pages/clinic/clinic/ClinicFeaturesPage.vue
Normal file
@@ -0,0 +1,591 @@
|
||||
<!-- src/views/pages/admin/ClinicTypesPage.vue -->
|
||||
<script setup>
|
||||
import { computed, onMounted, ref, watch, nextTick } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
|
||||
import ModuleRow from '@/features/clinic/components/ModuleRow.vue'
|
||||
|
||||
import { useTenantStore } from '@/stores/tenantStore'
|
||||
import { useTenantFeaturesStore } from '@/stores/tenantFeaturesStore'
|
||||
import { useMenuStore } from '@/stores/menuStore'
|
||||
|
||||
const toast = useToast()
|
||||
const route = useRoute()
|
||||
|
||||
const tenantStore = useTenantStore()
|
||||
const tf = useTenantFeaturesStore()
|
||||
const menuStore = useMenuStore()
|
||||
|
||||
const savingKey = ref(null)
|
||||
const applyingPreset = ref(false)
|
||||
|
||||
// evita cliques enquanto o contexto inicial ainda tá montando
|
||||
const booting = ref(true)
|
||||
|
||||
// guarda features que o plano bloqueou (pra não ficar “clicando e errando”)
|
||||
const planDenied = ref(new Set())
|
||||
|
||||
const tenantId = computed(() =>
|
||||
tenantStore.activeTenantId ||
|
||||
tenantStore.tenantId ||
|
||||
tenantStore.currentTenantId ||
|
||||
tenantStore.tenant?.id ||
|
||||
null
|
||||
)
|
||||
|
||||
const role = computed(() => tenantStore.activeRole || tenantStore.role || null)
|
||||
|
||||
// ✅ Somente owners/admins da clínica podem alterar features.
|
||||
// Terapeutas enxergam a página em modo somente-leitura (sem toggles, sem presets).
|
||||
const isOwner = computed(() =>
|
||||
role.value === 'owner' || role.value === 'admin'
|
||||
)
|
||||
|
||||
const loading = computed(() => tf.loading || tenantStore.loading || booting.value)
|
||||
|
||||
const tenantReady = computed(() => !!tenantId.value && tenantStore.loaded)
|
||||
|
||||
function isOn (key) {
|
||||
if (!tenantId.value) return false
|
||||
try { return !!tf.isEnabled(key, tenantId.value) } catch { return false }
|
||||
}
|
||||
|
||||
function labelOf (key) {
|
||||
if (key === 'patients') return 'Pacientes'
|
||||
if (key === 'shared_reception') return 'Recepção / Secretária'
|
||||
if (key === 'rooms') return 'Salas / Coworking'
|
||||
if (key === 'intake_public') return 'Link externo de cadastro'
|
||||
return key
|
||||
}
|
||||
|
||||
function isPlanDeniedError (e) {
|
||||
const msg = String(e?.message || e || '')
|
||||
return msg.toLowerCase().includes('não permitida') && msg.toLowerCase().includes('plano')
|
||||
}
|
||||
|
||||
function markPlanDenied (key, e) {
|
||||
if (!key) return
|
||||
if (!isPlanDeniedError(e)) return
|
||||
const s = new Set(planDenied.value)
|
||||
s.add(key)
|
||||
planDenied.value = s
|
||||
}
|
||||
|
||||
function clearPlanDenied () {
|
||||
planDenied.value = new Set()
|
||||
}
|
||||
|
||||
function isLocked (key) {
|
||||
return (
|
||||
!isOwner.value ||
|
||||
!tenantReady.value ||
|
||||
loading.value ||
|
||||
applyingPreset.value ||
|
||||
!!savingKey.value ||
|
||||
planDenied.value.has(key)
|
||||
)
|
||||
}
|
||||
|
||||
// ===============================
|
||||
// 🧠 Menu refresh (debounced)
|
||||
// evita "menu sumindo" ao resetar durante loading
|
||||
// ===============================
|
||||
let menuRefreshT = null
|
||||
function requestMenuRefresh () {
|
||||
if (menuRefreshT) clearTimeout(menuRefreshT)
|
||||
menuRefreshT = setTimeout(() => {
|
||||
if (tf.loading || tenantStore.loading || booting.value) {
|
||||
return requestMenuRefresh()
|
||||
}
|
||||
if (typeof menuStore.reset === 'function') menuStore.reset()
|
||||
}, 150)
|
||||
}
|
||||
|
||||
/**
|
||||
* ✅ Recalcular menu SEM router.replace().
|
||||
* O menu some quando o reset acontece enquanto stores ainda carregam.
|
||||
*/
|
||||
async function afterFeaturesChanged () {
|
||||
if (!tenantId.value) return
|
||||
|
||||
// ✅ refresh suave (evita “pisca vazio”)
|
||||
await tf.fetchForTenant(tenantId.value, { force: false })
|
||||
|
||||
// ✅ nunca navegar/replace aqui
|
||||
requestMenuRefresh()
|
||||
|
||||
await nextTick()
|
||||
}
|
||||
|
||||
async function reload () {
|
||||
if (!tenantId.value) return
|
||||
clearPlanDenied()
|
||||
|
||||
await tf.fetchForTenant(tenantId.value, { force: true })
|
||||
requestMenuRefresh()
|
||||
|
||||
toast.add({
|
||||
severity: 'info',
|
||||
summary: 'Atualizado',
|
||||
detail: 'Módulos recarregados.',
|
||||
life: 2000
|
||||
})
|
||||
}
|
||||
|
||||
async function toggle (key) {
|
||||
if (!isOwner.value) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Acesso restrito',
|
||||
detail: 'Apenas o administrador da clínica pode alterar módulos.',
|
||||
life: 3000
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (!tenantId.value) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Sem tenant ativo',
|
||||
detail: 'Selecione/ative um tenant primeiro.',
|
||||
life: 2500
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (planDenied.value.has(key)) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Indisponível no plano',
|
||||
detail: `${labelOf(key)} não está disponível no plano atual.`,
|
||||
life: 2800
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (savingKey.value) return
|
||||
savingKey.value = key
|
||||
|
||||
try {
|
||||
const next = !isOn(key)
|
||||
|
||||
await tf.setForTenant(tenantId.value, key, next)
|
||||
await afterFeaturesChanged()
|
||||
|
||||
toast.add({
|
||||
severity: 'success',
|
||||
summary: 'Atualizado',
|
||||
detail: `${labelOf(key)}: ${next ? 'Ativado' : 'Desativado'}`,
|
||||
life: 2500
|
||||
})
|
||||
} catch (e) {
|
||||
markPlanDenied(key, e)
|
||||
|
||||
toast.add({
|
||||
severity: isPlanDeniedError(e) ? 'warn' : 'error',
|
||||
summary: isPlanDeniedError(e) ? 'Bloqueado pelo plano' : 'Erro',
|
||||
detail: e?.message || 'Falha ao atualizar módulo',
|
||||
life: 3800
|
||||
})
|
||||
} finally {
|
||||
savingKey.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function applyPreset (preset) {
|
||||
if (!isOwner.value) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Acesso restrito',
|
||||
detail: 'Apenas o administrador da clínica pode aplicar presets.',
|
||||
life: 3000
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (!tenantId.value) return
|
||||
if (applyingPreset.value) return
|
||||
|
||||
clearPlanDenied()
|
||||
applyingPreset.value = true
|
||||
|
||||
try {
|
||||
const map = {
|
||||
coworking: {
|
||||
patients: false,
|
||||
shared_reception: false,
|
||||
rooms: true,
|
||||
intake_public: false
|
||||
},
|
||||
reception: {
|
||||
patients: false,
|
||||
shared_reception: true,
|
||||
rooms: false,
|
||||
intake_public: false
|
||||
},
|
||||
full: {
|
||||
patients: true,
|
||||
shared_reception: true,
|
||||
rooms: true,
|
||||
intake_public: true
|
||||
}
|
||||
}
|
||||
|
||||
const cfg = map[preset]
|
||||
if (!cfg) return
|
||||
|
||||
for (const [k, v] of Object.entries(cfg)) {
|
||||
try {
|
||||
await tf.setForTenant(tenantId.value, k, v)
|
||||
} catch (e) {
|
||||
markPlanDenied(k, e)
|
||||
toast.add({
|
||||
severity: isPlanDeniedError(e) ? 'warn' : 'error',
|
||||
summary: isPlanDeniedError(e) ? 'Bloqueado pelo plano' : 'Erro',
|
||||
detail: `${labelOf(k)}: ${e?.message || 'falha ao aplicar'}`,
|
||||
life: 4200
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await afterFeaturesChanged()
|
||||
|
||||
toast.add({
|
||||
severity: 'success',
|
||||
summary: 'Preset aplicado',
|
||||
detail: 'Configuração atualizada.',
|
||||
life: 2500
|
||||
})
|
||||
} catch (e) {
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: 'Erro',
|
||||
detail: e?.message || 'Falha ao aplicar preset',
|
||||
life: 3500
|
||||
})
|
||||
} finally {
|
||||
applyingPreset.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Carrega tenant/session se necessário
|
||||
onMounted(async () => {
|
||||
try {
|
||||
if (!tenantStore.loaded && !tenantStore.loading) {
|
||||
await tenantStore.loadSessionAndTenant()
|
||||
}
|
||||
} finally {
|
||||
// o watch do tenantId fará o fetch; aqui só destrava a tela
|
||||
booting.value = false
|
||||
}
|
||||
})
|
||||
|
||||
// Busca features sempre que o tenant ficar disponível (e no mount)
|
||||
watch(
|
||||
() => tenantId.value,
|
||||
async (id) => {
|
||||
if (!id) return
|
||||
|
||||
booting.value = true
|
||||
clearPlanDenied()
|
||||
|
||||
try {
|
||||
// ✅ não force no mount para evitar “pisca”
|
||||
await tf.fetchForTenant(id, { force: false })
|
||||
|
||||
// ✅ reset só quando estiver estável (debounced)
|
||||
requestMenuRefresh()
|
||||
|
||||
await nextTick()
|
||||
} catch (e) {
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: 'Erro ao carregar módulos',
|
||||
detail: e?.message || 'Falha ao buscar tenant_features',
|
||||
life: 4000
|
||||
})
|
||||
} finally {
|
||||
booting.value = false
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
// blindagem: se a rota mudar dentro da área admin e o menu tiver resetado,
|
||||
// solicita refresh leve (sem navigation)
|
||||
watch(
|
||||
() => route.fullPath,
|
||||
async () => {
|
||||
requestMenuRefresh()
|
||||
}
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="p-4 md:p-6">
|
||||
<Toast />
|
||||
|
||||
<!-- Header -->
|
||||
<div class="mb-4 overflow-hidden rounded-[2rem] border border-[var(--surface-border)] bg-[var(--surface-card)]">
|
||||
<div class="relative p-5 md:p-7">
|
||||
<!-- blobs sutis -->
|
||||
<div class="pointer-events-none absolute inset-0 opacity-80">
|
||||
<div class="absolute -top-16 -right-20 h-72 w-72 rounded-full bg-indigo-400/10 blur-3xl" />
|
||||
<div class="absolute top-10 -left-24 h-80 w-80 rounded-full bg-emerald-400/10 blur-3xl" />
|
||||
<div class="absolute -bottom-20 right-24 h-72 w-72 rounded-full bg-fuchsia-400/10 blur-3xl" />
|
||||
</div>
|
||||
|
||||
<div class="relative flex flex-col gap-2">
|
||||
<div class="flex items-center justify-between gap-3 flex-wrap">
|
||||
<div class="min-w-0">
|
||||
<h1 class="text-xl md:text-2xl font-semibold leading-tight">Tipos de Clínica</h1>
|
||||
<p class="mt-1 text-sm opacity-80">
|
||||
Ative/desative recursos por clínica. Isso controla menu, rotas (guard) e acesso no banco (RLS).
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 flex items-center gap-2">
|
||||
<Button
|
||||
label="Recarregar"
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:loading="loading"
|
||||
:disabled="applyingPreset || !!savingKey"
|
||||
@click="reload"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-2 flex flex-wrap items-center gap-2 text-xs opacity-80">
|
||||
<span class="inline-flex items-center gap-2 rounded-full border border-[var(--surface-border)] px-3 py-1">
|
||||
<i class="pi pi-building" />
|
||||
Tenant: <b class="font-mono">{{ tenantId || '—' }}</b>
|
||||
</span>
|
||||
<span class="inline-flex items-center gap-2 rounded-full border border-[var(--surface-border)] px-3 py-1">
|
||||
<i class="pi pi-user" />
|
||||
Role: <b>{{ role || '—' }}</b>
|
||||
</span>
|
||||
|
||||
<span
|
||||
v-if="!tenantReady"
|
||||
class="inline-flex items-center gap-2 rounded-full border border-[var(--surface-border)] px-3 py-1 opacity-70"
|
||||
>
|
||||
<i class="pi pi-spin pi-spinner" />
|
||||
Carregando contexto…
|
||||
</span>
|
||||
|
||||
<span
|
||||
v-else-if="loading"
|
||||
class="inline-flex items-center gap-2 rounded-full border border-[var(--surface-border)] px-3 py-1 opacity-70"
|
||||
>
|
||||
<i class="pi pi-spin pi-spinner" />
|
||||
Atualizando módulos…
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ⚠️ Banner: acesso somente leitura para terapeutas -->
|
||||
<div
|
||||
v-if="!isOwner && tenantReady"
|
||||
class="mb-4 flex items-center gap-3 rounded-[2rem] border border-amber-400/40 bg-amber-400/10 px-5 py-4 text-sm"
|
||||
>
|
||||
<i class="pi pi-lock text-amber-400 text-base shrink-0" />
|
||||
<span class="opacity-90">
|
||||
Você está visualizando as configurações da clínica em <b>modo somente leitura</b>.
|
||||
Apenas o administrador pode ativar ou desativar módulos.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Presets -->
|
||||
<div class="mb-4 grid grid-cols-1 md:grid-cols-3 gap-3">
|
||||
<Card class="rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-semibold">Preset: Coworking</div>
|
||||
<div class="mt-1 text-xs opacity-80">
|
||||
Para aluguel de salas: sem pacientes, com salas.
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="small"
|
||||
label="Aplicar"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:loading="applyingPreset"
|
||||
:disabled="!isOwner || !tenantReady || loading || !!savingKey"
|
||||
@click="applyPreset('coworking')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<Card class="rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-semibold">Preset: Clínica com recepção</div>
|
||||
<div class="mt-1 text-xs opacity-80">
|
||||
Para secretária gerenciar agenda (pacientes opcional).
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="small"
|
||||
label="Aplicar"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:loading="applyingPreset"
|
||||
:disabled="!isOwner || !tenantReady || loading || !!savingKey"
|
||||
@click="applyPreset('reception')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<Card class="rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-semibold">Preset: Clínica completa</div>
|
||||
<div class="mt-1 text-xs opacity-80">
|
||||
Pacientes + recepção + salas (se quiser).
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="small"
|
||||
label="Aplicar"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:loading="applyingPreset"
|
||||
:disabled="!isOwner || !tenantReady || loading || !!savingKey"
|
||||
@click="applyPreset('full')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<!-- Modules -->
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-3">
|
||||
<Card class="rounded-[2rem]">
|
||||
<template #content>
|
||||
<ModuleRow
|
||||
title="Pacientes"
|
||||
desc="Habilita gestão de pacientes por clínica. Todo paciente tem um responsável (therapist)."
|
||||
icon="pi pi-users"
|
||||
:enabled="isOn('patients')"
|
||||
:loading="savingKey === 'patients'"
|
||||
:disabled="isLocked('patients')"
|
||||
@toggle="toggle('patients')"
|
||||
/>
|
||||
<div
|
||||
v-if="planDenied.has('patients')"
|
||||
class="mt-3 text-xs rounded-2xl border border-[var(--surface-border)] p-3 opacity-90"
|
||||
>
|
||||
<i class="pi pi-lock mr-2" />
|
||||
Este módulo foi bloqueado pelo plano atual do tenant.
|
||||
</div>
|
||||
<Divider class="my-4" />
|
||||
<div class="text-xs opacity-80 leading-relaxed">
|
||||
Quando desligado:
|
||||
<ul class="mt-2 list-disc pl-5 space-y-1">
|
||||
<li>Menu “Pacientes” some.</li>
|
||||
<li>Rotas com <span class="font-mono">meta.tenantFeature = 'patients'</span> redirecionam pra cá.</li>
|
||||
<li>RLS bloqueia acesso direto no banco.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<Card class="rounded-[2rem]">
|
||||
<template #content>
|
||||
<ModuleRow
|
||||
title="Recepção / Secretária"
|
||||
desc="Permite um papel de secretária gerenciar a agenda dos profissionais (sem precisar ver tudo do paciente)."
|
||||
icon="pi pi-briefcase"
|
||||
:enabled="isOn('shared_reception')"
|
||||
:loading="savingKey === 'shared_reception'"
|
||||
:disabled="isLocked('shared_reception')"
|
||||
@toggle="toggle('shared_reception')"
|
||||
/>
|
||||
<div
|
||||
v-if="planDenied.has('shared_reception')"
|
||||
class="mt-3 text-xs rounded-2xl border border-[var(--surface-border)] p-3 opacity-90"
|
||||
>
|
||||
<i class="pi pi-lock mr-2" />
|
||||
Este módulo foi bloqueado pelo plano atual do tenant.
|
||||
</div>
|
||||
<Divider class="my-4" />
|
||||
<div class="text-xs opacity-80 leading-relaxed">
|
||||
Observação: este módulo é “produto” (UX + permissões). A base aqui é só o toggle.
|
||||
Depois a gente cria:
|
||||
<ul class="mt-2 list-disc pl-5 space-y-1">
|
||||
<li>role <span class="font-mono">secretary</span> em <span class="font-mono">tenant_members</span></li>
|
||||
<li>policies e telas para a secretária</li>
|
||||
<li>nível de visibilidade do paciente na agenda</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<Card class="rounded-[2rem]">
|
||||
<template #content>
|
||||
<ModuleRow
|
||||
title="Salas / Coworking"
|
||||
desc="Habilita cadastro e reserva de salas/recursos no agendamento."
|
||||
icon="pi pi-building"
|
||||
:enabled="isOn('rooms')"
|
||||
:loading="savingKey === 'rooms'"
|
||||
:disabled="isLocked('rooms')"
|
||||
@toggle="toggle('rooms')"
|
||||
/>
|
||||
<div
|
||||
v-if="planDenied.has('rooms')"
|
||||
class="mt-3 text-xs rounded-2xl border border-[var(--surface-border)] p-3 opacity-90"
|
||||
>
|
||||
<i class="pi pi-lock mr-2" />
|
||||
Este módulo foi bloqueado pelo plano atual do tenant.
|
||||
</div>
|
||||
<Divider class="my-4" />
|
||||
<div class="text-xs opacity-80 leading-relaxed">
|
||||
Isso prepara o terreno para a clínica operar como locação de sala, com agenda vinculando sala + profissional.
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<Card class="rounded-[2rem]">
|
||||
<template #content>
|
||||
<ModuleRow
|
||||
title="Link externo de cadastro"
|
||||
desc="Libera fluxo público de intake/cadastro externo para a clínica."
|
||||
icon="pi pi-link"
|
||||
:enabled="isOn('intake_public')"
|
||||
:loading="savingKey === 'intake_public'"
|
||||
:disabled="isLocked('intake_public')"
|
||||
@toggle="toggle('intake_public')"
|
||||
/>
|
||||
<div
|
||||
v-if="planDenied.has('intake_public')"
|
||||
class="mt-3 text-xs rounded-2xl border border-[var(--surface-border)] p-3 opacity-90"
|
||||
>
|
||||
<i class="pi pi-lock mr-2" />
|
||||
Este módulo foi bloqueado pelo plano atual do tenant.
|
||||
</div>
|
||||
<Divider class="my-4" />
|
||||
<div class="text-xs opacity-80 leading-relaxed">
|
||||
Você já tem páginas de link externo. Isso vira o controle fino: a clínica decide se usa ou não.
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* (sem estilos adicionais por enquanto) */
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
56
src/views/pages/editor/EditorDashboard.vue
Normal file
56
src/views/pages/editor/EditorDashboard.vue
Normal file
@@ -0,0 +1,56 @@
|
||||
<script setup>
|
||||
import NotificationsWidget from '@/components/dashboard/NotificationsWidget.vue';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="card mb-0">
|
||||
<div class="flex justify-between mb-4">
|
||||
<div>
|
||||
<span class="text-primary font-medium">Área</span>
|
||||
<span class="text-muted-color"> do Editor</span>
|
||||
</div>
|
||||
<div class="flex items-center justify-center bg-orange-100 dark:bg-orange-400/10 rounded-border" style="width: 2.5rem; height: 2.5rem">
|
||||
<i class="pi pi-pencil text-orange-500 text-xl!"></i>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-muted-color text-sm mt-0">
|
||||
Crie e gerencie cursos, módulos e conteúdos da plataforma de microlearning.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-12 gap-8">
|
||||
<!-- Estatísticas de conteúdo -->
|
||||
<div class="col-span-12">
|
||||
<div class="card">
|
||||
<div class="flex items-center gap-3 mb-4">
|
||||
<i class="pi pi-book text-orange-500 text-2xl"></i>
|
||||
<span class="font-semibold text-lg">Conteúdo da Plataforma</span>
|
||||
</div>
|
||||
<div class="grid grid-cols-12 gap-4">
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<div class="surface-100 dark:surface-700 rounded-xl p-4 text-center">
|
||||
<div class="text-3xl font-bold text-orange-500 mb-1">0</div>
|
||||
<div class="text-muted-color text-sm">Cursos publicados</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<div class="surface-100 dark:surface-700 rounded-xl p-4 text-center">
|
||||
<div class="text-3xl font-bold text-orange-500 mb-1">0</div>
|
||||
<div class="text-muted-color text-sm">Módulos criados</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<div class="surface-100 dark:surface-700 rounded-xl p-4 text-center">
|
||||
<div class="text-3xl font-bold text-orange-500 mb-1">0</div>
|
||||
<div class="text-muted-color text-sm">Alunos inscritos</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 xl:col-span-6">
|
||||
<NotificationsWidget />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
58
src/views/pages/portal/MinhasSessoes.vue
Normal file
58
src/views/pages/portal/MinhasSessoes.vue
Normal file
@@ -0,0 +1,58 @@
|
||||
<template>
|
||||
<div class="p-4 md:p-6">
|
||||
<!-- HEADER CONCEITUAL -->
|
||||
<div class="mb-6 overflow-hidden rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)]">
|
||||
<div class="relative p-6">
|
||||
|
||||
<!-- blobs sutis -->
|
||||
<div class="pointer-events-none absolute inset-0 opacity-80">
|
||||
<div class="absolute -top-16 -right-16 h-52 w-52 rounded-full bg-indigo-400/10 blur-3xl" />
|
||||
<div class="absolute bottom-0 left-10 h-44 w-44 rounded-full bg-emerald-400/10 blur-3xl" />
|
||||
</div>
|
||||
|
||||
<div class="relative flex items-center gap-4">
|
||||
<div class="grid h-14 w-14 place-items-center rounded-2xl bg-[var(--primary-color)]/10 text-[var(--primary-color)]">
|
||||
<i class="pi pi-calendar text-2xl" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div class="text-2xl font-semibold leading-none">
|
||||
Minhas Sessões
|
||||
</div>
|
||||
<div class="mt-2 text-sm text-color-secondary">
|
||||
Visualize e acompanhe suas sessões agendadas e realizadas.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- CONTEÚDO PLACEHOLDER -->
|
||||
<div class="flex items-center justify-center rounded-2xl border border-dashed border-[var(--surface-border)] bg-[var(--surface-card)] py-16">
|
||||
<div class="text-center max-w-md">
|
||||
|
||||
<div class="mx-auto mb-4 grid h-16 w-16 place-items-center rounded-2xl bg-[var(--primary-color)]/10 text-[var(--primary-color)]">
|
||||
<i class="pi pi-hourglass text-2xl" />
|
||||
</div>
|
||||
|
||||
<div class="text-lg font-semibold">
|
||||
Em desenvolvimento
|
||||
</div>
|
||||
|
||||
<div class="mt-2 text-sm text-color-secondary">
|
||||
A área de acompanhamento das sessões será exibida aqui.
|
||||
Em breve você poderá visualizar histórico, próximas sessões e detalhes clínicos.
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
// Placeholder simples — lógica será implementada futuramente.
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* mantém padrão visual consistente */
|
||||
</style>
|
||||
@@ -1,9 +0,0 @@
|
||||
<template>
|
||||
<div class="p-4">
|
||||
<h1>My Appointments</h1>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
// temporary placeholder
|
||||
</script>
|
||||
@@ -1,9 +0,0 @@
|
||||
<template>
|
||||
<div class="p-4">
|
||||
<h1>Add New Appointments</h1>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
// temporary placeholder
|
||||
</script>
|
||||
@@ -1,50 +1,109 @@
|
||||
<!-- src/views/pages/public/AcceptInvitePage.vue -->
|
||||
<template>
|
||||
<div class="min-h-screen flex items-center justify-center p-6 bg-[var(--surface-ground)] text-[var(--text-color)]">
|
||||
<div class="w-full max-w-lg rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] p-6 shadow-sm">
|
||||
<h1 class="text-xl font-semibold mb-2">Aceitar convite</h1>
|
||||
<p class="text-sm opacity-80 mb-6">
|
||||
Vamos validar seu convite e ativar seu acesso ao tenant.
|
||||
</p>
|
||||
<Toast />
|
||||
|
||||
<div v-if="state.loading" class="text-sm">
|
||||
Processando convite…
|
||||
</div>
|
||||
<div class="w-full max-w-lg overflow-hidden rounded-[2rem] border border-[var(--surface-border)] bg-[var(--surface-card)] shadow-sm">
|
||||
<!-- Header / Hero -->
|
||||
<div class="relative p-6">
|
||||
<div class="pointer-events-none absolute inset-0 opacity-80">
|
||||
<div class="absolute -top-16 -right-16 h-64 w-64 rounded-full bg-indigo-400/10 blur-3xl" />
|
||||
<div class="absolute top-10 -left-20 h-64 w-64 rounded-full bg-emerald-400/10 blur-3xl" />
|
||||
<div class="absolute -bottom-16 right-10 h-64 w-64 rounded-full bg-fuchsia-400/10 blur-3xl" />
|
||||
</div>
|
||||
|
||||
<div v-else-if="state.success" class="space-y-3">
|
||||
<div class="text-sm">
|
||||
✅ Convite aceito com sucesso. Redirecionando…
|
||||
<div class="relative">
|
||||
<h1 class="text-xl font-semibold mb-2">Aceitar convite</h1>
|
||||
<p class="text-sm opacity-80">
|
||||
Vamos validar seu convite e ativar seu acesso ao tenant.
|
||||
</p>
|
||||
|
||||
<div class="mt-3 flex flex-wrap items-center gap-2 text-xs opacity-80">
|
||||
<span class="inline-flex items-center gap-2 rounded-full border border-[var(--surface-border)] px-3 py-1">
|
||||
<i class="pi pi-ticket" />
|
||||
Token:
|
||||
<b class="font-mono">{{ shortToken }}</b>
|
||||
</span>
|
||||
|
||||
<span
|
||||
v-if="state.loading"
|
||||
class="inline-flex items-center gap-2 rounded-full border border-[var(--surface-border)] px-3 py-1"
|
||||
>
|
||||
<i class="pi pi-spin pi-spinner" />
|
||||
Processando…
|
||||
</span>
|
||||
|
||||
<span
|
||||
v-else-if="state.success"
|
||||
class="inline-flex items-center gap-2 rounded-full border border-[var(--surface-border)] px-3 py-1"
|
||||
>
|
||||
<i class="pi pi-check" />
|
||||
Confirmado
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="state.error" class="space-y-4">
|
||||
<div class="rounded-xl border border-red-500/30 bg-red-500/10 p-4 text-sm">
|
||||
<div class="font-semibold mb-1">Não foi possível aceitar o convite</div>
|
||||
<div class="opacity-90">{{ state.error }}</div>
|
||||
<!-- Body -->
|
||||
<div class="p-6 border-t border-[var(--surface-border)]">
|
||||
<!-- Loading -->
|
||||
<div v-if="state.loading" class="text-sm">
|
||||
Processando convite…
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
class="px-4 py-2 rounded-xl border border-[var(--surface-border)] hover:opacity-90 text-sm"
|
||||
@click="retry"
|
||||
>
|
||||
Tentar novamente
|
||||
</button>
|
||||
|
||||
<button
|
||||
class="px-4 py-2 rounded-xl bg-[var(--primary-color)] text-[var(--primary-color-text)] hover:opacity-90 text-sm"
|
||||
@click="goLogin"
|
||||
>
|
||||
Ir para login
|
||||
</button>
|
||||
<!-- Success -->
|
||||
<div v-else-if="state.success" class="space-y-3">
|
||||
<div class="text-sm">
|
||||
✅ Convite aceito com sucesso. Redirecionando…
|
||||
</div>
|
||||
<div class="text-xs opacity-70">
|
||||
Se você não for redirecionado, clique abaixo.
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<Button
|
||||
label="Ir para o painel"
|
||||
icon="pi pi-arrow-right"
|
||||
@click="goAdmin"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="text-xs opacity-70">
|
||||
Se você recebeu um convite, confirme se está logado com o mesmo e-mail do convite.
|
||||
</p>
|
||||
</div>
|
||||
<!-- Error -->
|
||||
<div v-else-if="state.error" class="space-y-4">
|
||||
<div class="rounded-2xl border border-red-500/30 bg-red-500/10 p-4 text-sm">
|
||||
<div class="font-semibold mb-1">Não foi possível aceitar o convite</div>
|
||||
<div class="opacity-90">{{ state.error }}</div>
|
||||
|
||||
<div v-else class="text-sm opacity-80">
|
||||
Preparando…
|
||||
<div v-if="state.debugDetails" class="mt-3 text-xs opacity-70">
|
||||
<div class="font-semibold mb-1">Detalhes (debug)</div>
|
||||
<pre class="m-0 whitespace-pre-wrap break-words">{{ state.debugDetails }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<Button
|
||||
label="Tentar novamente"
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
@click="retry"
|
||||
/>
|
||||
<Button
|
||||
label="Ir para login"
|
||||
icon="pi pi-sign-in"
|
||||
@click="goLogin"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p class="text-xs opacity-70 leading-relaxed">
|
||||
Se você recebeu um convite, confirme se está logado com o mesmo e-mail do convite.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Idle -->
|
||||
<div v-else class="text-sm opacity-80">
|
||||
Preparando…
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -54,6 +113,8 @@
|
||||
import { reactive, onMounted, computed } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
import { useTenantStore } from '@/stores/tenantStore'
|
||||
|
||||
@@ -76,12 +137,14 @@ function clearPendingToken () {
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
const tenantStore = useTenantStore()
|
||||
|
||||
const state = reactive({
|
||||
loading: true,
|
||||
success: false,
|
||||
error: ''
|
||||
error: '',
|
||||
debugDetails: '' // mantém vazio por padrão (pode ativar quando precisar)
|
||||
})
|
||||
|
||||
const tokenFromQuery = computed(() => {
|
||||
@@ -89,6 +152,15 @@ const tokenFromQuery = computed(() => {
|
||||
return typeof t === 'string' ? t.trim() : ''
|
||||
})
|
||||
|
||||
const tokenEffective = computed(() => tokenFromQuery.value || readPendingToken() || '')
|
||||
|
||||
const shortToken = computed(() => {
|
||||
const t = tokenEffective.value
|
||||
if (!t) return '—'
|
||||
if (t.length <= 14) return t
|
||||
return `${t.slice(0, 8)}…${t.slice(-4)}`
|
||||
})
|
||||
|
||||
function isUuid (v) {
|
||||
// UUID v1–v5 (aceita maiúsculas/minúsculas)
|
||||
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v)
|
||||
@@ -97,29 +169,39 @@ function isUuid (v) {
|
||||
function friendlyError (err) {
|
||||
const msg = (err?.message || err || '').toString()
|
||||
|
||||
// Ajuste esses “match” conforme as mensagens/raises do seu SQL.
|
||||
if (/expired|expirad/i.test(msg)) return 'Este convite expirou. Peça para a clínica reenviar o convite.'
|
||||
if (/invalid|inval/i.test(msg)) return 'Token inválido. Verifique se você copiou o link corretamente.'
|
||||
if (/not found|não encontrado|nao encontrado/i.test(msg)) return 'Convite não encontrado ou já utilizado.'
|
||||
if (/not found|não encontrado|nao encontrado|used|utilizad/i.test(msg)) return 'Convite não encontrado ou já utilizado.'
|
||||
if (/email/i.test(msg) && /mismatch|diferent|different|bate|match/i.test(msg)) {
|
||||
return 'Você está logado com um e-mail diferente do convite. Faça login com o e-mail correto.'
|
||||
}
|
||||
// cobre Postgres raise not_authenticated (P0001) e mensagens de JWT
|
||||
if (/not_authenticated|not authenticated|jwt|auth/i.test(msg)) {
|
||||
return 'Você precisa estar logado para aceitar este convite.'
|
||||
}
|
||||
return 'Não foi possível concluir o aceite. Tente novamente ou peça para reenviar o convite.'
|
||||
}
|
||||
|
||||
function safeRpcError (rpcError) {
|
||||
const raw = (rpcError?.message || '').toString().trim()
|
||||
// Por padrão: mensagem amigável. Se quiser ver a “real”, coloque em debugDetails.
|
||||
const friendly = friendlyError(rpcError)
|
||||
return { friendly, raw }
|
||||
}
|
||||
|
||||
async function goAdmin () {
|
||||
await router.replace('/admin')
|
||||
}
|
||||
|
||||
async function goLogin () {
|
||||
const token = tokenFromQuery.value || readPendingToken()
|
||||
const token = tokenEffective.value
|
||||
if (token) persistPendingToken(token)
|
||||
|
||||
// ✅ garante troca de conta
|
||||
await supabase.auth.signOut()
|
||||
// ✅ garante troca de conta (somente quando usuário clica)
|
||||
try {
|
||||
await supabase.auth.signOut()
|
||||
} catch (_) {}
|
||||
|
||||
// ✅ volta para o accept com token (ou com o storage pendente)
|
||||
// (mantém o link “real” para o login conseguir retornar certo)
|
||||
// ✅ volta para o accept com token (ou storage pendente)
|
||||
const returnTo = token ? `/accept-invite?token=${encodeURIComponent(token)}` : '/accept-invite'
|
||||
await router.replace({ path: '/auth/login', query: { redirect: returnTo } })
|
||||
}
|
||||
@@ -128,10 +210,9 @@ async function acceptInvite (token) {
|
||||
state.loading = true
|
||||
state.error = ''
|
||||
state.success = false
|
||||
state.debugDetails = ''
|
||||
|
||||
// 1) sessão
|
||||
// Obs: getSession lê do storage; não use pra “autorizar” no client,
|
||||
// mas aqui é só fluxo/UX; o servidor valida de verdade.
|
||||
const { data: sessionData, error: sessionErr } = await supabase.auth.getSession()
|
||||
if (sessionErr) {
|
||||
state.loading = false
|
||||
@@ -144,56 +225,44 @@ async function acceptInvite (token) {
|
||||
// não logado → salva token e vai pro login
|
||||
persistPendingToken(token)
|
||||
|
||||
// ✅ importante: /login dá 404 no seu projeto; use /auth/login
|
||||
// ✅ preserve o returnTo com querystring (token)
|
||||
const returnTo = route.fullPath || `/accept-invite?token=${encodeURIComponent(token)}`
|
||||
await router.replace({ path: '/auth/login', query: { redirect: returnTo } })
|
||||
|
||||
// não seta erro: é fluxo normal
|
||||
state.loading = false
|
||||
return
|
||||
}
|
||||
|
||||
// (debug útil: garante que a aba anônima realmente tem user/session)
|
||||
try {
|
||||
const s = await supabase.auth.getSession()
|
||||
const u = await supabase.auth.getUser()
|
||||
console.log('[accept-invite] session user:', s?.data?.session?.user?.id, s?.data?.session?.user?.email)
|
||||
console.log('[accept-invite] getUser:', u?.data?.user?.id, u?.data?.user?.email)
|
||||
} catch (_) {}
|
||||
|
||||
// 2) chama RPC
|
||||
// IMPORTANTÍSSIMO: a função deve validar:
|
||||
// - token existe, status=invited, não expirou
|
||||
// - email do invite == auth.email do caller
|
||||
// - cria/ativa tenant_members (status=active)
|
||||
// - revoga/consome invite
|
||||
//
|
||||
// A assinatura de args depende do seu SQL:
|
||||
// - se for tenant_accept_invite(token uuid) → { token }
|
||||
// - se for tenant_accept_invite(p_token uuid) → { p_token: token }
|
||||
//
|
||||
// ✅ NO SEU CASO: a assinatura existente é p_token (confirmado no SQL Editor).
|
||||
const { data, error } = await supabase.rpc('tenant_accept_invite', { p_token: token })
|
||||
|
||||
if (error) {
|
||||
state.loading = false
|
||||
// mostra o motivo real na tela (e não uma mensagem genérica)
|
||||
state.error = error?.message ? error.message : friendlyError(error)
|
||||
|
||||
const { friendly, raw } = safeRpcError(error)
|
||||
state.error = friendly
|
||||
|
||||
// Se você quiser ver a mensagem “crua” para debug, descomente a linha abaixo:
|
||||
// state.debugDetails = raw
|
||||
|
||||
// Opcional: toast discreto
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: 'Falha no convite',
|
||||
detail: friendly,
|
||||
life: 4000
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 3) sucesso → limpa token pendente
|
||||
clearPendingToken()
|
||||
|
||||
// 4) atualiza tenantStore (boa prática: refresh completo do “contexto do usuário”)
|
||||
// Ideal: sua RPC retorna tenant_id (e opcionalmente role/status)
|
||||
// 4) atualiza tenantStore
|
||||
const acceptedTenantId = data?.tenant_id || data?.tenantId || null
|
||||
|
||||
try {
|
||||
await refreshTenantContextAfterInvite(acceptedTenantId)
|
||||
} catch (e) {
|
||||
// mesmo que refresh falhe, o aceite ocorreu; ainda redireciona, mas você pode avisar
|
||||
// (mantive silencioso para não “quebrar” o fluxo).
|
||||
} catch (_) {
|
||||
// Silencioso: aceite ocorreu; não vamos quebrar o fluxo.
|
||||
}
|
||||
|
||||
state.loading = false
|
||||
@@ -203,20 +272,7 @@ async function acceptInvite (token) {
|
||||
await router.replace('/admin')
|
||||
}
|
||||
|
||||
/**
|
||||
* Melhor prática de atualização do tenantStore após aceite:
|
||||
* - 1) refetch “meus tenants + memberships” (fonte da verdade)
|
||||
* - 2) setActiveTenantId (se veio no retorno; senão, escolha um padrão)
|
||||
* - 3) carregar contexto do tenant ativo (permissões/entitlements/branding/etc)
|
||||
*/
|
||||
async function refreshTenantContextAfterInvite (acceptedTenantId) {
|
||||
// Ajuste para os métodos reais do seu tenantStore:
|
||||
// Exemplo recomendado de API do store:
|
||||
// - await tenantStore.fetchMyTenants()
|
||||
// - await tenantStore.fetchMyMemberships()
|
||||
// - tenantStore.setActiveTenantId(...)
|
||||
// - await tenantStore.hydrateActiveTenantContext()
|
||||
|
||||
if (typeof tenantStore.refreshMyTenantsAndMemberships === 'function') {
|
||||
await tenantStore.refreshMyTenantsAndMemberships()
|
||||
} else {
|
||||
@@ -239,9 +295,9 @@ async function run () {
|
||||
state.loading = true
|
||||
state.error = ''
|
||||
state.success = false
|
||||
state.debugDetails = ''
|
||||
|
||||
// 1) token: query > pendente (pós-login)
|
||||
const token = tokenFromQuery.value || readPendingToken()
|
||||
const token = tokenEffective.value
|
||||
|
||||
if (!token) {
|
||||
state.loading = false
|
||||
@@ -258,7 +314,6 @@ async function run () {
|
||||
// Se veio da query, persiste (caso precise atravessar login)
|
||||
if (tokenFromQuery.value) persistPendingToken(token)
|
||||
|
||||
// 2) tenta aceitar
|
||||
await acceptInvite(token)
|
||||
}
|
||||
|
||||
|
||||
@@ -790,21 +790,15 @@
|
||||
import { computed, reactive, ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
|
||||
import Button from 'primevue/button'
|
||||
import InputText from 'primevue/inputtext'
|
||||
import InputMask from 'primevue/inputmask'
|
||||
import Textarea from 'primevue/textarea'
|
||||
import Checkbox from 'primevue/checkbox'
|
||||
import Message from 'primevue/message'
|
||||
import Toast from 'primevue/toast'
|
||||
import Popover from 'primevue/popover'
|
||||
import Accordion from 'primevue/accordion'
|
||||
import AccordionPanel from 'primevue/accordionpanel'
|
||||
import AccordionHeader from 'primevue/accordionheader'
|
||||
import AccordionContent from 'primevue/accordioncontent'
|
||||
import FloatLabel from 'primevue/floatlabel'
|
||||
import IconField from 'primevue/iconfield'
|
||||
import InputIcon from 'primevue/inputicon'
|
||||
import Select from 'primevue/select'
|
||||
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
|
||||
519
src/views/pages/public/Landingpage-v1 - bkp.vue
Normal file
519
src/views/pages/public/Landingpage-v1 - bkp.vue
Normal file
@@ -0,0 +1,519 @@
|
||||
<template>
|
||||
<div class="min-h-screen bg-[var(--surface-ground)] text-[var(--text-color)]">
|
||||
<!-- TOPBAR -->
|
||||
<div
|
||||
class="sticky top-0 z-40 border-b border-[var(--surface-border)] bg-[color-mix(in_srgb,var(--surface-card),transparent_12%)] backdrop-blur"
|
||||
>
|
||||
<div class="mx-auto max-w-7xl px-4 md:px-6 py-3 flex items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-3 min-w-0">
|
||||
<div
|
||||
class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] grid place-items-center shadow-sm"
|
||||
>
|
||||
<i class="pi pi-sparkles text-lg opacity-80" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="font-semibold leading-tight truncate">{{ brandName }}</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] truncate">Gestão clínica sem ruído.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<Button label="Entrar" icon="pi pi-sign-in" severity="secondary" outlined @click="go('/auth/login')" />
|
||||
<Button label="Começar" icon="pi pi-bolt" @click="goStart()" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- HERO -->
|
||||
<section class="relative overflow-hidden">
|
||||
<!-- blobs / noir glow -->
|
||||
<div class="pointer-events-none absolute inset-0">
|
||||
<div class="absolute -top-28 -left-28 h-96 w-96 rounded-full blur-3xl opacity-60 bg-indigo-400/10" />
|
||||
<div class="absolute top-24 -right-24 h-[28rem] w-[28rem] rounded-full blur-3xl opacity-60 bg-emerald-400/10" />
|
||||
<div class="absolute -bottom-40 left-1/3 h-[34rem] w-[34rem] rounded-full blur-3xl opacity-60 bg-fuchsia-400/10" />
|
||||
</div>
|
||||
|
||||
<div class="mx-auto max-w-7xl px-4 md:px-6 pt-10 md:pt-16 pb-8 md:pb-14 relative">
|
||||
<div class="grid grid-cols-12 gap-6 items-center">
|
||||
<div class="col-span-12 lg:col-span-7">
|
||||
<Chip class="mb-4" label="Para psicólogos e clínicas" icon="pi pi-shield" />
|
||||
|
||||
<h1 class="text-3xl md:text-5xl font-semibold leading-tight">
|
||||
Uma agenda inteligente, um prontuário organizado, um financeiro respirável.
|
||||
</h1>
|
||||
|
||||
<p class="mt-4 text-base md:text-lg text-[var(--text-color-secondary)] max-w-2xl">
|
||||
Centralize a rotina clínica em um lugar só: pacientes, sessões, lembretes e indicadores. Menos dispersão.
|
||||
Mais presença.
|
||||
</p>
|
||||
|
||||
<div class="mt-6 flex flex-col sm:flex-row gap-2">
|
||||
<Button
|
||||
label="Criar conta grátis"
|
||||
icon="pi pi-arrow-right"
|
||||
class="w-full sm:w-auto"
|
||||
@click="goStart()"
|
||||
/>
|
||||
<Button
|
||||
label="Ver planos"
|
||||
icon="pi pi-credit-card"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="w-full sm:w-auto"
|
||||
@click="scrollTo('pricing')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 flex flex-wrap gap-2">
|
||||
<Tag severity="secondary" value="Agenda online (PRO)" />
|
||||
<Tag severity="secondary" value="Controle de sessões" />
|
||||
<Tag severity="secondary" value="Financeiro integrado" />
|
||||
<Tag severity="secondary" value="Clínica / multi-profissional" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 lg:col-span-5">
|
||||
<Card class="overflow-hidden">
|
||||
<template #content>
|
||||
<div class="p-1">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] p-4">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div class="font-semibold text-lg">Painel de hoje</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)]">Um recorte: o essencial, sem excesso.</div>
|
||||
</div>
|
||||
<i class="pi pi-chart-line opacity-70" />
|
||||
</div>
|
||||
|
||||
<Divider class="my-4" />
|
||||
|
||||
<div class="grid grid-cols-12 gap-3">
|
||||
<div class="col-span-12 md:col-span-6">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] p-3">
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">Sessões</div>
|
||||
<div class="text-2xl font-semibold mt-1">6</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">com lembretes automáticos</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 md:col-span-6">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] p-3">
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">Recebimentos</div>
|
||||
<div class="text-2xl font-semibold mt-1">R$ 840</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">visão clara do mês</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] p-3">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">Prontuário</div>
|
||||
<div class="font-semibold mt-1">Anotações e histórico</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">
|
||||
organizado por paciente, sessão e linha do tempo
|
||||
</div>
|
||||
</div>
|
||||
<i class="pi pi-file-edit opacity-70" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 text-xs text-[var(--text-color-secondary)]">
|
||||
* Ilustração conceitual do produto.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- TRUST / VALUE STRIP -->
|
||||
<section class="mx-auto max-w-7xl px-4 md:px-6 pb-10">
|
||||
<div class="grid grid-cols-12 gap-4">
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<Card class="h-full">
|
||||
<template #content>
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center"
|
||||
>
|
||||
<i class="pi pi-calendar opacity-80" />
|
||||
</div>
|
||||
<div>
|
||||
<div class="font-semibold">Agenda e autoagendamento</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1">
|
||||
O paciente confirma, agenda e reagenda com autonomia (PRO).
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<Card class="h-full">
|
||||
<template #content>
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center"
|
||||
>
|
||||
<i class="pi pi-wallet opacity-80" />
|
||||
</div>
|
||||
<div>
|
||||
<div class="font-semibold">Financeiro integrado</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1">
|
||||
Receita/despesa junto da agenda — sem planilhas espalhadas.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<Card class="h-full">
|
||||
<template #content>
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center"
|
||||
>
|
||||
<i class="pi pi-lock opacity-80" />
|
||||
</div>
|
||||
<div>
|
||||
<div class="font-semibold">Prontuário e controle de sessões</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1">
|
||||
Registro clínico e histórico acessíveis, com backups e organização.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 text-xs text-[var(--text-color-secondary)]">
|
||||
Inspirações de módulos comuns no mercado: agenda online, financeiro, prontuário/controle de sessões e gestão de
|
||||
clínica.
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- FEATURES -->
|
||||
<section class="mx-auto max-w-7xl px-4 md:px-6 pb-12">
|
||||
<div class="flex items-end justify-between gap-3 mb-4">
|
||||
<div>
|
||||
<div class="text-2xl md:text-3xl font-semibold">Recursos que sustentam a rotina</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1">
|
||||
O foco é tirar o excesso de fricção sem invadir o que é do seu método.
|
||||
</div>
|
||||
</div>
|
||||
<Button label="Ver planos" severity="secondary" outlined icon="pi pi-arrow-down" @click="scrollTo('pricing')" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-12 gap-4">
|
||||
<div v-for="f in features" :key="f.title" class="col-span-12 md:col-span-6 lg:col-span-4">
|
||||
<Card class="h-full">
|
||||
<template #content>
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center"
|
||||
>
|
||||
<i :class="f.icon" class="opacity-80" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="font-semibold">{{ f.title }}</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1">
|
||||
{{ f.desc }}
|
||||
</div>
|
||||
<div v-if="f.pro" class="mt-2">
|
||||
<Tag severity="warning" value="PRO" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Divider class="my-8" />
|
||||
|
||||
<Accordion :activeIndex="0">
|
||||
<AccordionTab header="Como fica o fluxo na prática?">
|
||||
<div class="text-sm text-[var(--text-color-secondary)] leading-relaxed">
|
||||
Você abre a agenda, a sessão acontece, o registro fica no prontuário, e o financeiro acompanha o movimento.
|
||||
O sistema existe para manter o consultório respirando — não para virar uma burocracia nova.
|
||||
</div>
|
||||
</AccordionTab>
|
||||
<AccordionTab header="E para clínica (multi-profissionais)?">
|
||||
<div class="text-sm text-[var(--text-color-secondary)] leading-relaxed">
|
||||
Perfis por função, agendas separadas, repasses e visão gerencial — quando você estiver pronto para crescer.
|
||||
</div>
|
||||
</AccordionTab>
|
||||
<AccordionTab header="Privacidade e segurança">
|
||||
<div class="text-sm text-[var(--text-color-secondary)] leading-relaxed">
|
||||
Controle de acesso por conta, separação por clínica/tenant, e políticas de storage por usuário. (Os detalhes
|
||||
de conformidade você pode expor numa página própria de segurança/LGPD.)
|
||||
</div>
|
||||
</AccordionTab>
|
||||
</Accordion>
|
||||
</section>
|
||||
|
||||
<!-- PRICING (dinâmico do SaaS) -->
|
||||
<section id="pricing" class="mx-auto max-w-7xl px-4 md:px-6 pb-14 scroll-mt-24">
|
||||
<div class="text-5xl md:text-4xl font-semibold text-center">Planos</div>
|
||||
<div class="text-2xl md:text-2xl text-[var(--text-color-secondary)] mt-1 text-center">
|
||||
Comece simples. Suba para PRO quando a agenda pedir automação.
|
||||
</div>
|
||||
|
||||
<!-- header conceitual + toggle -->
|
||||
<div class="flex flex-col items-center text-center mt-6">
|
||||
<div class="flex items-center gap-3 mb-4">
|
||||
<AvatarGroup>
|
||||
<Avatar
|
||||
image="https://fqjltiegiezfetthbags.supabase.co/storage/v1/render/image/public/block.images/blocks/avatars/circle/avatar-m-1.png"
|
||||
shape="circle"
|
||||
/>
|
||||
<Avatar
|
||||
image="https://fqjltiegiezfetthbags.supabase.co/storage/v1/render/image/public/block.images/blocks/avatars/circle/avatar-f-21.png"
|
||||
shape="circle"
|
||||
/>
|
||||
<Avatar
|
||||
image="https://fqjltiegiezfetthbags.supabase.co/storage/v1/render/image/public/block.images/blocks/avatars/circle/avatar-f-1.png"
|
||||
shape="circle"
|
||||
/>
|
||||
<Avatar
|
||||
image="https://fqjltiegiezfetthbags.supabase.co/storage/v1/render/image/public/block.images/blocks/avatars/circle/avatar-m-3.png"
|
||||
shape="circle"
|
||||
/>
|
||||
</AvatarGroup>
|
||||
|
||||
<Divider layout="vertical" />
|
||||
<span class="text-sm text-[var(--text-color-secondary)] font-medium">Happy Customers</span>
|
||||
</div>
|
||||
|
||||
<div class="inline-flex items-center rounded-xl border border-[var(--surface-border)] bg-[var(--surface-50)] p-1">
|
||||
<Button
|
||||
label="Mensal"
|
||||
size="small"
|
||||
:severity="billingInterval === 'month' ? 'success' : 'secondary'"
|
||||
:outlined="billingInterval !== 'month'"
|
||||
@click="billingInterval = 'month'"
|
||||
/>
|
||||
<Button
|
||||
label="Anual"
|
||||
size="small"
|
||||
:severity="billingInterval === 'year' ? 'success' : 'secondary'"
|
||||
:outlined="billingInterval !== 'year'"
|
||||
class="ml-1"
|
||||
@click="billingInterval = 'year'"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="billingInterval === 'year'" class="mt-2">
|
||||
<Tag severity="success" value="Economize até 20%" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loadingPricing" class="mt-8 text-sm text-[var(--text-color-secondary)]">
|
||||
Carregando planos...
|
||||
</div>
|
||||
|
||||
<div v-else class="mt-8 grid grid-cols-12 gap-4">
|
||||
<div v-for="p in pricing" :key="p.plan_id" class="col-span-12 md:col-span-4">
|
||||
<Card
|
||||
class="h-full overflow-hidden transition-transform"
|
||||
:class="p.is_featured ? 'ring-1 ring-emerald-500/30 md:-translate-y-2 md:scale-[1.02]' : ''"
|
||||
>
|
||||
<template #content>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)]">
|
||||
{{ p.badge || 'Plano' }}
|
||||
</div>
|
||||
<div class="text-xl font-semibold">
|
||||
{{ p.public_name || p.plan_name || p.plan_key }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Tag v-if="p.is_featured" severity="success" value="Popular" />
|
||||
</div>
|
||||
|
||||
<div class="mt-4 text-3xl font-semibold leading-none">
|
||||
{{ formatBRLFromCents(priceFor(p)) }}
|
||||
<span class="text-sm font-normal text-[var(--text-color-secondary)]">
|
||||
/{{ billingInterval === 'month' ? 'mês' : 'ano' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="billingInterval === 'year'"
|
||||
class="text-xs text-emerald-500 mt-1 font-medium"
|
||||
>
|
||||
Melhor custo-benefício
|
||||
</div>
|
||||
|
||||
<div class="mt-2 text-sm text-[var(--text-color-secondary)] min-h-[44px]">
|
||||
{{ p.public_description }}
|
||||
</div>
|
||||
|
||||
<Divider class="my-4" />
|
||||
|
||||
<ul v-if="p.bullets?.length" class="space-y-2 text-sm">
|
||||
<li v-for="b in p.bullets" :key="b.id" class="flex items-start gap-2">
|
||||
<i class="pi pi-check mt-1 text-emerald-500"></i>
|
||||
<span :class="b.highlight ? 'font-semibold' : 'text-[var(--text-color-secondary)]'">
|
||||
{{ b.text }}
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div v-else class="text-sm text-[var(--text-color-secondary)]">Benefícios em breve.</div>
|
||||
|
||||
<div class="mt-5">
|
||||
<Button
|
||||
label="Começar"
|
||||
class="w-full"
|
||||
:severity="p.is_featured ? 'success' : 'secondary'"
|
||||
:outlined="!p.is_featured"
|
||||
icon="pi pi-arrow-right"
|
||||
@click="go(`/auth/signup?plan=${p.plan_key}&interval=${billingInterval}`)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 text-xs text-[var(--text-color-secondary)]">
|
||||
Dica: estes planos vêm do painel SaaS (vitrine pública) e podem mapear diretamente para entitlements (FREE/PRO)
|
||||
sem mexer no código.
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- FOOTER -->
|
||||
<footer class="border-t border-[var(--surface-border)]">
|
||||
<div
|
||||
class="mx-auto max-w-7xl px-4 md:px-6 py-8 flex flex-col md:flex-row items-start md:items-center justify-between gap-4"
|
||||
>
|
||||
<div>
|
||||
<div class="font-semibold">{{ brandName }}</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">© {{ year }} — Todos os direitos reservados.</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<Button label="Entrar" severity="secondary" outlined icon="pi pi-sign-in" @click="go('/auth/login')" />
|
||||
<Button label="Criar conta" icon="pi pi-bolt" @click="goStart()" />
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
|
||||
import Chip from 'primevue/chip'
|
||||
import Accordion from 'primevue/accordion'
|
||||
import AccordionTab from 'primevue/accordiontab'
|
||||
import Avatar from 'primevue/avatar'
|
||||
import AvatarGroup from 'primevue/avatargroup'
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
const brandName = 'Psi Quasar' // ajuste para o nome final do produto
|
||||
const year = computed(() => new Date().getFullYear())
|
||||
|
||||
function go(path) {
|
||||
router.push(path)
|
||||
}
|
||||
|
||||
function scrollTo(id) {
|
||||
const el = document.getElementById(id)
|
||||
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' })
|
||||
}
|
||||
|
||||
const featuredPlanKey = computed(() => {
|
||||
const list = Array.isArray(pricing.value) ? pricing.value : []
|
||||
const featured = list.find(p => p && p.is_featured && p.is_visible)
|
||||
return featured?.plan_key || null
|
||||
})
|
||||
|
||||
function goStart() {
|
||||
if (featuredPlanKey.value) {
|
||||
router.push(`/auth/signup?plan=${featuredPlanKey.value}&interval=${billingInterval.value}`)
|
||||
return
|
||||
}
|
||||
|
||||
router.push('/auth/signup')
|
||||
}
|
||||
|
||||
const features = ref([
|
||||
{
|
||||
title: 'Agenda inteligente',
|
||||
desc: 'Configure sua semana, encaixes, bloqueios e visão por dia/semana.',
|
||||
icon: 'pi pi-calendar'
|
||||
},
|
||||
{
|
||||
title: 'Autoagendamento (PRO)',
|
||||
desc: 'Página para o paciente confirmar, agendar e reagendar sem fricção.',
|
||||
icon: 'pi pi-globe',
|
||||
pro: true
|
||||
},
|
||||
{
|
||||
title: 'Prontuário e sessões',
|
||||
desc: 'Registro por paciente, histórico por sessão e organização por linha do tempo.',
|
||||
icon: 'pi pi-file-edit'
|
||||
},
|
||||
{
|
||||
title: 'Financeiro integrado',
|
||||
desc: 'Receitas, despesas e visão do mês conectadas ao que acontece na agenda.',
|
||||
icon: 'pi pi-wallet'
|
||||
},
|
||||
{
|
||||
title: 'Pacientes e tags',
|
||||
desc: 'Segmentação por grupos, etiquetas e filtros práticos para achar rápido.',
|
||||
icon: 'pi pi-users'
|
||||
},
|
||||
{
|
||||
title: 'Clínica / multi-profissional',
|
||||
desc: 'Múltiplos profissionais, agendas separadas, papéis e visão gerencial.',
|
||||
icon: 'pi pi-building'
|
||||
}
|
||||
])
|
||||
|
||||
/** PRICING dinâmico do SaaS */
|
||||
const billingInterval = ref('year') // 'month' | 'year'
|
||||
const pricing = ref([])
|
||||
const loadingPricing = ref(false)
|
||||
|
||||
function formatBRLFromCents(cents) {
|
||||
if (cents == null) return '—'
|
||||
const v = Number(cents) / 100
|
||||
return v.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })
|
||||
}
|
||||
|
||||
function priceFor(p) {
|
||||
return billingInterval.value === 'year' ? p.yearly_cents : p.monthly_cents
|
||||
}
|
||||
|
||||
async function fetchPricing() {
|
||||
loadingPricing.value = true
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('v_public_pricing')
|
||||
.select('*')
|
||||
.eq('is_visible', true)
|
||||
.order('sort_order', { ascending: true })
|
||||
|
||||
loadingPricing.value = false
|
||||
|
||||
if (!error) pricing.value = data || []
|
||||
}
|
||||
|
||||
onMounted(fetchPricing)
|
||||
</script>
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- src/views/pages/public/LandingPage.vue -->
|
||||
<template>
|
||||
<div class="min-h-screen bg-[var(--surface-ground)] text-[var(--text-color)]">
|
||||
<!-- TOPBAR -->
|
||||
@@ -5,46 +6,65 @@
|
||||
class="sticky top-0 z-40 border-b border-[var(--surface-border)] bg-[color-mix(in_srgb,var(--surface-card),transparent_12%)] backdrop-blur"
|
||||
>
|
||||
<div class="mx-auto max-w-7xl px-4 md:px-6 py-3 flex items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-3 min-w-0">
|
||||
<button class="flex items-center gap-3 min-w-0" @click="scrollTo('top')">
|
||||
<div
|
||||
class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] grid place-items-center shadow-sm"
|
||||
>
|
||||
<i class="pi pi-sparkles text-lg opacity-80" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="min-w-0 text-left">
|
||||
<div class="font-semibold leading-tight truncate">{{ brandName }}</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] truncate">Gestão clínica sem ruído.</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] truncate">
|
||||
Gestão clínica sem ruído.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<Button label="Entrar" icon="pi pi-sign-in" severity="secondary" outlined @click="go('/auth/login')" />
|
||||
<Button label="Começar" icon="pi pi-bolt" @click="goStart()" />
|
||||
<Button
|
||||
label="Entrar"
|
||||
icon="pi pi-sign-in"
|
||||
severity="secondary"
|
||||
outlined
|
||||
@click="go('/auth/login')"
|
||||
/>
|
||||
<Button
|
||||
label="Começar"
|
||||
icon="pi pi-bolt"
|
||||
@click="goStart()"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- HERO -->
|
||||
<section class="relative overflow-hidden">
|
||||
<!-- blobs / noir glow -->
|
||||
<section id="top" class="relative overflow-hidden">
|
||||
<!-- background: noir grid + glow -->
|
||||
<div class="pointer-events-none absolute inset-0">
|
||||
<div class="hero-grid absolute inset-0 opacity-[0.35]" />
|
||||
<div class="absolute -top-28 -left-28 h-96 w-96 rounded-full blur-3xl opacity-60 bg-indigo-400/10" />
|
||||
<div class="absolute top-24 -right-24 h-[28rem] w-[28rem] rounded-full blur-3xl opacity-60 bg-emerald-400/10" />
|
||||
<div class="absolute top-20 -right-24 h-[28rem] w-[28rem] rounded-full blur-3xl opacity-60 bg-emerald-400/10" />
|
||||
<div class="absolute -bottom-40 left-1/3 h-[34rem] w-[34rem] rounded-full blur-3xl opacity-60 bg-fuchsia-400/10" />
|
||||
<div class="hero-noise absolute inset-0 opacity-[0.12]" />
|
||||
</div>
|
||||
|
||||
<div class="mx-auto max-w-7xl px-4 md:px-6 pt-10 md:pt-16 pb-8 md:pb-14 relative">
|
||||
<div class="mx-auto max-w-7xl px-4 md:px-6 pt-10 md:pt-16 pb-10 md:pb-14 relative">
|
||||
<div class="grid grid-cols-12 gap-6 items-center">
|
||||
<div class="col-span-12 lg:col-span-7">
|
||||
<Chip class="mb-4" label="Para psicólogos e clínicas" icon="pi pi-shield" />
|
||||
<div class="flex flex-wrap items-center gap-2 mb-4">
|
||||
<Chip label="Para psicólogos e clínicas" icon="pi pi-shield" />
|
||||
<span class="text-xs text-[var(--text-color-secondary)]">
|
||||
• menos dispersão • mais presença • mais previsibilidade
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<h1 class="text-3xl md:text-5xl font-semibold leading-tight">
|
||||
Uma agenda inteligente, um prontuário organizado, um financeiro respirável.
|
||||
Um sistema que <span class="hero-underline">reduz ruído</span> — sem roubar seu método.
|
||||
</h1>
|
||||
|
||||
<p class="mt-4 text-base md:text-lg text-[var(--text-color-secondary)] max-w-2xl">
|
||||
Centralize a rotina clínica em um lugar só: pacientes, sessões, lembretes e indicadores. Menos dispersão.
|
||||
Mais presença.
|
||||
<p class="mt-4 text-base md:text-lg text-[var(--text-color-secondary)] max-w-2xl leading-relaxed">
|
||||
Centralize a rotina clínica em um lugar só: pacientes, sessões, lembretes e indicadores.
|
||||
O objetivo não é “burocratizar”: é deixar o consultório respirável.
|
||||
</p>
|
||||
|
||||
<div class="mt-6 flex flex-col sm:flex-row gap-2">
|
||||
@@ -62,6 +82,14 @@
|
||||
class="w-full sm:w-auto"
|
||||
@click="scrollTo('pricing')"
|
||||
/>
|
||||
<Button
|
||||
label="Como funciona"
|
||||
icon="pi pi-compass"
|
||||
severity="secondary"
|
||||
text
|
||||
class="w-full sm:w-auto"
|
||||
@click="scrollTo('how')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 flex flex-wrap gap-2">
|
||||
@@ -69,18 +97,25 @@
|
||||
<Tag severity="secondary" value="Controle de sessões" />
|
||||
<Tag severity="secondary" value="Financeiro integrado" />
|
||||
<Tag severity="secondary" value="Clínica / multi-profissional" />
|
||||
<Tag severity="secondary" value="Separação por tenant + RLS" />
|
||||
</div>
|
||||
|
||||
<div class="mt-6 text-xs text-[var(--text-color-secondary)]">
|
||||
“A diferença entre ter uma agenda e ter um sistema mora nos detalhes.”
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 lg:col-span-5">
|
||||
<Card class="overflow-hidden">
|
||||
<Card class="overflow-hidden rounded-[2rem] border border-[var(--surface-border)]">
|
||||
<template #content>
|
||||
<div class="p-1">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] p-4">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div class="font-semibold text-lg">Painel de hoje</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)]">Um recorte: o essencial, sem excesso.</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)]">
|
||||
Um recorte: o essencial, sem excesso.
|
||||
</div>
|
||||
</div>
|
||||
<i class="pi pi-chart-line opacity-70" />
|
||||
</div>
|
||||
@@ -92,7 +127,9 @@
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] p-3">
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">Sessões</div>
|
||||
<div class="text-2xl font-semibold mt-1">6</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">com lembretes automáticos</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">
|
||||
com lembretes automáticos
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -100,18 +137,20 @@
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] p-3">
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">Recebimentos</div>
|
||||
<div class="text-2xl font-semibold mt-1">R$ 840</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">visão clara do mês</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">
|
||||
visão clara do mês
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] p-3">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<div class="min-w-0">
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">Prontuário</div>
|
||||
<div class="font-semibold mt-1">Anotações e histórico</div>
|
||||
<div class="font-semibold mt-1 truncate">Anotações e histórico</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">
|
||||
organizado por paciente, sessão e linha do tempo
|
||||
por paciente • por sessão • linha do tempo
|
||||
</div>
|
||||
</div>
|
||||
<i class="pi pi-file-edit opacity-70" />
|
||||
@@ -127,21 +166,40 @@
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
|
||||
<div class="mt-4 grid grid-cols-12 gap-3">
|
||||
<div class="col-span-12 sm:col-span-6">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[color-mix(in_srgb,var(--surface-card),transparent_10%)] p-4">
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">Promessa</div>
|
||||
<div class="font-semibold mt-1">Organizar sem invadir.</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">
|
||||
Você define o método. O sistema remove ruído.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-span-12 sm:col-span-6">
|
||||
<div class="rounded-2xl border border-[var(--surface-border)] bg-[color-mix(in_srgb,var(--surface-card),transparent_10%)] p-4">
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">Arquitetura</div>
|
||||
<div class="font-semibold mt-1">Multi-tenant de verdade.</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">
|
||||
Menus + guards + RLS alinhados.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- TRUST / VALUE STRIP -->
|
||||
<!-- VALUE STRIP -->
|
||||
<section class="mx-auto max-w-7xl px-4 md:px-6 pb-10">
|
||||
<div class="grid grid-cols-12 gap-4">
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<Card class="h-full">
|
||||
<Card class="h-full rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center"
|
||||
>
|
||||
<div class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center">
|
||||
<i class="pi pi-calendar opacity-80" />
|
||||
</div>
|
||||
<div>
|
||||
@@ -156,12 +214,10 @@
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<Card class="h-full">
|
||||
<Card class="h-full rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center"
|
||||
>
|
||||
<div class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center">
|
||||
<i class="pi pi-wallet opacity-80" />
|
||||
</div>
|
||||
<div>
|
||||
@@ -176,18 +232,16 @@
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<Card class="h-full">
|
||||
<Card class="h-full rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center"
|
||||
>
|
||||
<div class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center">
|
||||
<i class="pi pi-lock opacity-80" />
|
||||
</div>
|
||||
<div>
|
||||
<div class="font-semibold">Prontuário e controle de sessões</div>
|
||||
<div class="font-semibold">Prontuário e sessões</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1">
|
||||
Registro clínico e histórico acessíveis, com backups e organização.
|
||||
Registro e histórico acessíveis, com organização e backup.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -197,40 +251,82 @@
|
||||
</div>
|
||||
|
||||
<div class="mt-3 text-xs text-[var(--text-color-secondary)]">
|
||||
Inspirações de módulos comuns no mercado: agenda online, financeiro, prontuário/controle de sessões e gestão de
|
||||
clínica.
|
||||
Módulos: agenda, prontuário/sessões, financeiro e gestão multi-profissional.
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- FEATURES -->
|
||||
<section class="mx-auto max-w-7xl px-4 md:px-6 pb-12">
|
||||
<!-- HOW IT WORKS -->
|
||||
<section id="how" class="mx-auto max-w-7xl px-4 md:px-6 pb-12 scroll-mt-24">
|
||||
<div class="flex items-end justify-between gap-3 mb-4">
|
||||
<div>
|
||||
<div class="text-2xl md:text-3xl font-semibold">Recursos que sustentam a rotina</div>
|
||||
<div class="text-2xl md:text-3xl font-semibold">Como funciona</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1">
|
||||
O foco é tirar o excesso de fricção sem invadir o que é do seu método.
|
||||
Três movimentos: preparar, atender, acompanhar — sem fricção.
|
||||
</div>
|
||||
</div>
|
||||
<Button label="Ver planos" severity="secondary" outlined icon="pi pi-arrow-down" @click="scrollTo('pricing')" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-12 gap-4">
|
||||
<div v-for="f in features" :key="f.title" class="col-span-12 md:col-span-6 lg:col-span-4">
|
||||
<Card class="h-full">
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<Card class="h-full rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center"
|
||||
>
|
||||
<i :class="f.icon" class="opacity-80" />
|
||||
<div class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center">
|
||||
<i class="pi pi-sliders-h opacity-80" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="font-semibold">{{ f.title }}</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1">
|
||||
{{ f.desc }}
|
||||
<div>
|
||||
<div class="font-semibold">1) Preparar</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1 leading-relaxed">
|
||||
Configure agenda, encaixes e regras. Se quiser, habilite autoagendamento (PRO).
|
||||
</div>
|
||||
<div v-if="f.pro" class="mt-2">
|
||||
<Tag severity="warning" value="PRO" />
|
||||
<div class="mt-2">
|
||||
<Tag severity="secondary" value="Bloqueios" />
|
||||
<Tag class="ml-2" severity="secondary" value="Encaixes" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<Card class="h-full rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center">
|
||||
<i class="pi pi-comments opacity-80" />
|
||||
</div>
|
||||
<div>
|
||||
<div class="font-semibold">2) Atender</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1 leading-relaxed">
|
||||
Sessão acontece. Registro fica onde precisa ficar: no prontuário, no tempo certo.
|
||||
</div>
|
||||
<div class="mt-2">
|
||||
<Tag severity="secondary" value="Sessões" />
|
||||
<Tag class="ml-2" severity="secondary" value="Prontuário" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<Card class="h-full rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center">
|
||||
<i class="pi pi-chart-bar opacity-80" />
|
||||
</div>
|
||||
<div>
|
||||
<div class="font-semibold">3) Acompanhar</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1 leading-relaxed">
|
||||
Financeiro e indicadores acompanham o movimento. Menos “cadê?”, mais previsibilidade.
|
||||
</div>
|
||||
<div class="mt-2">
|
||||
<Tag severity="secondary" value="Recebimentos" />
|
||||
<Tag class="ml-2" severity="secondary" value="Indicadores" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -244,58 +340,71 @@
|
||||
<Accordion :activeIndex="0">
|
||||
<AccordionTab header="Como fica o fluxo na prática?">
|
||||
<div class="text-sm text-[var(--text-color-secondary)] leading-relaxed">
|
||||
Você abre a agenda, a sessão acontece, o registro fica no prontuário, e o financeiro acompanha o movimento.
|
||||
Você abre a agenda, a sessão acontece, o registro vai para o prontuário, e o financeiro acompanha.
|
||||
O sistema existe para manter o consultório respirando — não para virar uma burocracia nova.
|
||||
</div>
|
||||
</AccordionTab>
|
||||
<AccordionTab header="E para clínica (multi-profissionais)?">
|
||||
<div class="text-sm text-[var(--text-color-secondary)] leading-relaxed">
|
||||
Perfis por função, agendas separadas, repasses e visão gerencial — quando você estiver pronto para crescer.
|
||||
Perfis por função, agendas separadas, visão gerencial e convites (Modelo B).
|
||||
Você cresce sem quebrar a estrutura.
|
||||
</div>
|
||||
</AccordionTab>
|
||||
<AccordionTab header="Privacidade e segurança">
|
||||
<div class="text-sm text-[var(--text-color-secondary)] leading-relaxed">
|
||||
Controle de acesso por conta, separação por clínica/tenant, e políticas de storage por usuário. (Os detalhes
|
||||
de conformidade você pode expor numa página própria de segurança/LGPD.)
|
||||
Separação por clínica/tenant, controle de acesso e políticas no banco (RLS).
|
||||
(Quando quiser, a gente cria uma página dedicada de LGPD/Segurança.)
|
||||
</div>
|
||||
</AccordionTab>
|
||||
</Accordion>
|
||||
</section>
|
||||
|
||||
<!-- FEATURES -->
|
||||
<section class="mx-auto max-w-7xl px-4 md:px-6 pb-12">
|
||||
<div class="flex items-end justify-between gap-3 mb-4">
|
||||
<div>
|
||||
<div class="text-2xl md:text-3xl font-semibold">Recursos que sustentam a rotina</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1">
|
||||
O foco é tirar fricção — sem invadir o que é do seu método.
|
||||
</div>
|
||||
</div>
|
||||
<Button label="Ver planos" severity="secondary" outlined icon="pi pi-arrow-down" @click="scrollTo('pricing')" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-12 gap-4">
|
||||
<div v-for="f in features" :key="f.title" class="col-span-12 md:col-span-6 lg:col-span-4">
|
||||
<Card class="h-full rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="h-10 w-10 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center">
|
||||
<i :class="f.icon" class="opacity-80" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="font-semibold">{{ f.title }}</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1 leading-relaxed">
|
||||
{{ f.desc }}
|
||||
</div>
|
||||
<div v-if="f.pro" class="mt-2">
|
||||
<Tag severity="warning" value="PRO" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- PRICING (dinâmico do SaaS) -->
|
||||
<section id="pricing" class="mx-auto max-w-7xl px-4 md:px-6 pb-14 scroll-mt-24">
|
||||
<div class="text-5xl md:text-4xl font-semibold text-center">Planos</div>
|
||||
<div class="text-2xl md:text-2xl text-[var(--text-color-secondary)] mt-1 text-center">
|
||||
<div class="text-3xl md:text-4xl font-semibold text-center">Planos</div>
|
||||
<div class="text-base md:text-lg text-[var(--text-color-secondary)] mt-2 text-center">
|
||||
Comece simples. Suba para PRO quando a agenda pedir automação.
|
||||
</div>
|
||||
|
||||
<!-- header conceitual + toggle -->
|
||||
<!-- toggle -->
|
||||
<div class="flex flex-col items-center text-center mt-6">
|
||||
<div class="flex items-center gap-3 mb-4">
|
||||
<AvatarGroup>
|
||||
<Avatar
|
||||
image="https://fqjltiegiezfetthbags.supabase.co/storage/v1/render/image/public/block.images/blocks/avatars/circle/avatar-m-1.png"
|
||||
shape="circle"
|
||||
/>
|
||||
<Avatar
|
||||
image="https://fqjltiegiezfetthbags.supabase.co/storage/v1/render/image/public/block.images/blocks/avatars/circle/avatar-f-21.png"
|
||||
shape="circle"
|
||||
/>
|
||||
<Avatar
|
||||
image="https://fqjltiegiezfetthbags.supabase.co/storage/v1/render/image/public/block.images/blocks/avatars/circle/avatar-f-1.png"
|
||||
shape="circle"
|
||||
/>
|
||||
<Avatar
|
||||
image="https://fqjltiegiezfetthbags.supabase.co/storage/v1/render/image/public/block.images/blocks/avatars/circle/avatar-m-3.png"
|
||||
shape="circle"
|
||||
/>
|
||||
</AvatarGroup>
|
||||
|
||||
<Divider layout="vertical" />
|
||||
<span class="text-sm text-[var(--text-color-secondary)] font-medium">Happy Customers</span>
|
||||
</div>
|
||||
|
||||
<div class="inline-flex items-center rounded-xl border border-[var(--surface-border)] bg-[var(--surface-50)] p-1">
|
||||
<div class="inline-flex items-center rounded-xl border border-[var(--surface-border)] bg-[color-mix(in_srgb,var(--surface-card),transparent_10%)] p-1">
|
||||
<Button
|
||||
label="Mensal"
|
||||
size="small"
|
||||
@@ -312,95 +421,132 @@
|
||||
@click="billingInterval = 'year'"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="billingInterval === 'year'" class="mt-2">
|
||||
<Tag severity="success" value="Economize até 20%" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loadingPricing" class="mt-8 text-sm text-[var(--text-color-secondary)]">
|
||||
Carregando planos...
|
||||
</div>
|
||||
|
||||
<div v-else class="mt-8 grid grid-cols-12 gap-4">
|
||||
<div v-for="p in pricing" :key="p.plan_id" class="col-span-12 md:col-span-4">
|
||||
<Card
|
||||
class="h-full overflow-hidden transition-transform"
|
||||
:class="p.is_featured ? 'ring-1 ring-emerald-500/30 md:-translate-y-2 md:scale-[1.02]' : ''"
|
||||
>
|
||||
<template #content>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)]">
|
||||
{{ p.badge || 'Plano' }}
|
||||
</div>
|
||||
<div class="text-xl font-semibold">
|
||||
{{ p.public_name || p.plan_name || p.plan_key }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Tag v-if="p.is_featured" severity="success" value="Popular" />
|
||||
</div>
|
||||
|
||||
<div class="mt-4 text-3xl font-semibold leading-none">
|
||||
{{ formatBRLFromCents(priceFor(p)) }}
|
||||
<span class="text-sm font-normal text-[var(--text-color-secondary)]">
|
||||
/{{ billingInterval === 'month' ? 'mês' : 'ano' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="billingInterval === 'year'"
|
||||
class="text-xs text-emerald-500 mt-1 font-medium"
|
||||
>
|
||||
Melhor custo-benefício
|
||||
</div>
|
||||
|
||||
<div class="mt-2 text-sm text-[var(--text-color-secondary)] min-h-[44px]">
|
||||
{{ p.public_description }}
|
||||
</div>
|
||||
|
||||
<Divider class="my-4" />
|
||||
|
||||
<ul v-if="p.bullets?.length" class="space-y-2 text-sm">
|
||||
<li v-for="b in p.bullets" :key="b.id" class="flex items-start gap-2">
|
||||
<i class="pi pi-check mt-1 text-emerald-500"></i>
|
||||
<span :class="b.highlight ? 'font-semibold' : 'text-[var(--text-color-secondary)]'">
|
||||
{{ b.text }}
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div v-else class="text-sm text-[var(--text-color-secondary)]">Benefícios em breve.</div>
|
||||
|
||||
<div class="mt-5">
|
||||
<Button
|
||||
label="Começar"
|
||||
class="w-full"
|
||||
:severity="p.is_featured ? 'success' : 'secondary'"
|
||||
:outlined="!p.is_featured"
|
||||
icon="pi pi-arrow-right"
|
||||
@click="go(`/auth/signup?plan=${p.plan_key}&interval=${billingInterval}`)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
<div v-if="billingInterval === 'year'" class="mt-2">
|
||||
<Tag severity="success" value="Economize até 20%" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 text-xs text-[var(--text-color-secondary)]">
|
||||
Dica: estes planos vêm do painel SaaS (vitrine pública) e podem mapear diretamente para entitlements (FREE/PRO)
|
||||
sem mexer no código.
|
||||
<div v-if="loadingPricing" class="mt-8">
|
||||
<div class="grid grid-cols-12 gap-4">
|
||||
<div v-for="i in 3" :key="i" class="col-span-12 md:col-span-4">
|
||||
<div class="rounded-[2rem] border border-[var(--surface-border)] bg-[var(--surface-card)] p-5">
|
||||
<div class="h-4 w-24 bg-[color-mix(in_srgb,var(--surface-200),transparent_40%)] rounded mb-3 animate-pulse" />
|
||||
<div class="h-7 w-40 bg-[color-mix(in_srgb,var(--surface-200),transparent_40%)] rounded mb-4 animate-pulse" />
|
||||
<div class="h-10 w-48 bg-[color-mix(in_srgb,var(--surface-200),transparent_40%)] rounded mb-4 animate-pulse" />
|
||||
<div class="space-y-2">
|
||||
<div class="h-3 w-full bg-[color-mix(in_srgb,var(--surface-200),transparent_40%)] rounded animate-pulse" />
|
||||
<div class="h-3 w-11/12 bg-[color-mix(in_srgb,var(--surface-200),transparent_40%)] rounded animate-pulse" />
|
||||
<div class="h-3 w-10/12 bg-[color-mix(in_srgb,var(--surface-200),transparent_40%)] rounded animate-pulse" />
|
||||
</div>
|
||||
<div class="h-10 w-full bg-[color-mix(in_srgb,var(--surface-200),transparent_40%)] rounded-xl mt-6 animate-pulse" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="mt-8">
|
||||
<div v-if="!pricing.length" class="rounded-[2rem] border border-[var(--surface-border)] bg-[var(--surface-card)] p-6 text-center">
|
||||
<div class="text-lg font-semibold">Planos em preparação</div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] mt-1">
|
||||
Ainda não há itens visíveis na vitrine pública. Publique no painel SaaS para aparecer aqui.
|
||||
</div>
|
||||
<div class="mt-4 flex justify-center gap-2 flex-wrap">
|
||||
<Button label="Entrar" severity="secondary" outlined icon="pi pi-sign-in" @click="go('/auth/login')" />
|
||||
<Button label="Criar conta" icon="pi pi-bolt" @click="goStart()" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="grid grid-cols-12 gap-4">
|
||||
<div v-for="p in pricing" :key="p.plan_id" class="col-span-12 md:col-span-4">
|
||||
<div
|
||||
class="h-full rounded-[2rem] border border-[var(--surface-border)] bg-[var(--surface-card)] overflow-hidden transition-transform duration-300"
|
||||
:class="p.is_featured ? 'ring-1 ring-emerald-500/30 md:-translate-y-2 md:scale-[1.02]' : 'hover:-translate-y-1'"
|
||||
>
|
||||
<div class="relative p-5">
|
||||
<div v-if="p.is_featured" class="pointer-events-none absolute inset-0 opacity-70">
|
||||
<div class="absolute -top-20 -right-24 h-72 w-72 rounded-full bg-emerald-400/10 blur-3xl" />
|
||||
<div class="absolute -bottom-24 left-10 h-72 w-72 rounded-full bg-indigo-400/10 blur-3xl" />
|
||||
</div>
|
||||
|
||||
<div class="relative">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm text-[var(--text-color-secondary)]">
|
||||
{{ p.badge || 'Plano' }}
|
||||
</div>
|
||||
<div class="text-xl font-semibold truncate">
|
||||
{{ p.public_name || p.plan_name || p.plan_key }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Tag v-if="p.is_featured" severity="success" value="Popular" />
|
||||
</div>
|
||||
|
||||
<div class="mt-4 text-3xl font-semibold leading-none">
|
||||
{{ formatBRLFromCents(priceFor(p)) }}
|
||||
<span class="text-sm font-normal text-[var(--text-color-secondary)]">
|
||||
/{{ billingInterval === 'month' ? 'mês' : 'ano' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="billingInterval === 'year'" class="text-xs text-emerald-500 mt-1 font-medium">
|
||||
Melhor custo-benefício
|
||||
</div>
|
||||
|
||||
<div class="mt-2 text-sm text-[var(--text-color-secondary)] min-h-[44px] leading-relaxed">
|
||||
{{ p.public_description || '—' }}
|
||||
</div>
|
||||
|
||||
<Divider class="my-4" />
|
||||
|
||||
<ul v-if="p.bullets?.length" class="space-y-2 text-sm">
|
||||
<li v-for="b in p.bullets" :key="b.id" class="flex items-start gap-2">
|
||||
<i class="pi pi-check mt-1 text-emerald-500"></i>
|
||||
<span :class="b.highlight ? 'font-semibold' : 'text-[var(--text-color-secondary)]'">
|
||||
{{ b.text }}
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div v-else class="text-sm text-[var(--text-color-secondary)]">
|
||||
Benefícios em breve.
|
||||
</div>
|
||||
|
||||
<div class="mt-5">
|
||||
<Button
|
||||
label="Começar"
|
||||
class="w-full"
|
||||
:severity="p.is_featured ? 'success' : 'secondary'"
|
||||
:outlined="!p.is_featured"
|
||||
icon="pi pi-arrow-right"
|
||||
@click="go(`/auth/signup?plan=${encodeURIComponent(p.plan_key)}&interval=${billingInterval}`)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 text-xs text-[var(--text-color-secondary)]">
|
||||
Plano vem da vitrine SaaS — sem mexer no código.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 text-xs text-[var(--text-color-secondary)]">
|
||||
Dica: esses planos podem mapear diretamente para entitlements (FREE/PRO) e features (plan_features).
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- FOOTER -->
|
||||
<footer class="border-t border-[var(--surface-border)]">
|
||||
<div
|
||||
class="mx-auto max-w-7xl px-4 md:px-6 py-8 flex flex-col md:flex-row items-start md:items-center justify-between gap-4"
|
||||
>
|
||||
<div class="mx-auto max-w-7xl px-4 md:px-6 py-8 flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
|
||||
<div>
|
||||
<div class="font-semibold">{{ brandName }}</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">© {{ year }} — Todos os direitos reservados.</div>
|
||||
<div class="text-xs text-[var(--text-color-secondary)] mt-1">
|
||||
© {{ year }} — Todos os direitos reservados.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
@@ -417,77 +563,31 @@ import { computed, ref, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
|
||||
import Button from 'primevue/button'
|
||||
import Card from 'primevue/card'
|
||||
import Divider from 'primevue/divider'
|
||||
import Tag from 'primevue/tag'
|
||||
import Chip from 'primevue/chip'
|
||||
import Accordion from 'primevue/accordion'
|
||||
import AccordionTab from 'primevue/accordiontab'
|
||||
import Avatar from 'primevue/avatar'
|
||||
import AvatarGroup from 'primevue/avatargroup'
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
const brandName = 'Psi Quasar' // ajuste para o nome final do produto
|
||||
const brandName = 'Agência PSI' // ajuste para o nome final do produto
|
||||
const year = computed(() => new Date().getFullYear())
|
||||
|
||||
function go(path) {
|
||||
function go (path) {
|
||||
router.push(path)
|
||||
}
|
||||
|
||||
function scrollTo(id) {
|
||||
function scrollTo (id) {
|
||||
const el = document.getElementById(id)
|
||||
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' })
|
||||
}
|
||||
|
||||
const featuredPlanKey = computed(() => {
|
||||
const list = Array.isArray(pricing.value) ? pricing.value : []
|
||||
const featured = list.find(p => p && p.is_featured && p.is_visible)
|
||||
return featured?.plan_key || null
|
||||
})
|
||||
|
||||
function goStart() {
|
||||
if (featuredPlanKey.value) {
|
||||
router.push(`/auth/signup?plan=${featuredPlanKey.value}&interval=${billingInterval.value}`)
|
||||
return
|
||||
}
|
||||
|
||||
router.push('/auth/signup')
|
||||
}
|
||||
|
||||
const features = ref([
|
||||
{
|
||||
title: 'Agenda inteligente',
|
||||
desc: 'Configure sua semana, encaixes, bloqueios e visão por dia/semana.',
|
||||
icon: 'pi pi-calendar'
|
||||
},
|
||||
{
|
||||
title: 'Autoagendamento (PRO)',
|
||||
desc: 'Página para o paciente confirmar, agendar e reagendar sem fricção.',
|
||||
icon: 'pi pi-globe',
|
||||
pro: true
|
||||
},
|
||||
{
|
||||
title: 'Prontuário e sessões',
|
||||
desc: 'Registro por paciente, histórico por sessão e organização por linha do tempo.',
|
||||
icon: 'pi pi-file-edit'
|
||||
},
|
||||
{
|
||||
title: 'Financeiro integrado',
|
||||
desc: 'Receitas, despesas e visão do mês conectadas ao que acontece na agenda.',
|
||||
icon: 'pi pi-wallet'
|
||||
},
|
||||
{
|
||||
title: 'Pacientes e tags',
|
||||
desc: 'Segmentação por grupos, etiquetas e filtros práticos para achar rápido.',
|
||||
icon: 'pi pi-users'
|
||||
},
|
||||
{
|
||||
title: 'Clínica / multi-profissional',
|
||||
desc: 'Múltiplos profissionais, agendas separadas, papéis e visão gerencial.',
|
||||
icon: 'pi pi-building'
|
||||
}
|
||||
{ title: 'Agenda inteligente', desc: 'Configure semana, encaixes, bloqueios e visão por dia/semana.', icon: 'pi pi-calendar' },
|
||||
{ title: 'Autoagendamento (PRO)', desc: 'Página para o paciente confirmar, agendar e reagendar sem fricção.', icon: 'pi pi-globe', pro: true },
|
||||
{ title: 'Prontuário e sessões', desc: 'Registro por paciente, histórico por sessão e linha do tempo.', icon: 'pi pi-file-edit' },
|
||||
{ title: 'Financeiro integrado', desc: 'Receitas e despesas conectadas ao que acontece na agenda.', icon: 'pi pi-wallet' },
|
||||
{ title: 'Pacientes e tags', desc: 'Segmentação por grupos, etiquetas e filtros para achar rápido.', icon: 'pi pi-users' },
|
||||
{ title: 'Clínica / multi-profissional', desc: 'Múltiplos profissionais, papéis, convites e visão gerencial.', icon: 'pi pi-building' }
|
||||
])
|
||||
|
||||
/** PRICING dinâmico do SaaS */
|
||||
@@ -495,29 +595,82 @@ const billingInterval = ref('year') // 'month' | 'year'
|
||||
const pricing = ref([])
|
||||
const loadingPricing = ref(false)
|
||||
|
||||
function formatBRLFromCents(cents) {
|
||||
const featuredPlanKey = computed(() => {
|
||||
const list = Array.isArray(pricing.value) ? pricing.value : []
|
||||
const featured = list.find(p => p && p.is_featured && p.is_visible)
|
||||
return featured?.plan_key || null
|
||||
})
|
||||
|
||||
function goStart () {
|
||||
if (featuredPlanKey.value) {
|
||||
router.push(`/auth/signup?plan=${encodeURIComponent(featuredPlanKey.value)}&interval=${billingInterval.value}`)
|
||||
return
|
||||
}
|
||||
router.push('/auth/signup')
|
||||
}
|
||||
|
||||
function formatBRLFromCents (cents) {
|
||||
if (cents == null) return '—'
|
||||
const v = Number(cents) / 100
|
||||
if (!Number.isFinite(v)) return '—'
|
||||
return v.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })
|
||||
}
|
||||
|
||||
function priceFor(p) {
|
||||
return billingInterval.value === 'year' ? p.yearly_cents : p.monthly_cents
|
||||
function priceFor (p) {
|
||||
if (!p) return null
|
||||
const cents = billingInterval.value === 'year' ? p.yearly_cents : p.monthly_cents
|
||||
// fallback: se não existir anual, mostra mensal (e vice-versa)
|
||||
if (cents == null) return billingInterval.value === 'year' ? p.monthly_cents : p.yearly_cents
|
||||
return cents
|
||||
}
|
||||
|
||||
async function fetchPricing() {
|
||||
async function fetchPricing () {
|
||||
loadingPricing.value = true
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('v_public_pricing')
|
||||
.select('*')
|
||||
.eq('is_visible', true)
|
||||
.order('sort_order', { ascending: true })
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('v_public_pricing')
|
||||
.select('*')
|
||||
.eq('is_visible', true)
|
||||
.order('sort_order', { ascending: true })
|
||||
|
||||
loadingPricing.value = false
|
||||
|
||||
if (!error) pricing.value = data || []
|
||||
if (!error) pricing.value = data || []
|
||||
} finally {
|
||||
loadingPricing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(fetchPricing)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.hero-grid {
|
||||
background-image:
|
||||
linear-gradient(to right, rgba(255,255,255,0.06) 1px, transparent 1px),
|
||||
linear-gradient(to bottom, rgba(255,255,255,0.06) 1px, transparent 1px);
|
||||
background-size: 44px 44px;
|
||||
mask-image: radial-gradient(circle at 30% 20%, black 0%, transparent 65%);
|
||||
}
|
||||
|
||||
.hero-noise {
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='160' height='160' filter='url(%23n)' opacity='.35'/%3E%3C/svg%3E");
|
||||
background-size: 180px 180px;
|
||||
}
|
||||
|
||||
.hero-underline {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.hero-underline::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: -2%;
|
||||
right: -2%;
|
||||
bottom: 0.12em;
|
||||
height: 0.5em;
|
||||
background: linear-gradient(90deg, rgba(16,185,129,0.0), rgba(16,185,129,0.22), rgba(99,102,241,0.18), rgba(16,185,129,0.0));
|
||||
border-radius: 999px;
|
||||
z-index: -1;
|
||||
filter: blur(0.2px);
|
||||
}
|
||||
</style>
|
||||
@@ -63,9 +63,6 @@
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import Button from 'primevue/button'
|
||||
import Card from 'primevue/card'
|
||||
import InputText from 'primevue/inputtext'
|
||||
import Message from 'primevue/message'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
<!-- src/views/pages/auth/SignupPage.vue -->
|
||||
<script setup>
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
|
||||
import Card from 'primevue/card'
|
||||
import Button from 'primevue/button'
|
||||
import InputText from 'primevue/inputtext'
|
||||
import FloatLabel from 'primevue/floatlabel'
|
||||
import Password from 'primevue/password'
|
||||
import Divider from 'primevue/divider'
|
||||
import Tag from 'primevue/tag'
|
||||
import Chip from 'primevue/chip'
|
||||
import Message from 'primevue/message'
|
||||
import ProgressSpinner from 'primevue/progressspinner'
|
||||
@@ -26,13 +21,18 @@ const email = ref('')
|
||||
const password = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
// validação simples (sem “viajar”)
|
||||
const emailOk = computed(() => /\S+@\S+\.\S+/.test(String(email.value || '').trim()))
|
||||
const passwordOk = computed(() => String(password.value || '').length >= 6)
|
||||
const canSubmit = computed(() => !loading.value && emailOk.value && passwordOk.value)
|
||||
|
||||
// ============================
|
||||
// Query (plan / interval)
|
||||
// ============================
|
||||
const planFromQuery = computed(() => String(route.query.plan || '').trim().toLowerCase())
|
||||
const intervalFromQuery = computed(() => String(route.query.interval || '').trim().toLowerCase())
|
||||
|
||||
function normalizeInterval(v) {
|
||||
function normalizeInterval (v) {
|
||||
if (v === 'monthly') return 'month'
|
||||
if (v === 'annual' || v === 'annually' || v === 'yearly') return 'year'
|
||||
return v
|
||||
@@ -40,7 +40,7 @@ function normalizeInterval(v) {
|
||||
|
||||
const intervalNormalized = computed(() => normalizeInterval(intervalFromQuery.value))
|
||||
|
||||
function isValidInterval(v) {
|
||||
function isValidInterval (v) {
|
||||
return v === 'month' || v === 'year'
|
||||
}
|
||||
|
||||
@@ -67,29 +67,36 @@ const bullets = computed(() => {
|
||||
return Array.isArray(b) ? b : []
|
||||
})
|
||||
|
||||
const amountCents = computed(() => {
|
||||
if (!selectedPlanRow.value) return null
|
||||
return intervalNormalized.value === 'year'
|
||||
? selectedPlanRow.value.yearly_cents
|
||||
: selectedPlanRow.value.monthly_cents
|
||||
})
|
||||
function amountForInterval (row, interval) {
|
||||
if (!row) return null
|
||||
const cents = interval === 'year' ? row.yearly_cents : row.monthly_cents
|
||||
// fallback (se não existir preço no intervalo escolhido)
|
||||
if (cents == null) return interval === 'year' ? row.monthly_cents : row.yearly_cents
|
||||
return cents
|
||||
}
|
||||
|
||||
const currency = computed(() => {
|
||||
if (!selectedPlanRow.value) return 'BRL'
|
||||
return intervalNormalized.value === 'year'
|
||||
? (selectedPlanRow.value.yearly_currency || 'BRL')
|
||||
: (selectedPlanRow.value.monthly_currency || 'BRL')
|
||||
})
|
||||
function currencyForInterval (row, interval) {
|
||||
if (!row) return 'BRL'
|
||||
const cur = interval === 'year' ? (row.yearly_currency || 'BRL') : (row.monthly_currency || 'BRL')
|
||||
return cur || 'BRL'
|
||||
}
|
||||
|
||||
const amountCents = computed(() => amountForInterval(selectedPlanRow.value, intervalNormalized.value))
|
||||
const currency = computed(() => currencyForInterval(selectedPlanRow.value, intervalNormalized.value))
|
||||
|
||||
const formattedPrice = computed(() => {
|
||||
if (amountCents.value == null) return null
|
||||
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: currency.value || 'BRL' })
|
||||
.format(amountCents.value / 100)
|
||||
try {
|
||||
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: currency.value || 'BRL' })
|
||||
.format(Number(amountCents.value) / 100)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
})
|
||||
|
||||
const showPlanCard = computed(() => hasPlanQuery.value && !!selectedPlanRow.value)
|
||||
|
||||
async function loadSelectedPlanRow() {
|
||||
async function loadSelectedPlanRow () {
|
||||
selectedPlanRow.value = null
|
||||
if (!planFromQuery.value) return
|
||||
|
||||
@@ -117,59 +124,14 @@ async function loadSelectedPlanRow() {
|
||||
onMounted(loadSelectedPlanRow)
|
||||
|
||||
watch(
|
||||
() => planFromQuery.value,
|
||||
() => [planFromQuery.value, intervalNormalized.value],
|
||||
() => loadSelectedPlanRow()
|
||||
)
|
||||
|
||||
// ============================
|
||||
// Create subscription_intent after signup
|
||||
// subscription_intent (MODELO B: tenant)
|
||||
// ============================
|
||||
/*
|
||||
async function createSubscriptionIntentAfterSignup(userId, tenantIdFromRpc) {
|
||||
if (!hasPlanQuery.value) return
|
||||
if (!selectedPlanRow.value) return
|
||||
if (amountCents.value == null) return
|
||||
|
||||
let tenantId = tenantIdFromRpc || null
|
||||
|
||||
// fallback (se a RPC não retornou)
|
||||
if (!tenantId) {
|
||||
const { data, error } = await supabase
|
||||
.from('tenant_members')
|
||||
.select('tenant_id')
|
||||
.eq('user_id', userId)
|
||||
.eq('status', 'active')
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
if (error) throw error
|
||||
tenantId = data?.tenant_id || null
|
||||
}
|
||||
|
||||
if (!tenantId) throw new Error('Não encontrei tenant ativo para este usuário.')
|
||||
|
||||
const payload = {
|
||||
tenant_id: tenantId,
|
||||
created_by_user_id: userId,
|
||||
email: email.value || null,
|
||||
plan_key: selectedPlanRow.value.plan_key,
|
||||
interval: intervalNormalized.value,
|
||||
amount_cents: amountCents.value,
|
||||
currency: currency.value || 'BRL',
|
||||
status: 'new',
|
||||
source: 'landing'
|
||||
}
|
||||
|
||||
const { error } = await supabase.from('subscription_intents').insert(payload)
|
||||
if (error) throw error
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
// ============================
|
||||
// Create subscription_intent after signup (MODELO B: tenant)
|
||||
// ============================
|
||||
async function getActiveTenantIdForUser(userId) {
|
||||
async function getActiveTenantIdForUser (userId) {
|
||||
const { data, error } = await supabase
|
||||
.from('tenant_members')
|
||||
.select('tenant_id')
|
||||
@@ -183,22 +145,22 @@ async function getActiveTenantIdForUser(userId) {
|
||||
return data?.tenant_id || null
|
||||
}
|
||||
|
||||
async function createSubscriptionIntentAfterSignup(userId) {
|
||||
async function createSubscriptionIntentAfterSignup (userId, preferredTenantId = null) {
|
||||
if (!hasPlanQuery.value) return
|
||||
if (!selectedPlanRow.value) return
|
||||
if (amountCents.value == null) return
|
||||
|
||||
const tenantId = await getActiveTenantIdForUser(userId)
|
||||
const tenantId = preferredTenantId || (await getActiveTenantIdForUser(userId))
|
||||
if (!tenantId) throw new Error('Não encontrei tenant ativo para este usuário.')
|
||||
|
||||
const payload = {
|
||||
tenant_id: tenantId,
|
||||
created_by_user_id: userId,
|
||||
|
||||
// opcional: manter user_id por compat/telemetria (se sua tabela ainda tem a coluna)
|
||||
// opcional (se sua tabela ainda tem user_id)
|
||||
user_id: userId,
|
||||
|
||||
email: email.value || null,
|
||||
email: String(email.value || '').trim().toLowerCase() || null,
|
||||
plan_key: selectedPlanRow.value.plan_key,
|
||||
interval: intervalNormalized.value,
|
||||
amount_cents: amountCents.value,
|
||||
@@ -211,30 +173,33 @@ async function createSubscriptionIntentAfterSignup(userId) {
|
||||
if (error) throw error
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ============================
|
||||
// Actions
|
||||
// Nav
|
||||
// ============================
|
||||
function goLogin() {
|
||||
function goLogin () {
|
||||
router.push({
|
||||
path: '/auth/login',
|
||||
query: email.value ? { email: email.value } : undefined
|
||||
query: email.value ? { email: String(email.value).trim() } : undefined
|
||||
})
|
||||
}
|
||||
|
||||
function goBackPricing() {
|
||||
function goBackPricing () {
|
||||
// você usa /lp#pricing — mantive
|
||||
router.push('/lp#pricing')
|
||||
}
|
||||
|
||||
// ============================
|
||||
// Signup
|
||||
// ============================
|
||||
async function onSignup() {
|
||||
async function onSignup () {
|
||||
if (!canSubmit.value) return
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
const cleanEmail = String(email.value || '').trim().toLowerCase()
|
||||
|
||||
const { data, error } = await supabase.auth.signUp({
|
||||
email: email.value,
|
||||
email: cleanEmail,
|
||||
password: password.value
|
||||
})
|
||||
|
||||
@@ -242,7 +207,7 @@ async function onSignup() {
|
||||
|
||||
const userId = data?.user?.id || null
|
||||
|
||||
// ✅ Modelo B: garante tenant pessoal e captura tenant_id
|
||||
// ✅ Modelo B: garante tenant pessoal (não aborta se falhar)
|
||||
let tenantId = null
|
||||
if (userId) {
|
||||
try {
|
||||
@@ -250,7 +215,6 @@ async function onSignup() {
|
||||
tenantId = resTenant?.data || null
|
||||
} catch (e) {
|
||||
console.warn('[Signup] ensure_personal_tenant falhou:', e)
|
||||
// não aborta signup por isso
|
||||
}
|
||||
|
||||
// ✅ intent (não quebra signup se falhar)
|
||||
@@ -308,7 +272,6 @@ async function onSignup() {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -323,7 +286,7 @@ async function onSignup() {
|
||||
<div class="relative w-full max-w-6xl">
|
||||
<div class="rounded-3xl border border-[var(--surface-border)] bg-[var(--surface-card)] shadow-sm overflow-hidden">
|
||||
<div class="grid grid-cols-12">
|
||||
<!-- LEFT: conceitual (estilo PrimeBlocks) -->
|
||||
<!-- LEFT -->
|
||||
<div class="col-span-12 lg:col-span-6 p-6 md:p-10 bg-[color-mix(in_srgb,var(--surface-card),transparent_6%)] border-b lg:border-b-0 lg:border-r border-[var(--surface-border)]">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="h-11 w-11 rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-ground)] grid place-items-center">
|
||||
@@ -341,7 +304,7 @@ async function onSignup() {
|
||||
Menos dispersão. Mais presença.
|
||||
</div>
|
||||
|
||||
<div class="mt-3 text-sm md:text-base text-[var(--text-color-secondary)] max-w-lg">
|
||||
<div class="mt-3 text-sm md:text-base text-[var(--text-color-secondary)] max-w-lg leading-relaxed">
|
||||
Crie sua conta e siga para o pagamento manual (PIX/boleto). Assim que confirmado, seu plano é ativado
|
||||
e as funcionalidades liberadas.
|
||||
</div>
|
||||
@@ -387,7 +350,7 @@ async function onSignup() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- RIGHT: Card login/signup + plano no topo -->
|
||||
<!-- RIGHT -->
|
||||
<div class="col-span-12 lg:col-span-6 p-6 md:p-10">
|
||||
<div class="max-w-md mx-auto">
|
||||
<div class="text-2xl font-semibold">Criar conta</div>
|
||||
@@ -396,25 +359,26 @@ async function onSignup() {
|
||||
<a class="cursor-pointer font-medium" @click.prevent="goLogin">Entrar</a>
|
||||
</div>
|
||||
|
||||
<!-- Plano (card único, dentro da direita) -->
|
||||
<!-- Plano -->
|
||||
<div class="mt-5">
|
||||
<div v-if="pricingLoading" class="flex items-center gap-2 text-sm text-[var(--text-color-secondary)]">
|
||||
<ProgressSpinner style="width: 18px; height: 18px" strokeWidth="4" />
|
||||
Carregando plano…
|
||||
</div>
|
||||
|
||||
<Card v-else-if="showPlanCard" class="overflow-hidden">
|
||||
<Card v-else-if="showPlanCard" class="overflow-hidden rounded-[2rem]">
|
||||
<template #content>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-xs text-[var(--text-color-secondary)]">Plano selecionado</div>
|
||||
|
||||
<div class="mt-1 flex items-center gap-2 flex-wrap">
|
||||
<div class="text-lg font-semibold truncate">
|
||||
{{ selectedPlanName }}
|
||||
</div>
|
||||
<Tag v-if="selectedPlanRow?.is_featured" severity="success" value="Popular" />
|
||||
<Tag v-if="selectedBadge" severity="secondary" :value="selectedBadge" />
|
||||
<Chip :label="intervalLabel" />
|
||||
<Chip v-if="intervalLabel" :label="intervalLabel" />
|
||||
</div>
|
||||
|
||||
<div class="mt-2 text-2xl font-semibold leading-none">
|
||||
@@ -424,14 +388,14 @@ async function onSignup() {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="selectedDescription" class="mt-2 text-sm text-[var(--text-color-secondary)]">
|
||||
<div v-if="selectedDescription" class="mt-2 text-sm text-[var(--text-color-secondary)] leading-relaxed">
|
||||
{{ selectedDescription }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
icon="pi pi-pencil"
|
||||
label="Trocar"
|
||||
label="Trocar"
|
||||
severity="secondary"
|
||||
text
|
||||
rounded
|
||||
@@ -460,14 +424,28 @@ async function onSignup() {
|
||||
<Message v-else-if="hasPlanQuery && !selectedPlanRow" severity="warn" class="mb-0">
|
||||
Não encontrei esse plano na vitrine pública. Você ainda pode criar a conta normalmente.
|
||||
<div class="mt-2">
|
||||
<Button label="Ver planos" icon="pi pi-credit-card" severity="secondary" outlined class="w-full" @click="goBackPricing" />
|
||||
<Button
|
||||
label="Ver planos"
|
||||
icon="pi pi-credit-card"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="w-full"
|
||||
@click="goBackPricing"
|
||||
/>
|
||||
</div>
|
||||
</Message>
|
||||
|
||||
<Message v-else severity="info" class="mb-0">
|
||||
Você está criando a conta sem seleção de plano.
|
||||
<div class="mt-2">
|
||||
<Button label="Ver planos" icon="pi pi-credit-card" severity="secondary" outlined class="w-full" @click="goBackPricing" />
|
||||
<Button
|
||||
label="Ver planos"
|
||||
icon="pi pi-credit-card"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="w-full"
|
||||
@click="goBackPricing"
|
||||
/>
|
||||
</div>
|
||||
</Message>
|
||||
|
||||
@@ -480,96 +458,80 @@ async function onSignup() {
|
||||
</Message>
|
||||
</div>
|
||||
|
||||
<!-- Form -->
|
||||
<Divider class="my-6" />
|
||||
|
||||
<div class="mt-5">
|
||||
<!-- Social (opcional: deixa visual, mas desabilitado por enquanto) -->
|
||||
<div class="grid grid-cols-12 gap-2">
|
||||
<div class="col-span-12 md:col-span-6">
|
||||
<Button
|
||||
label="Sign up with Facebook"
|
||||
icon="pi pi-facebook"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="w-full"
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
<div class="col-span-12 md:col-span-6">
|
||||
<Button
|
||||
label="Sign up with Google"
|
||||
icon="pi pi-google"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="w-full"
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Form -->
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<FloatLabel variant="on">
|
||||
<InputText
|
||||
id="signup_email"
|
||||
v-model="email"
|
||||
class="w-full"
|
||||
autocomplete="email"
|
||||
:disabled="loading"
|
||||
@keydown.enter.prevent="onSignup"
|
||||
/>
|
||||
<label for="signup_email">Seu melhor e-mail</label>
|
||||
</FloatLabel>
|
||||
|
||||
<!-- Divider OR -->
|
||||
<div class="flex items-center gap-3 my-5">
|
||||
<div class="flex-1 h-px bg-[var(--surface-border)]"></div>
|
||||
<div class="text-sm text-[var(--text-color-secondary)] font-medium">or</div>
|
||||
<div class="flex-1 h-px bg-[var(--surface-border)]"></div>
|
||||
</div>
|
||||
<div v-if="email && !emailOk" class="mt-2 text-xs text-orange-600">
|
||||
Informe um e-mail válido.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Email -->
|
||||
<div class="mb-4">
|
||||
<FloatLabel variant="on">
|
||||
<InputText
|
||||
id="email"
|
||||
v-model="email"
|
||||
class="w-full"
|
||||
autocomplete="email"
|
||||
/>
|
||||
<label for="email">Seu melhor e-mail</label>
|
||||
</FloatLabel>
|
||||
</div>
|
||||
<div>
|
||||
<FloatLabel variant="on">
|
||||
<Password
|
||||
v-model="password"
|
||||
inputId="signup_password"
|
||||
toggleMask
|
||||
:feedback="true"
|
||||
autocomplete="new-password"
|
||||
:disabled="loading"
|
||||
@keydown.enter.prevent="onSignup"
|
||||
:pt="{
|
||||
root: { class: 'w-full' },
|
||||
input: { class: 'w-full' }
|
||||
}"
|
||||
/>
|
||||
<label for="signup_password">Senha</label>
|
||||
</FloatLabel>
|
||||
|
||||
<div v-if="password && !passwordOk" class="mt-2 text-xs text-orange-600">
|
||||
Use pelo menos 6 caracteres.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Password -->
|
||||
<div class="mb-3">
|
||||
<FloatLabel variant="on">
|
||||
<Password
|
||||
v-model="password"
|
||||
toggleMask
|
||||
:feedback="true"
|
||||
inputClass="w-full pr-5"
|
||||
autocomplete="current-password"
|
||||
:disabled="loading || loadingRecovery"
|
||||
:pt="{
|
||||
root: { class: 'w-full' },
|
||||
input: { class: 'w-full' },
|
||||
icon: { class: 'right-3' }
|
||||
}"
|
||||
/>
|
||||
<label for="password">Password</label>
|
||||
</FloatLabel>
|
||||
</div>
|
||||
<Button
|
||||
label="CRIAR CONTA"
|
||||
class="w-full"
|
||||
severity="success"
|
||||
:loading="loading"
|
||||
:disabled="!canSubmit"
|
||||
icon="pi pi-arrow-right"
|
||||
@click="onSignup"
|
||||
/>
|
||||
|
||||
<!-- CTA -->
|
||||
<Button
|
||||
label="CRIAR CONTA"
|
||||
class="w-full"
|
||||
:loading="loading"
|
||||
@click="onSignup"
|
||||
style="background: #10b981; border-color: #10b981"
|
||||
/>
|
||||
<div class="text-xs text-center text-[var(--text-color-secondary)]">
|
||||
Ao criar a conta, registramos sua intenção de assinatura.
|
||||
Pagamento é manual (PIX/boleto) por enquanto.
|
||||
</div>
|
||||
|
||||
<div class="text-xs text-center text-[var(--text-color-secondary)] mt-3">
|
||||
Ao criar a conta, registramos sua intenção de assinatura. Pagamento é manual (PIX/boleto) por enquanto.
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-xs text-center">
|
||||
<a class="cursor-pointer text-[var(--text-color-secondary)] hover:underline" @click.prevent="goLogin">
|
||||
Já tenho conta — entrar
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text-center text-xs text-[var(--text-color-secondary)] mt-4">
|
||||
Psi Quasar — gestão clínica sem ruído.
|
||||
Agência PSI — gestão clínica sem ruído.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
@@ -1,120 +1,295 @@
|
||||
<script setup>
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
import { useConfirm } from 'primevue/useconfirm'
|
||||
|
||||
import Card from 'primevue/card'
|
||||
import Button from 'primevue/button'
|
||||
import Tag from 'primevue/tag'
|
||||
import Toast from 'primevue/toast'
|
||||
import Chart from 'primevue/chart'
|
||||
import DataTable from 'primevue/datatable'
|
||||
import Column from 'primevue/column'
|
||||
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
const confirm = useConfirm()
|
||||
|
||||
const loading = ref(false)
|
||||
|
||||
// KPIs
|
||||
const totalActive = ref(0)
|
||||
const totalCanceled = ref(0)
|
||||
const totalMismatches = ref(0)
|
||||
|
||||
const plans = ref([])
|
||||
const subs = ref([])
|
||||
const plans = ref([]) // plans: id,key,target,is_active
|
||||
const prices = ref([]) // v_plan_active_prices
|
||||
const subs = ref([]) // subscriptions
|
||||
|
||||
// ------------------------------------
|
||||
// Intenções de assinatura (subscription_intents)
|
||||
// ------------------------------------
|
||||
const intents = ref([])
|
||||
const intentsLoading = ref(false)
|
||||
const intentsLimit = ref(12) // quantas mostrar no card
|
||||
const totalIntents = ref(0)
|
||||
const totalIntentsNew = ref(0)
|
||||
const totalIntentsPaid = ref(0)
|
||||
|
||||
// intervalo de exibição (MRR / ARPA)
|
||||
const intervalView = ref('month') // 'month' | 'year'
|
||||
const intervalOptions = [
|
||||
{ label: 'Mensal (MRR)', value: 'month' },
|
||||
{ label: 'Anual (ARR)', value: 'year' }
|
||||
]
|
||||
|
||||
const lastUpdatedAt = ref(null)
|
||||
|
||||
// ------------------------------------
|
||||
// Utils
|
||||
// ------------------------------------
|
||||
function moneyBRLFromCents (cents) {
|
||||
const v = Number(cents || 0) / 100
|
||||
return v.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })
|
||||
}
|
||||
|
||||
/**
|
||||
* MRR = soma de price_cents do plano para subscriptions ativas (intervalo month).
|
||||
* Se no futuro você tiver anual, dá pra normalizar (annual/12).
|
||||
*/
|
||||
const mrrCents = computed(() => {
|
||||
const planById = new Map(plans.value.map(p => [p.id, p]))
|
||||
let sum = 0
|
||||
for (const s of subs.value) {
|
||||
if (s.status !== 'active') continue
|
||||
const p = planById.get(s.plan_id)
|
||||
if (!p) continue
|
||||
if ((p.billing_interval || 'month') !== 'month') continue
|
||||
sum += Number(p.price_cents || 0)
|
||||
function planTargetLabel (t) {
|
||||
if (t === 'clinic') return 'Clínica'
|
||||
if (t === 'therapist') return 'Terapeuta'
|
||||
return '—'
|
||||
}
|
||||
|
||||
function planTargetSeverity (t) {
|
||||
if (t === 'clinic') return 'info'
|
||||
if (t === 'therapist') return 'success'
|
||||
return 'secondary'
|
||||
}
|
||||
|
||||
function fmtDate (iso) {
|
||||
if (!iso) return '—'
|
||||
const d = new Date(iso)
|
||||
if (Number.isNaN(d.getTime())) return String(iso)
|
||||
return d.toLocaleString('pt-BR')
|
||||
}
|
||||
|
||||
function intervalLabel (v) {
|
||||
if (v === 'month') return 'Mensal'
|
||||
if (v === 'year') return 'Anual'
|
||||
return v || '—'
|
||||
}
|
||||
|
||||
function statusSeverity (s) {
|
||||
const st = String(s || '').toLowerCase()
|
||||
if (st === 'new') return 'info'
|
||||
if (st === 'paid') return 'success'
|
||||
if (st === 'canceled') return 'danger'
|
||||
if (st === 'expired') return 'warning'
|
||||
return 'secondary'
|
||||
}
|
||||
|
||||
function maskEmail (email) {
|
||||
const e = String(email || '').trim()
|
||||
if (!e.includes('@')) return e || '—'
|
||||
const [u, d] = e.split('@')
|
||||
if (!u) return `***@${d}`
|
||||
const head = u.slice(0, 1)
|
||||
return `${head}***@${d}`
|
||||
}
|
||||
|
||||
// ------------------------------------
|
||||
// Preços (view)
|
||||
// ------------------------------------
|
||||
const priceByPlanId = computed(() => {
|
||||
const m = new Map()
|
||||
for (const r of (prices.value || [])) m.set(r.plan_id, r)
|
||||
return m
|
||||
})
|
||||
|
||||
function priceCentsForPlan (planId, interval) {
|
||||
const pr = priceByPlanId.value.get(planId)
|
||||
if (!pr) return null
|
||||
return interval === 'year' ? (pr.yearly_cents ?? null) : (pr.monthly_cents ?? null)
|
||||
}
|
||||
|
||||
function normalizedRevenueCents (planId, viewInterval) {
|
||||
const m = priceCentsForPlan(planId, 'month')
|
||||
const y = priceCentsForPlan(planId, 'year')
|
||||
|
||||
if (viewInterval === 'month') {
|
||||
if (m != null) return Number(m)
|
||||
if (y != null) return Math.round(Number(y) / 12)
|
||||
return 0
|
||||
}
|
||||
|
||||
if (y != null) return Number(y)
|
||||
if (m != null) return Math.round(Number(m) * 12)
|
||||
return 0
|
||||
}
|
||||
|
||||
// ------------------------------------
|
||||
// KPIs
|
||||
// ------------------------------------
|
||||
const activeSubs = computed(() => (subs.value || []).filter(s => String(s.status) === 'active'))
|
||||
|
||||
const revenueCents = computed(() => {
|
||||
let sum = 0
|
||||
for (const s of activeSubs.value) sum += normalizedRevenueCents(s.plan_id, intervalView.value)
|
||||
return sum
|
||||
})
|
||||
|
||||
const arpaCents = computed(() => {
|
||||
const act = subs.value.filter(s => s.status === 'active').length
|
||||
return act ? Math.round(mrrCents.value / act) : 0
|
||||
const act = activeSubs.value.length
|
||||
return act ? Math.round(revenueCents.value / act) : 0
|
||||
})
|
||||
|
||||
// Health UI
|
||||
const healthSeverity = computed(() => {
|
||||
if (loading.value) return 'secondary'
|
||||
return totalMismatches.value > 0 ? 'danger' : 'success'
|
||||
})
|
||||
const healthLabel = computed(() => {
|
||||
if (loading.value) return 'carregando'
|
||||
return totalMismatches.value > 0 ? 'atenção' : 'ok'
|
||||
})
|
||||
const healthHint = computed(() => {
|
||||
if (totalMismatches.value <= 0) return 'Tudo consistente: plano esperado = entitlements atuais.'
|
||||
return 'Há divergências entre o plano esperado e os entitlements atuais.'
|
||||
})
|
||||
|
||||
// ------------------------------------
|
||||
// Breakdown por plano
|
||||
// ------------------------------------
|
||||
const breakdown = computed(() => {
|
||||
const planById = new Map(plans.value.map(p => [p.id, p]))
|
||||
const planById = new Map((plans.value || []).map(p => [p.id, p]))
|
||||
const agg = new Map()
|
||||
|
||||
for (const s of subs.value) {
|
||||
for (const s of (subs.value || [])) {
|
||||
const p = planById.get(s.plan_id)
|
||||
const key = p?.key || '(sem plano)'
|
||||
|
||||
if (!agg.has(key)) {
|
||||
agg.set(key, {
|
||||
plan_id: s.plan_id,
|
||||
plan_key: key,
|
||||
plan_target: p?.target || null,
|
||||
plan_active: p?.is_active !== false,
|
||||
active_count: 0,
|
||||
canceled_count: 0,
|
||||
price_cents: Number(p?.price_cents || 0),
|
||||
mrr_cents: 0
|
||||
price_cents: normalizedRevenueCents(s.plan_id, intervalView.value),
|
||||
revenue_cents: 0
|
||||
})
|
||||
}
|
||||
|
||||
const row = agg.get(key)
|
||||
if (s.status === 'active') {
|
||||
|
||||
if (String(s.status) === 'active') {
|
||||
row.active_count += 1
|
||||
// só soma MRR se for mensal
|
||||
if ((p?.billing_interval || 'month') === 'month') row.mrr_cents += Number(p?.price_cents || 0)
|
||||
} else if (s.status === 'canceled') {
|
||||
row.revenue_cents += normalizedRevenueCents(s.plan_id, intervalView.value)
|
||||
} else if (String(s.status) === 'canceled') {
|
||||
row.canceled_count += 1
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(agg.values()).sort((a, b) => (b.mrr_cents - a.mrr_cents))
|
||||
const out = Array.from(agg.values())
|
||||
out.sort((a, b) => (b.revenue_cents - a.revenue_cents))
|
||||
return out
|
||||
})
|
||||
|
||||
// Chart
|
||||
const chartData = computed(() => {
|
||||
const labels = breakdown.value.map(r => r.plan_key)
|
||||
const data = breakdown.value.map(r => Math.round((r.mrr_cents || 0) / 100))
|
||||
const data = breakdown.value.map(r => Math.round((r.revenue_cents || 0) / 100))
|
||||
return {
|
||||
labels,
|
||||
datasets: [{ label: 'MRR por plano (R$)', data }]
|
||||
datasets: [
|
||||
{
|
||||
label: intervalView.value === 'year' ? 'ARR por plano (R$)' : 'MRR por plano (R$)',
|
||||
data
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
|
||||
const chartOptions = computed(() => ({
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: { display: true }
|
||||
legend: { display: true },
|
||||
tooltip: { mode: 'index', intersect: false }
|
||||
},
|
||||
scales: {
|
||||
y: { beginAtZero: true }
|
||||
}
|
||||
scales: { y: { beginAtZero: true } }
|
||||
}))
|
||||
|
||||
// ------------------------------------
|
||||
// Navegação
|
||||
// ------------------------------------
|
||||
function openPlanPublic (planKey) {
|
||||
if (!planKey || planKey === '(sem plano)') return
|
||||
router.push({ path: '/saas/plans-public', query: { q: planKey } })
|
||||
}
|
||||
|
||||
function openPlanCatalog (planKey) {
|
||||
if (!planKey || planKey === '(sem plano)') return
|
||||
router.push({ path: '/saas/plans', query: { q: planKey } })
|
||||
}
|
||||
|
||||
function openIntentEvents () {
|
||||
router.push('/saas/subscription-events')
|
||||
}
|
||||
|
||||
// ------------------------------------
|
||||
// Fetch
|
||||
// ------------------------------------
|
||||
async function loadIntents () {
|
||||
intentsLoading.value = true
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('subscription_intents')
|
||||
.select('created_at,email,plan_key,interval,status,tenant_id')
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(intentsLimit.value)
|
||||
|
||||
if (error) throw error
|
||||
intents.value = data || []
|
||||
|
||||
const [{ count: cAll, error: eAll }, { count: cNew, error: eNew }, { count: cPaid, error: ePaid }] = await Promise.all([
|
||||
supabase.from('subscription_intents').select('id', { count: 'exact', head: true }),
|
||||
supabase.from('subscription_intents').select('id', { count: 'exact', head: true }).eq('status', 'new'),
|
||||
supabase.from('subscription_intents').select('id', { count: 'exact', head: true }).eq('status', 'paid')
|
||||
])
|
||||
|
||||
if (eAll) throw eAll
|
||||
if (eNew) throw eNew
|
||||
if (ePaid) throw ePaid
|
||||
|
||||
totalIntents.value = Number(cAll || 0)
|
||||
totalIntentsNew.value = Number(cNew || 0)
|
||||
totalIntentsPaid.value = Number(cPaid || 0)
|
||||
} catch (e) {
|
||||
console.warn('[SAAS] loadIntents failed:', e)
|
||||
intents.value = []
|
||||
totalIntents.value = 0
|
||||
totalIntentsNew.value = 0
|
||||
totalIntentsPaid.value = 0
|
||||
} finally {
|
||||
intentsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadStats () {
|
||||
loading.value = true
|
||||
try {
|
||||
const [{ data: p, error: ep }, { data: s, error: es }] = await Promise.all([
|
||||
supabase.from('plans').select('id,key,price_cents,currency,billing_interval').order('key', { ascending: true }),
|
||||
supabase.from('subscriptions').select('id,tenant_id,plan_id,status,updated_at').order('updated_at', { ascending: false })
|
||||
const [{ data: p, error: ep }, { data: ap, error: eap }, { data: s, error: es }] = await Promise.all([
|
||||
supabase.from('plans').select('id,key,target,is_active').order('key', { ascending: true }),
|
||||
supabase.from('v_plan_active_prices').select('*'),
|
||||
supabase.from('subscriptions').select('id,tenant_id,user_id,plan_id,status,updated_at').order('updated_at', { ascending: false })
|
||||
])
|
||||
|
||||
if (ep) throw ep
|
||||
if (eap) throw eap
|
||||
if (es) throw es
|
||||
|
||||
plans.value = p || []
|
||||
prices.value = ap || []
|
||||
subs.value = s || []
|
||||
|
||||
totalActive.value = subs.value.filter(x => x.status === 'active').length
|
||||
totalCanceled.value = subs.value.filter(x => x.status === 'canceled').length
|
||||
totalActive.value = (subs.value || []).filter(x => x.status === 'active').length
|
||||
totalCanceled.value = (subs.value || []).filter(x => x.status === 'canceled').length
|
||||
|
||||
const { data: mismatches, error: em } = await supabase
|
||||
.from('v_subscription_feature_mismatch')
|
||||
@@ -122,13 +297,35 @@ async function loadStats () {
|
||||
|
||||
if (em) throw em
|
||||
totalMismatches.value = (mismatches || []).length
|
||||
|
||||
await loadIntents()
|
||||
|
||||
lastUpdatedAt.value = new Date().toISOString()
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 5000 })
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 5200 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------
|
||||
// Fix all (com confirmação)
|
||||
// ------------------------------------
|
||||
function askFixAll () {
|
||||
if (loading.value) return
|
||||
if (totalMismatches.value <= 0) return
|
||||
|
||||
confirm.require({
|
||||
header: 'Confirmar correção geral',
|
||||
message: `Reconstruir entitlements para todos os owners com divergência?\nTotal atual: ${totalMismatches.value}`,
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: 'Corrigir agora',
|
||||
rejectLabel: 'Voltar',
|
||||
acceptClass: 'p-button-danger',
|
||||
accept: () => fixAll()
|
||||
})
|
||||
}
|
||||
|
||||
async function fixAll () {
|
||||
loading.value = true
|
||||
try {
|
||||
@@ -139,119 +336,368 @@ async function fixAll () {
|
||||
severity: 'success',
|
||||
summary: 'Sistema corrigido',
|
||||
detail: 'Entitlements reconstruídos com sucesso.',
|
||||
life: 3000
|
||||
life: 3200
|
||||
})
|
||||
|
||||
await loadStats()
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 5000 })
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 5200 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadStats)
|
||||
// ------------------------------------
|
||||
// Hero sticky
|
||||
// ------------------------------------
|
||||
const heroRef = ref(null)
|
||||
const sentinelRef = ref(null)
|
||||
const heroStuck = ref(false)
|
||||
let heroObserver = null
|
||||
const mobileMenuRef = ref(null)
|
||||
|
||||
const heroMenuItems = computed(() => [
|
||||
{
|
||||
label: 'Recarregar',
|
||||
icon: 'pi pi-refresh',
|
||||
command: loadStats,
|
||||
disabled: loading.value
|
||||
},
|
||||
{
|
||||
label: 'Assinaturas',
|
||||
icon: 'pi pi-credit-card',
|
||||
command: () => router.push('/saas/subscriptions'),
|
||||
disabled: loading.value
|
||||
},
|
||||
{
|
||||
label: 'Eventos',
|
||||
icon: 'pi pi-history',
|
||||
command: () => router.push('/saas/subscription-events'),
|
||||
disabled: loading.value
|
||||
},
|
||||
{ separator: true },
|
||||
{
|
||||
label: 'Intervalo',
|
||||
items: intervalOptions.map(o => ({
|
||||
label: o.label,
|
||||
icon: intervalView.value === o.value ? 'pi pi-check' : 'pi pi-circle',
|
||||
command: () => { intervalView.value = o.value }
|
||||
}))
|
||||
}
|
||||
])
|
||||
|
||||
onMounted(() => {
|
||||
loadStats()
|
||||
|
||||
if (sentinelRef.value) {
|
||||
heroObserver = new IntersectionObserver(
|
||||
([entry]) => { heroStuck.value = !entry.isIntersecting },
|
||||
{ rootMargin: `${document.querySelector('.l2-main') ? '0px' : '-56px'} 0px 0px 0px`, threshold: 0 }
|
||||
)
|
||||
heroObserver.observe(sentinelRef.value)
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
heroObserver?.disconnect()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Toast />
|
||||
<ConfirmDialog />
|
||||
|
||||
<div class="p-4">
|
||||
<div class="flex items-center justify-content-between mb-4">
|
||||
<div>
|
||||
<div class="text-2xl font-semibold">SaaS Control Center</div>
|
||||
<small class="text-color-secondary">Visão estratégica + saúde de consistência.</small>
|
||||
</div>
|
||||
<!-- Info decorativa (scrolls away naturalmente) -->
|
||||
<div class="flex items-center gap-3 px-4 pb-3">
|
||||
<div class="dash-hero__icon shrink-0">
|
||||
<i class="pi pi-chart-bar text-2xl" />
|
||||
</div>
|
||||
<small class="text-color-secondary">
|
||||
Visão estratégica (receita e distribuição) + saúde de consistência (entitlements).
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<!-- sentinel -->
|
||||
<div ref="sentinelRef" style="height: 1px; pointer-events: none;" />
|
||||
|
||||
<!-- hero -->
|
||||
<div
|
||||
ref="heroRef"
|
||||
class="dash-hero"
|
||||
:class="{ 'dash-hero--stuck': heroStuck }"
|
||||
>
|
||||
<div class="dash-hero__blob dash-hero__blob--1" />
|
||||
<div class="dash-hero__blob dash-hero__blob--2" />
|
||||
|
||||
<div class="flex items-center gap-3 min-w-0">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<span class="text-xl font-bold leading-none">Central de Controle do SaaS</span>
|
||||
|
||||
<!-- desktop actions -->
|
||||
<div class="hidden xl:flex items-center gap-2">
|
||||
<SelectButton
|
||||
v-model="intervalView"
|
||||
:options="intervalOptions"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
:disabled="loading"
|
||||
/>
|
||||
<Button
|
||||
label="Recarregar"
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:loading="loading"
|
||||
@click="loadStats"
|
||||
/>
|
||||
<Button
|
||||
label="Assinaturas"
|
||||
icon="pi pi-credit-card"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:disabled="loading"
|
||||
@click="router.push('/saas/subscriptions')"
|
||||
/>
|
||||
<Button
|
||||
label="Eventos"
|
||||
icon="pi pi-history"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:disabled="loading"
|
||||
@click="router.push('/saas/subscription-events')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- mobile -->
|
||||
<div class="flex xl:hidden">
|
||||
<Button
|
||||
label="Ações"
|
||||
icon="pi pi-ellipsis-v"
|
||||
severity="warn"
|
||||
outlined
|
||||
@click="(e) => mobileMenuRef.toggle(e)"
|
||||
/>
|
||||
<Menu ref="mobileMenuRef" :model="heroMenuItems" popup />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<Button label="Recarregar" icon="pi pi-refresh" severity="secondary" outlined :loading="loading" @click="loadStats" />
|
||||
<Button label="Subscriptions" icon="pi pi-credit-card" severity="secondary" outlined @click="router.push('/saas/subscriptions')" />
|
||||
<Button label="Histórico" icon="pi pi-history" severity="secondary" outlined @click="router.push('/saas/subscription-events')" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- content -->
|
||||
<div class="px-4 pb-4">
|
||||
<!-- KPIs -->
|
||||
<div class="grid grid-cols-12 gap-4">
|
||||
<div class="col-span-12 md:col-span-3">
|
||||
<Card>
|
||||
<template #title>Ativas</template>
|
||||
<Card class="h-full">
|
||||
<template #title>
|
||||
<div class="flex items-center justify-between">
|
||||
<span>Ativas</span>
|
||||
<Tag value="active" severity="success" rounded />
|
||||
</div>
|
||||
</template>
|
||||
<template #content>
|
||||
<div class="text-4xl font-bold text-green-500">{{ totalActive }}</div>
|
||||
<div class="text-4xl font-semibold">{{ totalActive }}</div>
|
||||
<small class="text-color-secondary">assinaturas em status <b>active</b></small>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 md:col-span-3">
|
||||
<Card>
|
||||
<template #title>Canceladas</template>
|
||||
<Card class="h-full">
|
||||
<template #title>
|
||||
<div class="flex items-center justify-between">
|
||||
<span>Canceladas</span>
|
||||
<Tag value="canceled" severity="danger" rounded />
|
||||
</div>
|
||||
</template>
|
||||
<template #content>
|
||||
<div class="text-4xl font-bold text-red-400">{{ totalCanceled }}</div>
|
||||
<div class="text-4xl font-semibold">{{ totalCanceled }}</div>
|
||||
<small class="text-color-secondary">assinaturas em status <b>canceled</b></small>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 md:col-span-3">
|
||||
<Card>
|
||||
<template #title>MRR</template>
|
||||
<Card class="h-full">
|
||||
<template #title>
|
||||
<div class="flex items-center justify-between">
|
||||
<span>{{ intervalView === 'year' ? 'ARR' : 'MRR' }}</span>
|
||||
<Tag :value="intervalView === 'year' ? 'anual' : 'mensal'" severity="secondary" rounded />
|
||||
</div>
|
||||
</template>
|
||||
<template #content>
|
||||
<div class="text-3xl font-bold">{{ moneyBRLFromCents(mrrCents) }}</div>
|
||||
<small class="text-color-secondary">somente planos mensais</small>
|
||||
<div class="text-3xl font-semibold">{{ moneyBRLFromCents(revenueCents) }}</div>
|
||||
<small class="text-color-secondary">normalizado (mensal ↔ anual)</small>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 md:col-span-3">
|
||||
<Card>
|
||||
<template #title>ARPA</template>
|
||||
<Card class="h-full">
|
||||
<template #title>
|
||||
<div class="flex items-center justify-between">
|
||||
<span>ARPA</span>
|
||||
<Tag value="média" severity="secondary" rounded />
|
||||
</div>
|
||||
</template>
|
||||
<template #content>
|
||||
<div class="text-3xl font-bold">{{ moneyBRLFromCents(arpaCents) }}</div>
|
||||
<small class="text-color-secondary">receita média por ativa</small>
|
||||
<div class="text-3xl font-semibold">{{ moneyBRLFromCents(arpaCents) }}</div>
|
||||
<small class="text-color-secondary">média por assinatura ativa</small>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Health + Actions -->
|
||||
<!-- Intenções + Health + Chart -->
|
||||
<div class="grid grid-cols-12 gap-4 mt-4">
|
||||
<!-- Intenções -->
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<Card>
|
||||
<template #title>System Health</template>
|
||||
<template #content>
|
||||
<div class="flex items-center justify-content-between">
|
||||
<div class="text-4xl font-bold" :class="totalMismatches > 0 ? 'text-red-500' : 'text-green-500'">
|
||||
{{ totalMismatches }}
|
||||
</div>
|
||||
<Card class="h-full">
|
||||
<template #title>
|
||||
<div class="flex items-center justify-between">
|
||||
<span>Intenções de assinatura</span>
|
||||
<Tag :value="intentsLoading ? 'carregando' : 'últimas'" severity="secondary" rounded />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<Tag
|
||||
:severity="totalMismatches > 0 ? 'danger' : 'success'"
|
||||
:value="totalMismatches > 0 ? 'Inconsistências' : 'Saudável'"
|
||||
/>
|
||||
<template #content>
|
||||
<div class="grid grid-cols-12 gap-3">
|
||||
<div class="col-span-4 rounded-xl border border-[var(--surface-border)] p-3">
|
||||
<div class="text-xs text-color-secondary">Total</div>
|
||||
<div class="text-2xl font-semibold">{{ totalIntents }}</div>
|
||||
</div>
|
||||
<div class="col-span-4 rounded-xl border border-[var(--surface-border)] p-3">
|
||||
<div class="text-xs text-color-secondary">New</div>
|
||||
<div class="text-2xl font-semibold">{{ totalIntentsNew }}</div>
|
||||
</div>
|
||||
<div class="col-span-4 rounded-xl border border-[var(--surface-border)] p-3">
|
||||
<div class="text-xs text-color-secondary">Paid</div>
|
||||
<div class="text-2xl font-semibold">{{ totalIntentsPaid }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex gap-2 flex-wrap">
|
||||
<Divider class="my-3" />
|
||||
|
||||
<div v-if="intentsLoading" class="text-color-secondary text-sm">
|
||||
Carregando intenções…
|
||||
</div>
|
||||
|
||||
<div v-else>
|
||||
<div v-if="!intents.length" class="text-color-secondary text-sm">
|
||||
Nenhuma intenção encontrada.
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-2">
|
||||
<div
|
||||
v-for="(it, idx) in intents"
|
||||
:key="idx"
|
||||
class="flex items-start justify-between gap-3 rounded-xl border border-[var(--surface-border)] p-3"
|
||||
>
|
||||
<div class="min-w-0">
|
||||
<div class="font-medium truncate">
|
||||
{{ maskEmail(it.email) }}
|
||||
</div>
|
||||
<div class="text-xs text-color-secondary mt-1">
|
||||
{{ it.plan_key || '—' }} • {{ intervalLabel(it.interval) }} •
|
||||
<span class="font-mono">{{ it.tenant_id ? String(it.tenant_id).slice(0, 8) + '…' : '—' }}</span>
|
||||
</div>
|
||||
<div class="text-xs text-color-secondary mt-1">
|
||||
{{ fmtDate(it.created_at) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0">
|
||||
<Tag :value="it.status || '—'" :severity="statusSeverity(it.status)" rounded />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 flex-wrap mt-3">
|
||||
<Button
|
||||
label="Atualizar"
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
size="small"
|
||||
:loading="intentsLoading || loading"
|
||||
@click="loadIntents"
|
||||
/>
|
||||
<Button
|
||||
label="Ver eventos"
|
||||
icon="pi pi-history"
|
||||
severity="secondary"
|
||||
outlined
|
||||
size="small"
|
||||
:disabled="loading"
|
||||
@click="openIntentEvents"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="text-color-secondary text-xs mt-3">
|
||||
Mostrando {{ intentsLimit }} itens mais recentes de <span class="font-mono">subscription_intents</span>.
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<!-- Health -->
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<Card class="h-full">
|
||||
<template #title>
|
||||
<div class="flex items-center justify-between">
|
||||
<span>Saúde do sistema</span>
|
||||
<Tag :severity="healthSeverity" :value="healthLabel" rounded />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #content>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<div class="text-4xl font-semibold">{{ totalMismatches }}</div>
|
||||
<small class="text-color-secondary text-right">
|
||||
divergências entre plano (esperado) e entitlements (atual)
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="text-color-secondary text-sm mt-2">
|
||||
{{ healthHint }}
|
||||
</div>
|
||||
|
||||
<Divider class="my-3" />
|
||||
|
||||
<div class="flex gap-2 flex-wrap">
|
||||
<Button
|
||||
v-if="totalMismatches > 0"
|
||||
label="Fix All"
|
||||
label="Corrigir tudo"
|
||||
icon="pi pi-refresh"
|
||||
severity="danger"
|
||||
:loading="loading"
|
||||
@click="fixAll"
|
||||
@click="askFixAll"
|
||||
/>
|
||||
<Button
|
||||
label="Ver divergências"
|
||||
icon="pi pi-search"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:disabled="loading"
|
||||
@click="router.push('/saas/subscription-health')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="text-color-secondary text-xs mt-3" v-if="lastUpdatedAt">
|
||||
Atualizado em {{ fmtDate(lastUpdatedAt) }}
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div class="col-span-12 md:col-span-8">
|
||||
<Card>
|
||||
<template #title>MRR por plano</template>
|
||||
<!-- Chart -->
|
||||
<div class="col-span-12 md:col-span-4">
|
||||
<Card class="h-full">
|
||||
<template #title>{{ intervalView === 'year' ? 'ARR por plano' : 'MRR por plano' }}</template>
|
||||
<template #content>
|
||||
<div style="height: 260px;">
|
||||
<Chart type="bar" :data="chartData" :options="chartOptions" />
|
||||
@@ -261,28 +707,124 @@ onMounted(loadStats)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Breakdown table -->
|
||||
<!-- Breakdown table (com ações) -->
|
||||
<div class="mt-4">
|
||||
<Card>
|
||||
<template #title>Distribuição por plano</template>
|
||||
<template #content>
|
||||
<DataTable :value="breakdown" stripedRows responsiveLayout="scroll">
|
||||
<Column field="plan_key" header="Plano" style="min-width: 12rem" />
|
||||
<DataTable :value="breakdown" stripedRows responsiveLayout="scroll" emptyMessage="Sem dados para exibir.">
|
||||
<Column field="plan_key" header="Plano" style="min-width: 14rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex flex-col">
|
||||
<span class="font-medium">{{ data.plan_key }}</span>
|
||||
<small class="text-color-secondary">
|
||||
{{ data.plan_active ? 'ativo no catálogo' : 'inativo no catálogo' }}
|
||||
</small>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Público" style="width: 12rem">
|
||||
<template #body="{ data }">
|
||||
<Tag
|
||||
:value="planTargetLabel(data.plan_target)"
|
||||
:severity="planTargetSeverity(data.plan_target)"
|
||||
rounded
|
||||
/>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Ativas" style="width: 8rem">
|
||||
<template #body="{ data }">{{ data.active_count }}</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Canceladas" style="width: 10rem">
|
||||
<template #body="{ data }">{{ data.canceled_count }}</template>
|
||||
</Column>
|
||||
<Column header="Preço" style="min-width: 12rem">
|
||||
|
||||
<Column header="Preço (ref.)" style="min-width: 12rem">
|
||||
<template #body="{ data }">{{ moneyBRLFromCents(data.price_cents) }}</template>
|
||||
</Column>
|
||||
<Column header="MRR" style="min-width: 12rem">
|
||||
<template #body="{ data }">{{ moneyBRLFromCents(data.mrr_cents) }}</template>
|
||||
|
||||
<Column :header="intervalView === 'year' ? 'ARR' : 'MRR'" style="min-width: 12rem">
|
||||
<template #body="{ data }">{{ moneyBRLFromCents(data.revenue_cents) }}</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Ações" style="width: 16rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex gap-2 justify-end flex-wrap">
|
||||
<Button
|
||||
label="Abrir vitrine"
|
||||
icon="pi pi-external-link"
|
||||
severity="secondary"
|
||||
outlined
|
||||
size="small"
|
||||
:disabled="!data.plan_key || data.plan_key === '(sem plano)'"
|
||||
@click="openPlanPublic(data.plan_key)"
|
||||
/>
|
||||
<Button
|
||||
icon="pi pi-pencil"
|
||||
severity="secondary"
|
||||
outlined
|
||||
size="small"
|
||||
:disabled="!data.plan_key || data.plan_key === '(sem plano)'"
|
||||
v-tooltip.top="'Abrir catálogo interno do plano'"
|
||||
@click="openPlanCatalog(data.plan_key)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
</DataTable>
|
||||
|
||||
<div class="text-color-secondary text-sm mt-3">
|
||||
Nota: "Preço (ref.)" e "MRR/ARR" são normalizados usando o preço ativo.
|
||||
Se só existir anual, MRR = anual/12; se só existir mensal, ARR = mensal*12.
|
||||
</div>
|
||||
</template>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* Hero */
|
||||
.dash-hero {
|
||||
position: sticky;
|
||||
top: var(--layout-sticky-top, 56px);
|
||||
z-index: 20;
|
||||
overflow: hidden;
|
||||
border-radius: 1rem;
|
||||
margin: 1rem;
|
||||
padding: 1.25rem 1.5rem;
|
||||
background: linear-gradient(135deg, var(--surface-card) 0%, var(--surface-section) 100%);
|
||||
border: 1px solid var(--surface-border);
|
||||
box-shadow: 0 2px 12px rgba(0, 0, 0, .08);
|
||||
}
|
||||
.dash-hero--stuck {
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
}
|
||||
.dash-hero__blob {
|
||||
position: absolute;
|
||||
border-radius: 50%;
|
||||
opacity: .15;
|
||||
pointer-events: none;
|
||||
}
|
||||
.dash-hero__blob--1 {
|
||||
width: 220px; height: 220px;
|
||||
top: -60px; right: 80px;
|
||||
background: radial-gradient(circle, #2dd4bf, transparent 70%);
|
||||
}
|
||||
.dash-hero__blob--2 {
|
||||
width: 160px; height: 160px;
|
||||
bottom: -40px; right: 260px;
|
||||
background: radial-gradient(circle, #60a5fa, transparent 70%);
|
||||
}
|
||||
.dash-hero__icon {
|
||||
width: 2.75rem; height: 2.75rem;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
border-radius: .75rem;
|
||||
background: var(--primary-100, rgba(99,102,241,.1));
|
||||
color: var(--primary-color, #6366f1);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,16 +1,9 @@
|
||||
<!-- src/views/pages/billing/SaasFeaturesPage.vue -->
|
||||
<script setup>
|
||||
import { ref, onMounted, computed } from 'vue'
|
||||
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
|
||||
import Toolbar from 'primevue/toolbar'
|
||||
import Button from 'primevue/button'
|
||||
import DataTable from 'primevue/datatable'
|
||||
import Column from 'primevue/column'
|
||||
import Dialog from 'primevue/dialog'
|
||||
import InputText from 'primevue/inputtext'
|
||||
import Textarea from 'primevue/textarea'
|
||||
import Toast from 'primevue/toast'
|
||||
import ConfirmDialog from 'primevue/confirmdialog'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
import { useConfirm } from 'primevue/useconfirm'
|
||||
|
||||
@@ -24,83 +17,15 @@ const showDlg = ref(false)
|
||||
const saving = ref(false)
|
||||
const isEdit = ref(false)
|
||||
|
||||
const q = ref('')
|
||||
|
||||
const form = ref({
|
||||
id: null,
|
||||
key: '',
|
||||
name: '',
|
||||
descricao: ''
|
||||
})
|
||||
|
||||
const hasCreatedAt = computed(() => rows.value?.length && 'created_at' in rows.value[0])
|
||||
|
||||
async function fetchAll () {
|
||||
loading.value = true
|
||||
const { data, error } = await supabase
|
||||
.from('features')
|
||||
.select('*')
|
||||
.order('key', { ascending: true })
|
||||
|
||||
loading.value = false
|
||||
|
||||
if (error) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: error.message, life: 4500 })
|
||||
return
|
||||
}
|
||||
|
||||
rows.value = data || []
|
||||
}
|
||||
|
||||
function openCreate () {
|
||||
isEdit.value = false
|
||||
form.value = { id: null, key: '', descricao: '' }
|
||||
showDlg.value = true
|
||||
}
|
||||
|
||||
function openEdit (row) {
|
||||
isEdit.value = true
|
||||
form.value = {
|
||||
id: row.id,
|
||||
key: row.key ?? '',
|
||||
descricao: row.descricao ?? ''
|
||||
}
|
||||
showDlg.value = true
|
||||
}
|
||||
|
||||
function validate () {
|
||||
const k = String(form.value.key || '').trim()
|
||||
if (!k) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Atenção',
|
||||
detail: 'Informe a key da feature.',
|
||||
life: 3000
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
const d = String(form.value.descricao || '').trim()
|
||||
|
||||
// 🔒 evita duplicidade no frontend (exceto no próprio registro em edição)
|
||||
const exists = rows.value.some(r =>
|
||||
String(r.key).trim() === k && r.id !== form.value.id
|
||||
)
|
||||
|
||||
if (exists) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Key já existente',
|
||||
detail: 'Já existe uma feature com essa key. Use outra.',
|
||||
life: 3000
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
form.value.key = k
|
||||
form.value.descricao = d
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
function isUniqueViolation (err) {
|
||||
if (!err) return false
|
||||
if (err.code === '23505') return true
|
||||
@@ -108,62 +33,145 @@ function isUniqueViolation (err) {
|
||||
return msg.includes('duplicate key value') || msg.includes('unique constraint')
|
||||
}
|
||||
|
||||
function isFkViolation (err) {
|
||||
if (!err) return false
|
||||
if (err.code === '23503') return true
|
||||
const msg = String(err.message || '').toLowerCase()
|
||||
return msg.includes('foreign key') || msg.includes('violates foreign key')
|
||||
}
|
||||
|
||||
function slugifyKey (s) {
|
||||
return String(s || '')
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/\s+/g, '_')
|
||||
.replace(/[^a-z0-9._]/g, '')
|
||||
}
|
||||
|
||||
function featureDomain (key) {
|
||||
const k = String(key || '').trim()
|
||||
if (!k) return 'geral'
|
||||
if (k.includes('.')) return k.split('.')[0]
|
||||
if (k.includes('_')) return k.split('_')[0]
|
||||
return k
|
||||
}
|
||||
|
||||
function domainSeverity (domain) {
|
||||
const d = String(domain || '').toLowerCase()
|
||||
if (d.includes('agenda') || d.includes('scheduling')) return 'info'
|
||||
if (d.includes('billing') || d.includes('assin') || d.includes('plano')) return 'success'
|
||||
if (d.includes('portal') || d.includes('patient')) return 'warn'
|
||||
if (d.includes('admin') || d.includes('saas')) return 'secondary'
|
||||
return 'secondary'
|
||||
}
|
||||
|
||||
const filteredRows = computed(() => {
|
||||
const term = String(q.value || '').trim().toLowerCase()
|
||||
if (!term) return rows.value
|
||||
return (rows.value || []).filter(r => {
|
||||
return [r.key, r.name, r.descricao].some(s => String(s || '').toLowerCase().includes(term))
|
||||
})
|
||||
})
|
||||
|
||||
async function fetchAll () {
|
||||
loading.value = true
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('features')
|
||||
.select('id, key, name, descricao, created_at')
|
||||
.order('key', { ascending: true })
|
||||
|
||||
if (error) throw error
|
||||
rows.value = data || []
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 4500 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate () {
|
||||
isEdit.value = false
|
||||
form.value = { id: null, key: '', name: '', descricao: '' }
|
||||
showDlg.value = true
|
||||
}
|
||||
|
||||
function openEdit (row) {
|
||||
isEdit.value = true
|
||||
form.value = {
|
||||
id: row.id,
|
||||
key: row.key ?? '',
|
||||
name: row.name ?? '',
|
||||
descricao: row.descricao ?? ''
|
||||
}
|
||||
showDlg.value = true
|
||||
}
|
||||
|
||||
function validate () {
|
||||
const k = slugifyKey(form.value.key)
|
||||
if (!k) {
|
||||
toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Informe a key do recurso.', life: 3000 })
|
||||
return false
|
||||
}
|
||||
if (!String(form.value.name || '').trim()) {
|
||||
toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Informe o nome do recurso.', life: 3000 })
|
||||
return false
|
||||
}
|
||||
|
||||
const exists = rows.value.some(r =>
|
||||
String(r.key || '').trim().toLowerCase() === k && r.id !== form.value.id
|
||||
)
|
||||
if (exists) {
|
||||
toast.add({ severity: 'warn', summary: 'Key já existente', detail: 'Já existe um recurso com essa key.', life: 3000 })
|
||||
return false
|
||||
}
|
||||
|
||||
form.value.key = k
|
||||
form.value.name = String(form.value.name || '').trim()
|
||||
form.value.descricao = String(form.value.descricao || '').trim()
|
||||
return true
|
||||
}
|
||||
|
||||
async function save () {
|
||||
if (saving.value) return
|
||||
if (!validate()) return
|
||||
|
||||
saving.value = true
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
key: form.value.key,
|
||||
name: form.value.name,
|
||||
descricao: form.value.descricao
|
||||
}
|
||||
|
||||
if (isEdit.value) {
|
||||
const { error } = await supabase
|
||||
.from('features')
|
||||
.update({
|
||||
key: form.value.key,
|
||||
descricao: form.value.descricao
|
||||
})
|
||||
.eq('id', form.value.id)
|
||||
|
||||
const { error } = await supabase.from('features').update(payload).eq('id', form.value.id)
|
||||
if (error) throw error
|
||||
toast.add({ severity: 'success', summary: 'Ok', detail: 'Feature atualizada.', life: 2500 })
|
||||
toast.add({ severity: 'success', summary: 'Ok', detail: 'Recurso atualizado.', life: 2500 })
|
||||
} else {
|
||||
const { error } = await supabase
|
||||
.from('features')
|
||||
.insert({
|
||||
key: form.value.key,
|
||||
descricao: form.value.descricao
|
||||
})
|
||||
|
||||
const { error } = await supabase.from('features').insert(payload)
|
||||
if (error) throw error
|
||||
toast.add({ severity: 'success', summary: 'Ok', detail: 'Feature criada.', life: 2500 })
|
||||
toast.add({ severity: 'success', summary: 'Ok', detail: 'Recurso criado.', life: 2500 })
|
||||
}
|
||||
|
||||
showDlg.value = false
|
||||
await fetchAll()
|
||||
} catch (e) {
|
||||
if (isUniqueViolation(e)) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Key já existente',
|
||||
detail: 'Já existe uma feature com essa key. Use outra.',
|
||||
life: 3500
|
||||
})
|
||||
} else {
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: 'Erro',
|
||||
detail: e.message || String(e),
|
||||
life: 4500
|
||||
})
|
||||
if (isUniqueViolation(e)) {
|
||||
toast.add({ severity: 'warn', summary: 'Key já existente', detail: 'Já existe um recurso com essa key.', life: 3500 })
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 4500 })
|
||||
}
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function askDelete (row) {
|
||||
confirm.require({
|
||||
message: `Excluir a feature "${row.key}"?`,
|
||||
message: `Excluir o recurso "${row.key}"?`,
|
||||
header: 'Confirmar exclusão',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptClass: 'p-button-danger',
|
||||
@@ -172,100 +180,305 @@ function askDelete (row) {
|
||||
}
|
||||
|
||||
async function doDelete (row) {
|
||||
const { error } = await supabase
|
||||
.from('features')
|
||||
.delete()
|
||||
.eq('id', row.id)
|
||||
|
||||
if (error) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: error.message, life: 4500 })
|
||||
return
|
||||
try {
|
||||
const { error } = await supabase.from('features').delete().eq('id', row.id)
|
||||
if (error) throw error
|
||||
toast.add({ severity: 'success', summary: 'Ok', detail: 'Recurso excluído.', life: 2500 })
|
||||
await fetchAll()
|
||||
} catch (e) {
|
||||
const hint = isFkViolation(e)
|
||||
? 'Este recurso está vinculado a planos ou módulos. Remova o vínculo antes de excluir.'
|
||||
: ''
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: 'Erro',
|
||||
detail: hint ? `${e?.message} — ${hint}` : (e?.message || String(e)),
|
||||
life: 5200
|
||||
})
|
||||
}
|
||||
|
||||
toast.add({ severity: 'success', summary: 'Ok', detail: 'Feature excluída.', life: 2500 })
|
||||
await fetchAll()
|
||||
}
|
||||
|
||||
onMounted(fetchAll)
|
||||
// ── Hero sticky ───────────────────────────────────────────
|
||||
const heroEl = ref(null)
|
||||
const heroSentinelRef = ref(null)
|
||||
const heroMenuRef = ref(null)
|
||||
const heroStuck = ref(false)
|
||||
let disconnectStickyObserver = null
|
||||
|
||||
const heroMenuItems = computed(() => [
|
||||
{ label: 'Atualizar', icon: 'pi pi-refresh', command: fetchAll, disabled: loading.value || saving.value },
|
||||
{ label: 'Adicionar recurso', icon: 'pi pi-plus', command: openCreate, disabled: saving.value }
|
||||
])
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchAll()
|
||||
|
||||
const sentinel = heroSentinelRef.value
|
||||
if (sentinel) {
|
||||
const io = new IntersectionObserver(
|
||||
([entry]) => { heroStuck.value = !entry.isIntersecting },
|
||||
{ rootMargin: `${document.querySelector('.l2-main') ? '0px' : '-56px'} 0px 0px 0px` }
|
||||
)
|
||||
io.observe(sentinel)
|
||||
disconnectStickyObserver = () => io.disconnect()
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
try { disconnectStickyObserver?.() } catch {}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Toast />
|
||||
<ConfirmDialog />
|
||||
|
||||
<div class="p-4">
|
||||
<Toolbar class="mb-4">
|
||||
<template #start>
|
||||
<div class="flex flex-col">
|
||||
<div class="text-xl font-semibold leading-none">Features</div>
|
||||
<small class="text-color-secondary mt-1">
|
||||
Funcionalidades que podem ser ativadas por plano.
|
||||
</small>
|
||||
<div class="features-root">
|
||||
|
||||
<!-- Info decorativa (scrolls away naturalmente) -->
|
||||
<div class="flex items-start gap-4 px-4 pb-3">
|
||||
<div class="features-hero__icon-wrap">
|
||||
<i class="pi pi-bolt features-hero__icon" />
|
||||
</div>
|
||||
<div class="features-hero__sub">
|
||||
Cadastre os recursos (features) que os planos podem habilitar.
|
||||
A <b>key</b> é o identificador técnico; o <b>nome</b> é exibido para o usuário.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── HERO ─────────────────────────────────────────────── -->
|
||||
<div ref="heroSentinelRef" class="features-hero-sentinel" />
|
||||
<div ref="heroEl" class="features-hero mb-4" :class="{ 'features-hero--stuck': heroStuck }">
|
||||
<div class="features-hero__blobs" aria-hidden="true">
|
||||
<div class="features-hero__blob features-hero__blob--1" />
|
||||
<div class="features-hero__blob features-hero__blob--2" />
|
||||
</div>
|
||||
|
||||
<div class="features-hero__inner">
|
||||
<div class="features-hero__info min-w-0">
|
||||
<div class="features-hero__title">Recursos do Sistema</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #end>
|
||||
<div class="flex items-center gap-2">
|
||||
<Button label="Atualizar" icon="pi pi-refresh" severity="secondary" outlined :loading="loading" @click="fetchAll" />
|
||||
<Button label="Adicionar" icon="pi pi-plus" @click="openCreate" />
|
||||
<!-- Ações desktop (≥ 1200px) -->
|
||||
<div class="features-hero__actions features-hero__actions--desktop">
|
||||
<Button label="Atualizar" icon="pi pi-refresh" severity="secondary" outlined size="small" :loading="loading" :disabled="saving" @click="fetchAll" />
|
||||
<Button label="Adicionar recurso" icon="pi pi-plus" size="small" :disabled="saving" @click="openCreate" />
|
||||
</div>
|
||||
</template>
|
||||
</Toolbar>
|
||||
|
||||
<DataTable :value="rows" dataKey="id" :loading="loading" stripedRows responsiveLayout="scroll">
|
||||
<Column field="key" header="Key" sortable />
|
||||
<!-- Ações mobile (< 1200px) -->
|
||||
<div class="features-hero__actions--mobile">
|
||||
<Button
|
||||
label="Ações"
|
||||
icon="pi pi-ellipsis-v"
|
||||
severity="warn"
|
||||
size="small"
|
||||
aria-haspopup="true"
|
||||
aria-controls="features_hero_menu"
|
||||
@click="(e) => heroMenuRef.toggle(e)"
|
||||
/>
|
||||
<Menu ref="heroMenuRef" id="features_hero_menu" :model="heroMenuItems" :popup="true" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Column field="descricao" header="Descrição" sortable style="min-width: 22rem">
|
||||
<!-- Search — sempre visível, fora do hero sticky -->
|
||||
<div class="px-4 mb-4">
|
||||
<FloatLabel variant="on" class="w-full md:w-[380px]">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-search" />
|
||||
<InputText v-model="q" id="features_search" class="w-full pr-10" variant="filled" autocomplete="off" :disabled="loading || saving" />
|
||||
</IconField>
|
||||
<label for="features_search">Buscar por key, nome ou descrição</label>
|
||||
</FloatLabel>
|
||||
</div>
|
||||
|
||||
<div class="px-4 pb-4">
|
||||
<DataTable :value="filteredRows" dataKey="id" :loading="loading" stripedRows responsiveLayout="scroll">
|
||||
<Column header="Domínio" style="width: 9rem">
|
||||
<template #body="{ data }">
|
||||
<!-- Tooltip opcional: se v-tooltip estiver habilitado no app, vai ficar ótimo.
|
||||
Se não estiver, é só remover o v-tooltip que segue normal. -->
|
||||
<div
|
||||
class="max-w-[520px] whitespace-nowrap overflow-hidden text-ellipsis text-color-secondary"
|
||||
v-tooltip.top="data.descricao || ''"
|
||||
>
|
||||
{{ data.descricao || '-' }}
|
||||
<Tag :value="featureDomain(data.key)" :severity="domainSeverity(featureDomain(data.key))" rounded />
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column field="key" header="Key" sortable style="min-width: 18rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex flex-col">
|
||||
<span class="font-medium font-mono text-sm">{{ data.key }}</span>
|
||||
<small class="text-color-secondary">ID: {{ data.id }}</small>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column v-if="hasCreatedAt" field="created_at" header="Criado em" sortable />
|
||||
|
||||
<Column header="Ações" style="width: 12rem">
|
||||
<Column field="name" header="Nome" sortable style="min-width: 16rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex gap-2">
|
||||
<span>{{ data.name || '—' }}</span>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column field="descricao" header="Descrição" sortable style="min-width: 22rem">
|
||||
<template #body="{ data }">
|
||||
<div class="max-w-[600px] whitespace-nowrap overflow-hidden text-ellipsis text-color-secondary" :title="data.descricao || ''">
|
||||
{{ data.descricao || '—' }}
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column field="created_at" header="Criado em" sortable style="width: 13rem" />
|
||||
|
||||
<Column header="Ações" style="width: 10rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex gap-2 justify-end">
|
||||
<Button icon="pi pi-pencil" severity="secondary" outlined @click="openEdit(data)" />
|
||||
<Button icon="pi pi-trash" severity="danger" outlined @click="askDelete(data)" />
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
</DataTable>
|
||||
</div>
|
||||
|
||||
<Dialog v-model:visible="showDlg" modal :header="isEdit ? 'Editar feature' : 'Nova feature'" :style="{ width: '620px' }">
|
||||
<Dialog
|
||||
v-model:visible="showDlg"
|
||||
modal
|
||||
:header="isEdit ? 'Editar recurso' : 'Novo recurso'"
|
||||
:style="{ width: '640px' }"
|
||||
:closable="!saving"
|
||||
:dismissableMask="!saving"
|
||||
:draggable="false"
|
||||
>
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- Key -->
|
||||
<div>
|
||||
<label class="block mb-2">Key</label>
|
||||
<InputText v-model="form.key" class="w-full" placeholder="ex: online_scheduling.manage" />
|
||||
<FloatLabel variant="on">
|
||||
<IconField>
|
||||
<InputIcon class="pi pi-tag" />
|
||||
<InputText
|
||||
id="cr-key"
|
||||
v-model.trim="form.key"
|
||||
class="w-full"
|
||||
variant="filled"
|
||||
:disabled="saving"
|
||||
autocomplete="off"
|
||||
autofocus
|
||||
@blur="form.key = slugifyKey(form.key)"
|
||||
@keydown.enter.prevent="save"
|
||||
/>
|
||||
</IconField>
|
||||
<label for="cr-key">Key *</label>
|
||||
</FloatLabel>
|
||||
<small class="text-color-secondary block mt-1">
|
||||
Ex.: <span class="font-mono">agenda.view</span> ou <span class="font-mono">online_scheduling.manage</span>.
|
||||
Espaços e acentos são normalizados automaticamente.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<!-- Nome -->
|
||||
<div>
|
||||
<label class="block mb-2">Descrição</label>
|
||||
<Textarea
|
||||
v-model="form.descricao"
|
||||
class="w-full"
|
||||
:autoResize="true"
|
||||
rows="3"
|
||||
placeholder="Explique em linguagem humana o que essa feature habilita..."
|
||||
/>
|
||||
<small class="text-color-secondary block mt-2">
|
||||
Dica: isso aparece no admin e ajuda a documentar o que cada feature faz.
|
||||
<FloatLabel variant="on">
|
||||
<IconField>
|
||||
<InputIcon class="pi pi-bookmark" />
|
||||
<InputText
|
||||
id="cr-name"
|
||||
v-model.trim="form.name"
|
||||
class="w-full"
|
||||
variant="filled"
|
||||
:disabled="saving"
|
||||
autocomplete="off"
|
||||
@keydown.enter.prevent="save"
|
||||
/>
|
||||
</IconField>
|
||||
<label for="cr-name">Nome *</label>
|
||||
</FloatLabel>
|
||||
<small class="text-color-secondary block mt-1">
|
||||
Nome exibido para o usuário na página de upgrade e nas listagens.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<!-- Descrição PT-BR -->
|
||||
<div>
|
||||
<FloatLabel variant="on">
|
||||
<Textarea
|
||||
id="cr-desc-pt"
|
||||
v-model.trim="form.descricao"
|
||||
class="w-full"
|
||||
rows="3"
|
||||
autoResize
|
||||
:disabled="saving"
|
||||
/>
|
||||
<label for="cr-desc-pt">Descrição</label>
|
||||
</FloatLabel>
|
||||
<small class="text-color-secondary block mt-1">
|
||||
Explique o que o recurso habilita e para quem se aplica.
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<Button label="Cancelar" severity="secondary" outlined @click="showDlg = false" />
|
||||
<Button label="Cancelar" severity="secondary" outlined @click="showDlg = false" :disabled="saving" />
|
||||
<Button :label="isEdit ? 'Salvar' : 'Criar'" icon="pi pi-check" :loading="saving" @click="save" />
|
||||
</template>
|
||||
</Dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.features-root { padding: 1rem; }
|
||||
@media (min-width: 768px) { .features-root { padding: 1.5rem; } }
|
||||
|
||||
.features-hero-sentinel { height: 1px; }
|
||||
|
||||
.features-hero {
|
||||
position: sticky;
|
||||
top: var(--layout-sticky-top, 56px);
|
||||
z-index: 20;
|
||||
overflow: hidden;
|
||||
border-radius: 1.75rem;
|
||||
border: 1px solid var(--surface-border);
|
||||
background: var(--surface-card);
|
||||
padding: 1.5rem;
|
||||
}
|
||||
.features-hero--stuck {
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
}
|
||||
.features-hero__blobs {
|
||||
position: absolute; inset: 0; pointer-events: none; overflow: hidden;
|
||||
}
|
||||
.features-hero__blob {
|
||||
position: absolute; border-radius: 50%; filter: blur(70px);
|
||||
}
|
||||
.features-hero__blob--1 { width: 20rem; height: 20rem; top: -5rem; right: -4rem; background: rgba(217,70,239,0.10); }
|
||||
.features-hero__blob--2 { width: 18rem; height: 18rem; top: 1rem; left: -5rem; background: rgba(99,102,241,0.10); }
|
||||
|
||||
.features-hero__inner {
|
||||
position: relative; z-index: 1;
|
||||
display: flex; align-items: center; gap: 1.25rem; flex-wrap: wrap;
|
||||
}
|
||||
.features-hero__icon-wrap {
|
||||
flex-shrink: 0;
|
||||
width: 4rem; height: 4rem; border-radius: 1.125rem;
|
||||
border: 2px solid var(--surface-border);
|
||||
background: var(--surface-ground);
|
||||
display: grid; place-items: center;
|
||||
}
|
||||
.features-hero__icon { font-size: 1.5rem; color: var(--text-color); }
|
||||
|
||||
.features-hero__info { flex: 1; min-width: 0; }
|
||||
.features-hero__title {
|
||||
font-size: 1.25rem; font-weight: 700; letter-spacing: -0.025em;
|
||||
color: var(--text-color); line-height: 1.2;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.features-hero__sub {
|
||||
font-size: 0.78rem; color: var(--text-color-secondary); margin-top: 4px; line-height: 1.5;
|
||||
}
|
||||
|
||||
.features-hero__actions--desktop {
|
||||
display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap;
|
||||
}
|
||||
.features-hero__actions--mobile { display: none; }
|
||||
|
||||
@media (max-width: 1199px) {
|
||||
.features-hero__actions--desktop { display: none; }
|
||||
.features-hero__actions--mobile { display: flex; }
|
||||
}
|
||||
</style>
|
||||
@@ -1,45 +1,129 @@
|
||||
<!-- src/views/pages/billing/PlanFeaturesMatrixPage.vue -->
|
||||
<script setup>
|
||||
import { ref, onMounted, computed } from 'vue'
|
||||
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
|
||||
import Toolbar from 'primevue/toolbar'
|
||||
import Button from 'primevue/button'
|
||||
import DataTable from 'primevue/datatable'
|
||||
import Column from 'primevue/column'
|
||||
import Checkbox from 'primevue/checkbox'
|
||||
import Toast from 'primevue/toast'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
import InputText from 'primevue/inputtext'
|
||||
import { useConfirm } from 'primevue/useconfirm'
|
||||
|
||||
const toast = useToast()
|
||||
const confirm = useConfirm()
|
||||
|
||||
const loading = ref(false)
|
||||
const loading = ref(false) // carregamento geral (fetch)
|
||||
const saving = ref(false) // salvando pendências
|
||||
const hasPending = ref(false)
|
||||
|
||||
const plans = ref([])
|
||||
const features = ref([])
|
||||
const links = ref([]) // plan_features rows
|
||||
const links = ref([]) // estado atual (reflete UI)
|
||||
const originalLinks = ref([]) // snapshot do banco (para diff / cancelar)
|
||||
|
||||
const q = ref('')
|
||||
|
||||
const planById = computed(() => {
|
||||
const m = new Map()
|
||||
for (const p of plans.value) m.set(p.id, p)
|
||||
return m
|
||||
})
|
||||
const targetFilter = ref('all') // 'all' | 'clinic' | 'therapist' | 'supervisor'
|
||||
const targetOptions = [
|
||||
{ label: 'Todos', value: 'all' },
|
||||
{ label: 'Clínica', value: 'clinic' },
|
||||
{ label: 'Terapeuta', value: 'therapist' },
|
||||
{ label: 'Supervisor', value: 'supervisor' }
|
||||
]
|
||||
|
||||
// trava por célula (evita corrida)
|
||||
const busySet = ref(new Set())
|
||||
|
||||
function cellKey (planId, featureId) {
|
||||
return `${planId}::${featureId}`
|
||||
}
|
||||
|
||||
function isBusy (planId, featureId) {
|
||||
return busySet.value.has(cellKey(planId, featureId))
|
||||
}
|
||||
|
||||
function setBusy (planId, featureId, v) {
|
||||
const k = cellKey(planId, featureId)
|
||||
const next = new Set(busySet.value)
|
||||
if (v) next.add(k)
|
||||
else next.delete(k)
|
||||
busySet.value = next
|
||||
}
|
||||
|
||||
function isUniqueViolation (err) {
|
||||
if (!err) return false
|
||||
if (err.code === '23505') return true
|
||||
const msg = String(err.message || '')
|
||||
return msg.includes('duplicate key value') || msg.includes('unique constraint')
|
||||
}
|
||||
|
||||
// set de enablement (usa links do estado da UI)
|
||||
const enabledSet = computed(() => {
|
||||
// Set de "planId::featureId" para lookup rápido
|
||||
const s = new Set()
|
||||
for (const r of links.value) s.add(`${r.plan_id}::${r.feature_id}`)
|
||||
return s
|
||||
})
|
||||
|
||||
const originalSet = computed(() => {
|
||||
const s = new Set()
|
||||
for (const r of originalLinks.value) s.add(`${r.plan_id}::${r.feature_id}`)
|
||||
return s
|
||||
})
|
||||
|
||||
const filteredPlans = computed(() => {
|
||||
const t = targetFilter.value
|
||||
if (t === 'all') return plans.value
|
||||
return plans.value.filter(p => p.target === t)
|
||||
})
|
||||
|
||||
const filteredFeatures = computed(() => {
|
||||
const term = String(q.value || '').trim().toLowerCase()
|
||||
if (!term) return features.value
|
||||
return features.value.filter(f => String(f.key || '').toLowerCase().includes(term))
|
||||
return features.value.filter(f => {
|
||||
const key = String(f.key || '').toLowerCase()
|
||||
const desc = String(f.descricao || '').toLowerCase()
|
||||
const descEn = String(f.description || '').toLowerCase()
|
||||
return key.includes(term) || desc.includes(term) || descEn.includes(term)
|
||||
})
|
||||
})
|
||||
|
||||
function targetLabel (t) {
|
||||
if (t === 'clinic') return 'Clínica'
|
||||
if (t === 'therapist') return 'Terapeuta'
|
||||
if (t === 'supervisor') return 'Supervisor'
|
||||
return '—'
|
||||
}
|
||||
|
||||
function targetSeverity (t) {
|
||||
if (t === 'clinic') return 'info'
|
||||
if (t === 'therapist') return 'success'
|
||||
if (t === 'supervisor') return 'warn'
|
||||
return 'secondary'
|
||||
}
|
||||
|
||||
function planTitle (p) {
|
||||
// ✅ Mostrar nome do plano; fallback para key
|
||||
return p?.name || p?.plan_name || p?.public_name || p?.key || 'Plano'
|
||||
}
|
||||
|
||||
function markDirtyIfNeeded () {
|
||||
// compara tamanhos e conteúdo (set diff)
|
||||
const a = enabledSet.value
|
||||
const b = originalSet.value
|
||||
|
||||
if (a.size !== b.size) {
|
||||
hasPending.value = true
|
||||
return
|
||||
}
|
||||
|
||||
for (const k of a) {
|
||||
if (!b.has(k)) {
|
||||
hasPending.value = true
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
hasPending.value = false
|
||||
}
|
||||
|
||||
async function fetchAll () {
|
||||
loading.value = true
|
||||
try {
|
||||
@@ -56,10 +140,13 @@ async function fetchAll () {
|
||||
plans.value = p || []
|
||||
features.value = f || []
|
||||
links.value = pf || []
|
||||
originalLinks.value = pf || []
|
||||
hasPending.value = false
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 5000 })
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 5000 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
busySet.value = new Set()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,71 +154,326 @@ function isEnabled (planId, featureId) {
|
||||
return enabledSet.value.has(`${planId}::${featureId}`)
|
||||
}
|
||||
|
||||
async function toggle (planId, featureId, nextValue) {
|
||||
// otimista (UI responde rápido) — mas com rollback se falhar
|
||||
const key = `${planId}::${featureId}`
|
||||
const prev = links.value.slice()
|
||||
/**
|
||||
* ✅ Toggle agora NÃO salva no banco.
|
||||
* Apenas altera o estado local (links) e marca como “pendente”.
|
||||
*/
|
||||
function toggleLocal (planId, featureId, nextValue) {
|
||||
if (loading.value || saving.value) return
|
||||
if (isBusy(planId, featureId)) return
|
||||
|
||||
setBusy(planId, featureId, true)
|
||||
|
||||
try {
|
||||
if (nextValue) {
|
||||
// adiciona
|
||||
links.value = [...links.value, { plan_id: planId, feature_id: featureId }]
|
||||
const { error } = await supabase.from('plan_features').insert({ plan_id: planId, feature_id: featureId })
|
||||
if (error) throw error
|
||||
if (!enabledSet.value.has(`${planId}::${featureId}`)) {
|
||||
links.value = [...links.value, { plan_id: planId, feature_id: featureId }]
|
||||
}
|
||||
} else {
|
||||
// remove
|
||||
links.value = links.value.filter(x => !(x.plan_id === planId && x.feature_id === featureId))
|
||||
const { error } = await supabase
|
||||
.from('plan_features')
|
||||
.delete()
|
||||
.eq('plan_id', planId)
|
||||
.eq('feature_id', featureId)
|
||||
if (error) throw error
|
||||
}
|
||||
} catch (e) {
|
||||
links.value = prev
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 5000 })
|
||||
return
|
||||
|
||||
markDirtyIfNeeded()
|
||||
} finally {
|
||||
setBusy(planId, featureId, false)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(fetchAll)
|
||||
/**
|
||||
* ✅ Ação em massa local (sem salvar)
|
||||
*/
|
||||
function setAllForPlanLocal (planId, mode) {
|
||||
if (!planId) return
|
||||
if (loading.value || saving.value) return
|
||||
|
||||
const feats = filteredFeatures.value || []
|
||||
if (!feats.length) return
|
||||
|
||||
if (mode === 'enable') {
|
||||
const next = links.value.slice()
|
||||
const exists = new Set(next.map(x => `${x.plan_id}::${x.feature_id}`))
|
||||
|
||||
let changed = 0
|
||||
for (const f of feats) {
|
||||
const k = `${planId}::${f.id}`
|
||||
if (!exists.has(k)) {
|
||||
next.push({ plan_id: planId, feature_id: f.id })
|
||||
exists.add(k)
|
||||
changed++
|
||||
}
|
||||
}
|
||||
|
||||
links.value = next
|
||||
markDirtyIfNeeded()
|
||||
|
||||
if (!changed) {
|
||||
toast.add({ severity: 'info', summary: 'Sem mudanças', detail: 'Todos os recursos filtrados já estavam marcados.', life: 2200 })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (mode === 'disable') {
|
||||
const toRemove = new Set(feats.map(f => `${planId}::${f.id}`))
|
||||
const before = links.value.length
|
||||
links.value = links.value.filter(x => !toRemove.has(`${x.plan_id}::${x.feature_id}`))
|
||||
const changed = before - links.value.length
|
||||
|
||||
markDirtyIfNeeded()
|
||||
|
||||
if (!changed) {
|
||||
toast.add({ severity: 'info', summary: 'Sem mudanças', detail: 'Nenhum recurso filtrado estava marcado para remover.', life: 2200 })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ✅ Confirmação dupla antes de aplicar ação em massa (local)
|
||||
* (1) confirma ação
|
||||
* (2) confirma impacto (quantidade)
|
||||
*/
|
||||
function confirmMassAction (plan, mode) {
|
||||
if (!plan?.id) return
|
||||
|
||||
const feats = filteredFeatures.value || []
|
||||
const qtd = feats.length
|
||||
if (!qtd) {
|
||||
toast.add({ severity: 'info', summary: 'Nada a fazer', detail: 'Não há recursos no filtro atual.', life: 2200 })
|
||||
return
|
||||
}
|
||||
|
||||
const modeLabel = mode === 'enable' ? 'marcar' : 'desmarcar'
|
||||
const modeLabel2 = mode === 'enable' ? 'MARCAR' : 'DESMARCAR'
|
||||
|
||||
confirm.require({
|
||||
header: 'Confirmação',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
message: `Você quer realmente ${modeLabel} TODOS os recursos filtrados para o plano "${planTitle(plan)}"?`,
|
||||
acceptClass: mode === 'disable' ? 'p-button-danger' : 'p-button-success',
|
||||
accept: () => {
|
||||
// ✅ importante: deixa o primeiro confirm fechar antes de abrir o segundo
|
||||
setTimeout(() => {
|
||||
confirm.require({
|
||||
header: 'Confirmação final',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
message: `Isso vai ${modeLabel} ${qtd} recurso(s) (apenas na tela) e ficará como "alterações pendentes". Confirmar ${modeLabel2}?`,
|
||||
acceptClass: mode === 'disable' ? 'p-button-danger' : 'p-button-success',
|
||||
accept: () => {
|
||||
setAllForPlanLocal(plan.id, mode) // ✅ aplica local
|
||||
}
|
||||
})
|
||||
}, 0)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function confirmReset () {
|
||||
if (!hasPending.value || saving.value || loading.value) return
|
||||
|
||||
confirm.require({
|
||||
header: 'Descartar alterações?',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
message: 'Você quer descartar as alterações pendentes e voltar ao estado do banco?',
|
||||
acceptClass: 'p-button-danger',
|
||||
accept: () => {
|
||||
links.value = (originalLinks.value || []).slice()
|
||||
markDirtyIfNeeded()
|
||||
toast.add({ severity: 'info', summary: 'Ok', detail: 'Alterações descartadas.', life: 2200 })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* ✅ Persistência: calcula diff entre originalLinks e links
|
||||
* - inserts: (UI tem e original não tinha)
|
||||
* - deletes: (original tinha e UI removeu)
|
||||
*/
|
||||
async function saveChanges () {
|
||||
if (loading.value || saving.value) return
|
||||
if (!hasPending.value) {
|
||||
toast.add({ severity: 'info', summary: 'Nada a salvar', detail: 'Não há alterações pendentes.', life: 2200 })
|
||||
return
|
||||
}
|
||||
|
||||
saving.value = true
|
||||
try {
|
||||
const nowSet = enabledSet.value
|
||||
const wasSet = originalSet.value
|
||||
|
||||
const inserts = []
|
||||
const deletes = []
|
||||
|
||||
for (const k of nowSet) {
|
||||
if (!wasSet.has(k)) {
|
||||
const [plan_id, feature_id] = k.split('::')
|
||||
inserts.push({ plan_id, feature_id })
|
||||
}
|
||||
}
|
||||
|
||||
for (const k of wasSet) {
|
||||
if (!nowSet.has(k)) {
|
||||
const [plan_id, feature_id] = k.split('::')
|
||||
deletes.push({ plan_id, feature_id })
|
||||
}
|
||||
}
|
||||
|
||||
// aplica inserts
|
||||
if (inserts.length) {
|
||||
const { error } = await supabase.from('plan_features').insert(inserts)
|
||||
if (error && !isUniqueViolation(error)) throw error
|
||||
}
|
||||
|
||||
// aplica deletes (em lote por plano)
|
||||
if (deletes.length) {
|
||||
const byPlan = new Map()
|
||||
for (const d of deletes) {
|
||||
const arr = byPlan.get(d.plan_id) || []
|
||||
arr.push(d.feature_id)
|
||||
byPlan.set(d.plan_id, arr)
|
||||
}
|
||||
|
||||
for (const [planId, featureIds] of byPlan.entries()) {
|
||||
const { error } = await supabase
|
||||
.from('plan_features')
|
||||
.delete()
|
||||
.eq('plan_id', planId)
|
||||
.in('feature_id', featureIds)
|
||||
|
||||
if (error) throw error
|
||||
}
|
||||
}
|
||||
|
||||
// snapshot novo
|
||||
originalLinks.value = links.value.slice()
|
||||
markDirtyIfNeeded()
|
||||
|
||||
toast.add({ severity: 'success', summary: 'Salvo', detail: 'Alterações aplicadas com sucesso.', life: 2600 })
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro ao salvar', detail: e?.message || String(e), life: 5200 })
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ── Hero sticky ───────────────────────────────────────────
|
||||
const heroEl = ref(null)
|
||||
const heroSentinelRef = ref(null)
|
||||
const heroMenuRef = ref(null)
|
||||
const heroStuck = ref(false)
|
||||
let disconnectStickyObserver = null
|
||||
|
||||
const heroMenuItems = computed(() => [
|
||||
{ label: 'Recarregar', icon: 'pi pi-refresh', command: fetchAll, disabled: loading.value || saving.value || hasPending.value },
|
||||
{ label: 'Descartar', icon: 'pi pi-undo', command: confirmReset, disabled: loading.value || saving.value || !hasPending.value },
|
||||
{ label: 'Salvar alterações', icon: 'pi pi-save', command: saveChanges, disabled: loading.value || !hasPending.value },
|
||||
{ separator: true },
|
||||
{
|
||||
label: 'Filtrar por público',
|
||||
items: targetOptions.map(o => ({
|
||||
label: o.label,
|
||||
command: () => { targetFilter.value = o.value }
|
||||
}))
|
||||
}
|
||||
])
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchAll()
|
||||
|
||||
const sentinel = heroSentinelRef.value
|
||||
if (sentinel) {
|
||||
const io = new IntersectionObserver(
|
||||
([entry]) => { heroStuck.value = !entry.isIntersecting },
|
||||
{ rootMargin: `${document.querySelector('.l2-main') ? '0px' : '-56px'} 0px 0px 0px` }
|
||||
)
|
||||
io.observe(sentinel)
|
||||
disconnectStickyObserver = () => io.disconnect()
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
try { disconnectStickyObserver?.() } catch {}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Toast />
|
||||
<ConfirmDialog />
|
||||
|
||||
<div class="p-4">
|
||||
<Toolbar class="mb-4">
|
||||
<template #start>
|
||||
<div class="flex flex-col">
|
||||
<div class="text-xl font-semibold leading-none">Plan Features</div>
|
||||
<small class="text-color-secondary mt-1">
|
||||
Marque quais features pertencem a cada plano. Isso define FREE/PRO sem mexer no código.
|
||||
</small>
|
||||
</div>
|
||||
</template>
|
||||
<div class="matrix-root">
|
||||
|
||||
<template #end>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="p-input-icon-left">
|
||||
<FloatLabel variant="on" class="w-full">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-search" />
|
||||
<InputText
|
||||
v-model="q"
|
||||
id="features_search"
|
||||
class="w-full pr-10"
|
||||
variant="filled"
|
||||
/>
|
||||
</IconField>
|
||||
<label for="features_search">Filtrar features</label>
|
||||
</FloatLabel>
|
||||
</span>
|
||||
<Button label="Recarregar" icon="pi pi-refresh" severity="secondary" outlined :loading="loading" @click="fetchAll" />
|
||||
<!-- Info decorativa (scrolls away naturalmente) -->
|
||||
<div class="flex items-start gap-4 px-4 pb-3">
|
||||
<div class="matrix-hero__icon-wrap">
|
||||
<i class="pi pi-th-large matrix-hero__icon" />
|
||||
</div>
|
||||
<div class="matrix-hero__sub">
|
||||
Defina quais recursos cada plano habilita. As mudanças ficam <b>pendentes</b> até clicar em <b>Salvar alterações</b>.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── HERO ─────────────────────────────────────────────── -->
|
||||
<div ref="heroSentinelRef" class="matrix-hero-sentinel" />
|
||||
<div ref="heroEl" class="matrix-hero mb-4" :class="{ 'matrix-hero--stuck': heroStuck }">
|
||||
<div class="matrix-hero__blobs" aria-hidden="true">
|
||||
<div class="matrix-hero__blob matrix-hero__blob--1" />
|
||||
<div class="matrix-hero__blob matrix-hero__blob--2" />
|
||||
</div>
|
||||
|
||||
<div class="matrix-hero__inner">
|
||||
<div class="matrix-hero__info min-w-0">
|
||||
<div class="matrix-hero__title">Controle de Recursos</div>
|
||||
</div>
|
||||
</template>
|
||||
</Toolbar>
|
||||
|
||||
<!-- Ações desktop (≥ 1200px) -->
|
||||
<div class="matrix-hero__actions matrix-hero__actions--desktop">
|
||||
<SelectButton v-model="targetFilter" :options="targetOptions" optionLabel="label" optionValue="value" size="small" :disabled="loading || saving" />
|
||||
<Button label="Recarregar" icon="pi pi-refresh" severity="secondary" outlined size="small" :loading="loading" :disabled="saving || hasPending" v-tooltip.top="hasPending ? 'Salve ou descarte antes de recarregar.' : ''" @click="fetchAll" />
|
||||
<Button label="Descartar" icon="pi pi-undo" severity="secondary" outlined size="small" :disabled="loading || saving || !hasPending" @click="confirmReset" />
|
||||
<Button label="Salvar alterações" icon="pi pi-save" size="small" :loading="saving" :disabled="loading || !hasPending" @click="saveChanges" />
|
||||
</div>
|
||||
|
||||
<!-- Ações mobile (< 1200px) -->
|
||||
<div class="matrix-hero__actions--mobile">
|
||||
<Button
|
||||
label="Ações"
|
||||
icon="pi pi-ellipsis-v"
|
||||
severity="warn"
|
||||
size="small"
|
||||
aria-haspopup="true"
|
||||
aria-controls="matrix_hero_menu"
|
||||
@click="(e) => heroMenuRef.toggle(e)"
|
||||
/>
|
||||
<Menu ref="heroMenuRef" id="matrix_hero_menu" :model="heroMenuItems" :popup="true" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Search — sempre visível, fora do hero sticky -->
|
||||
<div class="px-4 mb-4">
|
||||
<FloatLabel variant="on" class="w-full md:w-[340px]">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-search" />
|
||||
<InputText v-model="q" id="features_search" class="w-full pr-10" variant="filled" :disabled="loading || saving" autocomplete="off" />
|
||||
</IconField>
|
||||
<label for="features_search">Filtrar recursos (key ou descrição)</label>
|
||||
</FloatLabel>
|
||||
</div>
|
||||
|
||||
<div class="px-4 pb-4">
|
||||
<div class="mb-3 surface-100 border-round p-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<div class="flex gap-2 items-center flex-wrap">
|
||||
<Tag :value="`Planos: ${filteredPlans.length}`" severity="info" icon="pi pi-list" rounded />
|
||||
<Tag :value="`Recursos: ${filteredFeatures.length}`" severity="success" icon="pi pi-bolt" rounded />
|
||||
<Tag v-if="hasPending" value="Alterações pendentes" severity="warn" icon="pi pi-clock" rounded />
|
||||
</div>
|
||||
|
||||
<div class="text-color-secondary text-sm">
|
||||
Dica: use a busca para reduzir a lista e aplique ações em massa com confirmação.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Divider class="my-4" />
|
||||
|
||||
<DataTable
|
||||
:value="filteredFeatures"
|
||||
@@ -142,37 +484,130 @@ onMounted(fetchAll)
|
||||
:scrollable="true"
|
||||
scrollHeight="70vh"
|
||||
>
|
||||
<Column header="Feature" frozen style="min-width: 22rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex flex-col">
|
||||
<span class="font-medium">
|
||||
{{ data.key }}
|
||||
</span>
|
||||
|
||||
<small class="text-color-secondary leading-snug mt-1">
|
||||
{{ data.descricao || '—' }}
|
||||
</small>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="" frozen style="min-width: 28rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex flex-col">
|
||||
<span class="font-medium">{{ data.key }}</span>
|
||||
<small class="text-color-secondary leading-snug mt-1">
|
||||
{{ data.descricao || data.description || '—' }}
|
||||
</small>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column
|
||||
v-for="p in plans"
|
||||
v-for="p in filteredPlans"
|
||||
:key="p.id"
|
||||
:header="p.key"
|
||||
:style="{ minWidth: '10rem' }"
|
||||
:style="{ minWidth: '14rem' }"
|
||||
>
|
||||
<template #header>
|
||||
<div class="flex flex-col items-center gap-2 w-full text-center">
|
||||
<div class="font-semibold truncate w-full" :title="planTitle(p)">
|
||||
{{ planTitle(p) }}
|
||||
</div>
|
||||
<div class="flex items-center justify-center gap-1 flex-wrap">
|
||||
<small class="text-color-secondary truncate" :title="p.key">{{ p.key }}</small>
|
||||
<Tag :value="targetLabel(p.target)" :severity="targetSeverity(p.target)" rounded />
|
||||
</div>
|
||||
<div class="flex gap-2 justify-center">
|
||||
<Button
|
||||
icon="pi pi-check"
|
||||
severity="success"
|
||||
size="small"
|
||||
outlined
|
||||
:disabled="loading || saving"
|
||||
v-tooltip.top="'Marcar todas as features filtradas (fica pendente até salvar)'"
|
||||
@click="confirmMassAction(p, 'enable')"
|
||||
/>
|
||||
<Button
|
||||
icon="pi pi-times"
|
||||
severity="danger"
|
||||
size="small"
|
||||
outlined
|
||||
:disabled="loading || saving"
|
||||
v-tooltip.top="'Desmarcar todas as features filtradas (fica pendente até salvar)'"
|
||||
@click="confirmMassAction(p, 'disable')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #body="{ data }">
|
||||
<div class="flex justify-center">
|
||||
<Checkbox
|
||||
:binary="true"
|
||||
:modelValue="isEnabled(p.id, data.id)"
|
||||
@update:modelValue="(val) => toggle(p.id, data.id, val)"
|
||||
:disabled="loading || saving || isBusy(p.id, data.id)"
|
||||
:aria-label="`Alternar ${p.key} -> ${data.key}`"
|
||||
@update:modelValue="(val) => toggleLocal(p.id, data.id, val)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
</DataTable>
|
||||
</div><!-- /px-4 pb-4 -->
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.matrix-root { padding: 1rem; }
|
||||
@media (min-width: 768px) { .matrix-root { padding: 1.5rem; } }
|
||||
|
||||
.matrix-hero-sentinel { height: 1px; }
|
||||
|
||||
.matrix-hero {
|
||||
position: sticky;
|
||||
top: var(--layout-sticky-top, 56px);
|
||||
z-index: 20;
|
||||
overflow: hidden;
|
||||
border-radius: 1.75rem;
|
||||
border: 1px solid var(--surface-border);
|
||||
background: var(--surface-card);
|
||||
padding: 1.5rem;
|
||||
}
|
||||
.matrix-hero--stuck {
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
}
|
||||
.matrix-hero__blobs {
|
||||
position: absolute; inset: 0; pointer-events: none; overflow: hidden;
|
||||
}
|
||||
.matrix-hero__blob {
|
||||
position: absolute; border-radius: 50%; filter: blur(70px);
|
||||
}
|
||||
.matrix-hero__blob--1 { width: 20rem; height: 20rem; top: -5rem; right: -4rem; background: rgba(52,211,153,0.12); }
|
||||
.matrix-hero__blob--2 { width: 18rem; height: 18rem; top: 1rem; left: -5rem; background: rgba(99,102,241,0.09); }
|
||||
|
||||
.matrix-hero__inner {
|
||||
position: relative; z-index: 1;
|
||||
display: flex; align-items: center; gap: 1.25rem; flex-wrap: wrap;
|
||||
}
|
||||
.matrix-hero__icon-wrap {
|
||||
flex-shrink: 0;
|
||||
width: 4rem; height: 4rem; border-radius: 1.125rem;
|
||||
border: 2px solid var(--surface-border);
|
||||
background: var(--surface-ground);
|
||||
display: grid; place-items: center;
|
||||
}
|
||||
.matrix-hero__icon { font-size: 1.5rem; color: var(--text-color); }
|
||||
|
||||
.matrix-hero__info { flex: 1; min-width: 0; }
|
||||
.matrix-hero__title {
|
||||
font-size: 1.25rem; font-weight: 700; letter-spacing: -0.025em;
|
||||
color: var(--text-color); line-height: 1.2;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.matrix-hero__sub {
|
||||
font-size: 0.78rem; color: var(--text-color-secondary); margin-top: 4px; line-height: 1.5;
|
||||
}
|
||||
|
||||
.matrix-hero__actions--desktop {
|
||||
display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap;
|
||||
}
|
||||
.matrix-hero__actions--mobile { display: none; }
|
||||
|
||||
@media (max-width: 1199px) {
|
||||
.matrix-hero__actions--desktop { display: none; }
|
||||
.matrix-hero__actions--mobile { display: flex; }
|
||||
}
|
||||
</style>
|
||||
775
src/views/pages/saas/SaasPlanLimitsPage.vue
Normal file
775
src/views/pages/saas/SaasPlanLimitsPage.vue
Normal file
@@ -0,0 +1,775 @@
|
||||
<!-- src/views/pages/billing/SaasPlanLimitsPage.vue -->
|
||||
<script setup>
|
||||
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
|
||||
import InputNumber from 'primevue/inputnumber'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
import { useConfirm } from 'primevue/useconfirm'
|
||||
|
||||
const toast = useToast()
|
||||
const confirm = useConfirm()
|
||||
|
||||
// ─── State ────────────────────────────────────────────────────────────────────
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
|
||||
const plans = ref([])
|
||||
const features = ref([])
|
||||
const planFeatures = ref([]) // { plan_id, feature_id, enabled, limits }
|
||||
|
||||
const q = ref('')
|
||||
const targetFilter = ref('all')
|
||||
const targetOptions = [
|
||||
{ label: 'Todos', value: 'all' },
|
||||
{ label: 'Clínica', value: 'clinic' },
|
||||
{ label: 'Terapeuta', value: 'therapist' }
|
||||
]
|
||||
|
||||
// Dialog
|
||||
const showDlg = ref(false)
|
||||
const dlgPlan = ref(null) // plano selecionado
|
||||
const dlgFeature = ref(null) // feature selecionada
|
||||
const dlgPlanFeature = ref(null) // registro atual de plan_features
|
||||
|
||||
// Campos do form de limites (editável pelo admin)
|
||||
// Cada "campo" é um par { key, label, type, value }
|
||||
// O admin define quais keys existem em cada feature
|
||||
const limitFields = ref([])
|
||||
const newLimitKey = ref('')
|
||||
const newLimitValue = ref(null)
|
||||
const newLimitType = ref('number') // 'number' | 'boolean' | 'text'
|
||||
|
||||
const limitTypeOptions = [
|
||||
{ label: 'Número', value: 'number' },
|
||||
{ label: 'Texto', value: 'text' },
|
||||
{ label: 'Booleano', value: 'boolean' }
|
||||
]
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
function targetLabel(t) {
|
||||
if (t === 'clinic') return 'Clínica'
|
||||
if (t === 'therapist') return 'Terapeuta'
|
||||
return '—'
|
||||
}
|
||||
|
||||
function targetSeverity(t) {
|
||||
if (t === 'clinic') return 'info'
|
||||
if (t === 'therapist') return 'success'
|
||||
return 'secondary'
|
||||
}
|
||||
|
||||
function featureDomain(key) {
|
||||
const k = String(key || '')
|
||||
if (k.includes('.')) return k.split('.')[0]
|
||||
if (k.includes('_')) return k.split('_')[0]
|
||||
return k
|
||||
}
|
||||
|
||||
function domainSeverity(domain) {
|
||||
const d = String(domain || '').toLowerCase()
|
||||
if (d.includes('agenda') || d.includes('scheduling')) return 'info'
|
||||
if (d.includes('billing') || d.includes('plano')) return 'success'
|
||||
if (d.includes('portal') || d.includes('patient')) return 'warn'
|
||||
return 'secondary'
|
||||
}
|
||||
|
||||
function limitsDisplay(limits) {
|
||||
if (!limits || typeof limits !== 'object' || !Object.keys(limits).length) return '—'
|
||||
return Object.entries(limits)
|
||||
.map(([k, v]) => {
|
||||
if (v === -1 || v === null) return `${k}: ilimitado`
|
||||
if (typeof v === 'boolean') return `${k}: ${v ? 'sim' : 'não'}`
|
||||
return `${k}: ${v}`
|
||||
})
|
||||
.join(' · ')
|
||||
}
|
||||
|
||||
function limitValueDisplay(v) {
|
||||
if (v === null || v === undefined) return '—'
|
||||
if (v === -1) return 'Ilimitado'
|
||||
if (typeof v === 'boolean') return v ? 'Sim' : 'Não'
|
||||
return String(v)
|
||||
}
|
||||
|
||||
// ─── Computeds ────────────────────────────────────────────────────────────────
|
||||
const filteredPlans = computed(() => {
|
||||
let list = plans.value || []
|
||||
if (targetFilter.value !== 'all') {
|
||||
list = list.filter(p => p.target === targetFilter.value)
|
||||
}
|
||||
return list
|
||||
})
|
||||
|
||||
const filteredFeatures = computed(() => {
|
||||
const term = String(q.value || '').trim().toLowerCase()
|
||||
if (!term) return features.value
|
||||
return (features.value || []).filter(f =>
|
||||
String(f.key || '').toLowerCase().includes(term) ||
|
||||
String(f.descricao || '').toLowerCase().includes(term)
|
||||
)
|
||||
})
|
||||
|
||||
// Linha da tabela = 1 feature × N planos
|
||||
const tableRows = computed(() => {
|
||||
return filteredFeatures.value.map(f => {
|
||||
const planCols = {}
|
||||
for (const p of filteredPlans.value) {
|
||||
const pf = planFeatures.value.find(x => x.plan_id === p.id && x.feature_id === f.id)
|
||||
planCols[p.id] = {
|
||||
enabled: pf?.enabled ?? false,
|
||||
limits: pf?.limits ?? null,
|
||||
hasRecord: !!pf
|
||||
}
|
||||
}
|
||||
return { feature: f, planCols }
|
||||
})
|
||||
})
|
||||
|
||||
// ─── Fetch ────────────────────────────────────────────────────────────────────
|
||||
async function fetchAll() {
|
||||
loading.value = true
|
||||
try {
|
||||
const [
|
||||
{ data: p, error: ep },
|
||||
{ data: f, error: ef },
|
||||
{ data: pf, error: epf }
|
||||
] = await Promise.all([
|
||||
supabase.from('plans').select('id,key,name,target,is_active').order('key'),
|
||||
supabase.from('features').select('id,key,name,descricao').order('key'),
|
||||
supabase.from('plan_features').select('plan_id,feature_id,enabled,limits')
|
||||
])
|
||||
|
||||
if (ep) throw ep
|
||||
if (ef) throw ef
|
||||
if (epf) throw epf
|
||||
|
||||
plans.value = p || []
|
||||
features.value = f || []
|
||||
planFeatures.value = pf || []
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 4500 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Dialog: abrir ────────────────────────────────────────────────────────────
|
||||
function openLimits(plan, feature) {
|
||||
if (saving.value) return
|
||||
|
||||
dlgPlan.value = plan
|
||||
dlgFeature.value = feature
|
||||
|
||||
const pf = planFeatures.value.find(x => x.plan_id === plan.id && x.feature_id === feature.id)
|
||||
dlgPlanFeature.value = pf || null
|
||||
|
||||
// Monta campos a partir dos limits existentes
|
||||
const existingLimits = pf?.limits && typeof pf.limits === 'object' ? pf.limits : {}
|
||||
limitFields.value = Object.entries(existingLimits).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
type: typeof value === 'boolean' ? 'boolean' : (typeof value === 'number' ? 'number' : 'text')
|
||||
}))
|
||||
|
||||
newLimitKey.value = ''
|
||||
newLimitValue.value = null
|
||||
newLimitType.value = 'number'
|
||||
|
||||
showDlg.value = true
|
||||
}
|
||||
|
||||
// ─── Dialog: add campo ────────────────────────────────────────────────────────
|
||||
function addLimitField() {
|
||||
const k = String(newLimitKey.value || '').trim()
|
||||
.toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, '')
|
||||
|
||||
if (!k) {
|
||||
toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Informe o nome do limite (ex: max_patients).', life: 3000 })
|
||||
return
|
||||
}
|
||||
|
||||
if (limitFields.value.some(f => f.key === k)) {
|
||||
toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Já existe um campo com esse nome.', life: 3000 })
|
||||
return
|
||||
}
|
||||
|
||||
let v = newLimitValue.value
|
||||
if (newLimitType.value === 'boolean') v = !!v
|
||||
else if (newLimitType.value === 'number') v = v ?? 0
|
||||
else v = String(v ?? '')
|
||||
|
||||
limitFields.value.push({ key: k, value: v, type: newLimitType.value })
|
||||
newLimitKey.value = ''
|
||||
newLimitValue.value = null
|
||||
}
|
||||
|
||||
function removeLimitField(index) {
|
||||
limitFields.value.splice(index, 1)
|
||||
}
|
||||
|
||||
function setUnlimited(index) {
|
||||
limitFields.value[index].value = -1
|
||||
limitFields.value[index].type = 'number'
|
||||
}
|
||||
|
||||
// ─── Dialog: salvar ───────────────────────────────────────────────────────────
|
||||
async function saveLimits() {
|
||||
if (!dlgPlan.value || !dlgFeature.value) return
|
||||
if (saving.value) return
|
||||
|
||||
saving.value = true
|
||||
try {
|
||||
// Monta o objeto limits a partir dos campos
|
||||
const limits = {}
|
||||
for (const field of limitFields.value) {
|
||||
let v = field.value
|
||||
if (field.type === 'boolean') v = !!v
|
||||
else if (field.type === 'number') v = v === null ? 0 : Number(v)
|
||||
else v = String(v ?? '')
|
||||
limits[field.key] = v
|
||||
}
|
||||
|
||||
const payload = {
|
||||
plan_id: dlgPlan.value.id,
|
||||
feature_id: dlgFeature.value.id,
|
||||
enabled: dlgPlanFeature.value?.enabled ?? true,
|
||||
limits: Object.keys(limits).length ? limits : null
|
||||
}
|
||||
|
||||
const { error } = await supabase
|
||||
.from('plan_features')
|
||||
.upsert(payload, { onConflict: 'plan_id,feature_id' })
|
||||
|
||||
if (error) throw error
|
||||
|
||||
toast.add({ severity: 'success', summary: 'Ok', detail: 'Limites salvos.', life: 2500 })
|
||||
showDlg.value = false
|
||||
await fetchAll()
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 4500 })
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Limpar limites ───────────────────────────────────────────────────────────
|
||||
function askClearLimits(plan, feature) {
|
||||
const pf = planFeatures.value.find(x => x.plan_id === plan.id && x.feature_id === feature.id)
|
||||
if (!pf || !pf.limits) {
|
||||
toast.add({ severity: 'info', summary: 'Nada a limpar', detail: 'Este plano/feature não tem limites definidos.', life: 2500 })
|
||||
return
|
||||
}
|
||||
|
||||
confirm.require({
|
||||
message: `Remover todos os limites de "${feature.key}" no plano "${plan.key}"?\n\nO acesso continuará habilitado, mas sem restrições de quantidade.`,
|
||||
header: 'Confirmar remoção de limites',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptClass: 'p-button-danger',
|
||||
accept: () => doClearLimits(plan, feature)
|
||||
})
|
||||
}
|
||||
|
||||
async function doClearLimits(plan, feature) {
|
||||
try {
|
||||
const { error } = await supabase
|
||||
.from('plan_features')
|
||||
.update({ limits: null })
|
||||
.eq('plan_id', plan.id)
|
||||
.eq('feature_id', feature.id)
|
||||
|
||||
if (error) throw error
|
||||
|
||||
toast.add({ severity: 'success', summary: 'Ok', detail: 'Limites removidos.', life: 2500 })
|
||||
await fetchAll()
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 4500 })
|
||||
}
|
||||
}
|
||||
|
||||
// ── Hero sticky ───────────────────────────────────────────
|
||||
const heroEl = ref(null)
|
||||
const heroSentinelRef = ref(null)
|
||||
const heroMenuRef = ref(null)
|
||||
const heroStuck = ref(false)
|
||||
let disconnectStickyObserver = null
|
||||
|
||||
const heroMenuItems = computed(() => [
|
||||
{ label: 'Recarregar', icon: 'pi pi-refresh', command: fetchAll, disabled: loading.value || saving.value },
|
||||
{ separator: true },
|
||||
{
|
||||
label: 'Filtrar por público',
|
||||
items: targetOptions.map(o => ({
|
||||
label: o.label,
|
||||
command: () => { targetFilter.value = o.value }
|
||||
}))
|
||||
}
|
||||
])
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchAll()
|
||||
|
||||
const sentinel = heroSentinelRef.value
|
||||
if (sentinel) {
|
||||
const io = new IntersectionObserver(
|
||||
([entry]) => { heroStuck.value = !entry.isIntersecting },
|
||||
{ rootMargin: `${document.querySelector('.l2-main') ? '0px' : '-56px'} 0px 0px 0px` }
|
||||
)
|
||||
io.observe(sentinel)
|
||||
disconnectStickyObserver = () => io.disconnect()
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
try { disconnectStickyObserver?.() } catch {}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Toast />
|
||||
<ConfirmDialog />
|
||||
|
||||
<div class="limits-root">
|
||||
|
||||
<!-- Info decorativa (scrolls away naturalmente) -->
|
||||
<div class="flex items-start gap-4 px-4 pb-3">
|
||||
<div class="limits-hero__icon-wrap">
|
||||
<i class="pi pi-sliders-h limits-hero__icon" />
|
||||
</div>
|
||||
<div class="limits-hero__sub">
|
||||
Configure os limites reais de cada feature por plano (ex: max_patients, max_sessions_per_month).
|
||||
Esses valores são lidos pelo sistema para bloquear ações quando o limite é atingido.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── HERO ─────────────────────────────────────────────── -->
|
||||
<div ref="heroSentinelRef" class="limits-hero-sentinel" />
|
||||
<div ref="heroEl" class="limits-hero mb-4" :class="{ 'limits-hero--stuck': heroStuck }">
|
||||
<div class="limits-hero__blobs" aria-hidden="true">
|
||||
<div class="limits-hero__blob limits-hero__blob--1" />
|
||||
<div class="limits-hero__blob limits-hero__blob--2" />
|
||||
</div>
|
||||
|
||||
<div class="limits-hero__inner">
|
||||
<div class="limits-hero__info min-w-0">
|
||||
<div class="limits-hero__title">Limites por Plano</div>
|
||||
</div>
|
||||
|
||||
<!-- Ações desktop (≥ 1200px) -->
|
||||
<div class="limits-hero__actions limits-hero__actions--desktop">
|
||||
<SelectButton v-model="targetFilter" :options="targetOptions" optionLabel="label" optionValue="value" size="small" :disabled="loading || saving" />
|
||||
<Button label="Recarregar" icon="pi pi-refresh" severity="secondary" outlined size="small" :loading="loading" :disabled="saving" @click="fetchAll" />
|
||||
</div>
|
||||
|
||||
<!-- Ações mobile (< 1200px) -->
|
||||
<div class="limits-hero__actions--mobile">
|
||||
<Button
|
||||
label="Ações"
|
||||
icon="pi pi-ellipsis-v"
|
||||
severity="warn"
|
||||
size="small"
|
||||
aria-haspopup="true"
|
||||
aria-controls="limits_hero_menu"
|
||||
@click="(e) => heroMenuRef.toggle(e)"
|
||||
/>
|
||||
<Menu ref="heroMenuRef" id="limits_hero_menu" :model="heroMenuItems" :popup="true" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Search — sempre visível, fora do hero sticky -->
|
||||
<div class="px-4 mb-4">
|
||||
<FloatLabel variant="on" class="w-full md:w-80">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-search" />
|
||||
<InputText v-model="q" id="limits_search" class="w-full pr-10" variant="filled" :disabled="loading || saving" autocomplete="off" />
|
||||
</IconField>
|
||||
<label for="limits_search">Filtrar features (key ou descrição)</label>
|
||||
</FloatLabel>
|
||||
</div>
|
||||
|
||||
<div class="px-4 pb-4">
|
||||
<!-- Legenda rápida -->
|
||||
<div class="surface-100 border-round p-3 mb-4">
|
||||
<div class="flex flex-wrap gap-4 items-center">
|
||||
<div class="flex items-center gap-2 text-sm text-color-secondary">
|
||||
<i class="pi pi-info-circle text-blue-400" />
|
||||
<span><strong>Sem limites</strong> = acesso habilitado sem restrição de quantidade</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 text-sm text-color-secondary">
|
||||
<i class="pi pi-info-circle text-orange-400" />
|
||||
<span><strong>-1</strong> = ilimitado (explícito no JSON, útil para planos PRO)</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 text-sm text-color-secondary">
|
||||
<i class="pi pi-info-circle text-red-400" />
|
||||
<span><strong>0 ou N</strong> = limite máximo que o sistema vai verificar</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 ml-auto">
|
||||
<Tag :value="`${filteredPlans.length} plano(s)`" severity="info" icon="pi pi-star" rounded />
|
||||
<Tag :value="`${filteredFeatures.length} feature(s)`" severity="success" icon="pi pi-bolt" rounded />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tabela: feature × planos -->
|
||||
<DataTable
|
||||
:value="tableRows"
|
||||
dataKey="feature.id"
|
||||
:loading="loading"
|
||||
stripedRows
|
||||
responsiveLayout="scroll"
|
||||
:scrollable="true"
|
||||
scrollHeight="65vh"
|
||||
>
|
||||
<!-- Coluna fixa: Feature -->
|
||||
<Column header="Feature" frozen style="min-width: 26rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex flex-col">
|
||||
<div class="flex items-center gap-2">
|
||||
<Tag
|
||||
:value="featureDomain(data.feature.key)"
|
||||
:severity="domainSeverity(featureDomain(data.feature.key))"
|
||||
rounded
|
||||
/>
|
||||
<span class="font-medium font-mono text-sm">{{ data.feature.key }}</span>
|
||||
</div>
|
||||
<small class="text-color-secondary mt-1 leading-snug">
|
||||
{{ data.feature.descricao || '—' }}
|
||||
</small>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<!-- Coluna dinâmica: 1 por plano filtrado -->
|
||||
<Column
|
||||
v-for="plan in filteredPlans"
|
||||
:key="plan.id"
|
||||
:style="{ minWidth: '20rem' }"
|
||||
>
|
||||
<template #header>
|
||||
<div class="flex flex-col gap-1 w-full">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="font-semibold truncate" :title="plan.name">{{ plan.name || plan.key }}</span>
|
||||
<Tag :value="targetLabel(plan.target)" :severity="targetSeverity(plan.target)" rounded />
|
||||
</div>
|
||||
<small class="text-color-secondary font-mono">{{ plan.key }}</small>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #body="{ data }">
|
||||
<div class="flex flex-col gap-2">
|
||||
<!-- Status: habilitado ou não -->
|
||||
<div class="flex items-center gap-2">
|
||||
<Tag
|
||||
v-if="data.planCols[plan.id].hasRecord"
|
||||
:value="data.planCols[plan.id].enabled ? 'Habilitado' : 'Desabilitado'"
|
||||
:severity="data.planCols[plan.id].enabled ? 'success' : 'secondary'"
|
||||
rounded
|
||||
/>
|
||||
<Tag v-else value="Sem vínculo" severity="secondary" rounded />
|
||||
</div>
|
||||
|
||||
<!-- Limites atuais -->
|
||||
<div
|
||||
v-if="data.planCols[plan.id].limits"
|
||||
class="text-xs text-color-secondary leading-relaxed bg-surface-100 border-round p-2"
|
||||
>
|
||||
<div
|
||||
v-for="(val, key) in data.planCols[plan.id].limits"
|
||||
:key="key"
|
||||
class="flex items-center gap-1"
|
||||
>
|
||||
<span class="font-mono font-medium">{{ key }}:</span>
|
||||
<span>{{ limitValueDisplay(val) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="data.planCols[plan.id].hasRecord" class="text-xs text-color-secondary">
|
||||
Sem limites definidos
|
||||
</div>
|
||||
|
||||
<!-- Ações -->
|
||||
<div v-if="data.planCols[plan.id].hasRecord" class="flex gap-2 flex-wrap">
|
||||
<Button
|
||||
icon="pi pi-pencil"
|
||||
size="small"
|
||||
severity="secondary"
|
||||
outlined
|
||||
v-tooltip.top="'Editar limites'"
|
||||
:disabled="loading || saving"
|
||||
@click="openLimits(plan, data.feature)"
|
||||
/>
|
||||
<Button
|
||||
icon="pi pi-times"
|
||||
size="small"
|
||||
severity="danger"
|
||||
outlined
|
||||
v-tooltip.top="'Limpar limites'"
|
||||
:disabled="loading || saving || !data.planCols[plan.id].limits"
|
||||
@click="askClearLimits(plan, data.feature)"
|
||||
/>
|
||||
</div>
|
||||
<div v-else class="text-xs text-color-secondary italic">
|
||||
Feature não vinculada a este plano.<br/>
|
||||
Configure em <strong>Recursos por Plano</strong>.
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
</DataTable>
|
||||
|
||||
</div><!-- /px-4 pb-4 -->
|
||||
|
||||
<!-- Dialog: editar limites de plan_features -->
|
||||
<Dialog
|
||||
v-model:visible="showDlg"
|
||||
modal
|
||||
:draggable="false"
|
||||
:closable="!saving"
|
||||
:dismissableMask="!saving"
|
||||
:style="{ width: '680px' }"
|
||||
>
|
||||
<template #header>
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="text-lg font-semibold">Limites — {{ dlgFeature?.key }}</div>
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<Tag :value="dlgPlan?.name || dlgPlan?.key" severity="secondary" />
|
||||
<Tag :value="targetLabel(dlgPlan?.target)" :severity="targetSeverity(dlgPlan?.target)" rounded />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
|
||||
<!-- Campos existentes -->
|
||||
<div v-if="limitFields.length">
|
||||
<div class="font-semibold mb-2">Limites configurados</div>
|
||||
<div class="flex flex-col gap-2">
|
||||
<div
|
||||
v-for="(field, idx) in limitFields"
|
||||
:key="idx"
|
||||
class="flex items-center gap-3 surface-100 border-round p-3"
|
||||
>
|
||||
<!-- Key (não editável) -->
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="font-mono font-medium text-sm">{{ field.key }}</div>
|
||||
<small class="text-color-secondary">{{ field.type }}</small>
|
||||
</div>
|
||||
|
||||
<!-- Valor -->
|
||||
<div class="w-40 shrink-0">
|
||||
<template v-if="field.type === 'number'">
|
||||
<InputNumber
|
||||
v-model="field.value"
|
||||
class="w-full"
|
||||
inputClass="w-full"
|
||||
:disabled="saving"
|
||||
:min="-1"
|
||||
placeholder="-1 = ilimitado"
|
||||
/>
|
||||
</template>
|
||||
<template v-else-if="field.type === 'boolean'">
|
||||
<SelectButton
|
||||
v-model="field.value"
|
||||
:options="[{ label: 'Sim', value: true }, { label: 'Não', value: false }]"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
:disabled="saving"
|
||||
/>
|
||||
</template>
|
||||
<template v-else>
|
||||
<InputText v-model="field.value" class="w-full" :disabled="saving" />
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- Ações rápidas -->
|
||||
<div class="flex gap-1 shrink-0">
|
||||
<Button
|
||||
icon="pi pi-infinity"
|
||||
size="small"
|
||||
severity="secondary"
|
||||
outlined
|
||||
v-tooltip.top="'Definir como ilimitado (-1)'"
|
||||
:disabled="saving || field.type !== 'number'"
|
||||
@click="setUnlimited(idx)"
|
||||
/>
|
||||
<Button
|
||||
icon="pi pi-trash"
|
||||
size="small"
|
||||
severity="danger"
|
||||
outlined
|
||||
v-tooltip.top="'Remover este campo'"
|
||||
:disabled="saving"
|
||||
@click="removeLimitField(idx)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="text-sm text-color-secondary surface-100 border-round p-3 text-center">
|
||||
Nenhum limite configurado. Adicione abaixo.
|
||||
</div>
|
||||
|
||||
<Divider />
|
||||
|
||||
<!-- Adicionar novo campo -->
|
||||
<div>
|
||||
<div class="font-semibold mb-3">Adicionar campo de limite</div>
|
||||
|
||||
<div class="flex flex-col gap-3">
|
||||
<!-- Nome -->
|
||||
<div>
|
||||
<label class="text-xs font-semibold text-color-secondary uppercase tracking-wide block mb-1">
|
||||
Nome do campo *
|
||||
</label>
|
||||
<InputText
|
||||
id="new-limit-key"
|
||||
v-model="newLimitKey"
|
||||
class="w-full"
|
||||
variant="filled"
|
||||
:disabled="saving"
|
||||
autocomplete="off"
|
||||
placeholder="ex: max_patients"
|
||||
@keydown.enter.prevent="addLimitField"
|
||||
/>
|
||||
<small class="text-color-secondary mt-1 block">
|
||||
Ex: <span class="font-mono">max_patients</span>, <span class="font-mono">max_sessions_per_month</span>
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<!-- Tipo + Valor + Botão -->
|
||||
<div class="flex items-end gap-2 flex-wrap">
|
||||
<div>
|
||||
<label class="text-xs font-semibold text-color-secondary uppercase tracking-wide block mb-1">Tipo</label>
|
||||
<SelectButton
|
||||
v-model="newLimitType"
|
||||
:options="limitTypeOptions"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
:disabled="saving"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex-1" style="min-width: 8rem;">
|
||||
<label class="text-xs font-semibold text-color-secondary uppercase tracking-wide block mb-1">Valor inicial</label>
|
||||
<InputNumber
|
||||
v-if="newLimitType === 'number'"
|
||||
v-model="newLimitValue"
|
||||
class="w-full"
|
||||
inputClass="w-full"
|
||||
variant="filled"
|
||||
:disabled="saving"
|
||||
:min="-1"
|
||||
placeholder="-1 = ilimitado"
|
||||
/>
|
||||
<SelectButton
|
||||
v-else-if="newLimitType === 'boolean'"
|
||||
v-model="newLimitValue"
|
||||
:options="[{ label: 'Sim', value: true }, { label: 'Não', value: false }]"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
:disabled="saving"
|
||||
/>
|
||||
<InputText
|
||||
v-else
|
||||
v-model="newLimitValue"
|
||||
class="w-full"
|
||||
variant="filled"
|
||||
:disabled="saving"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
icon="pi pi-plus"
|
||||
label="Adicionar"
|
||||
:disabled="saving || !newLimitKey?.trim()"
|
||||
@click="addLimitField"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Dica de boas práticas -->
|
||||
<div class="surface-100 border-round p-3 text-xs text-color-secondary leading-relaxed">
|
||||
<div class="font-semibold mb-1">Convenções recomendadas</div>
|
||||
<div class="grid grid-cols-2 gap-x-4 gap-y-1">
|
||||
<div><span class="font-mono">max_patients</span> — número máximo de pacientes</div>
|
||||
<div><span class="font-mono">max_sessions_per_month</span> — sessões/mês</div>
|
||||
<div><span class="font-mono">max_members</span> — membros da clínica</div>
|
||||
<div><span class="font-mono">max_therapists</span> — terapeutas vinculados</div>
|
||||
<div><span class="font-mono">-1</span> — sem limite (planos PRO)</div>
|
||||
<div><span class="font-mono">0</span> — bloqueado completamente</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<Button label="Cancelar" severity="secondary" outlined :disabled="saving" @click="showDlg = false" />
|
||||
<Button label="Salvar limites" icon="pi pi-check" :loading="saving" @click="saveLimits" />
|
||||
</template>
|
||||
</Dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.limits-root { padding: 1rem; }
|
||||
@media (min-width: 768px) { .limits-root { padding: 1.5rem; } }
|
||||
|
||||
.limits-hero-sentinel { height: 1px; }
|
||||
|
||||
.limits-hero {
|
||||
position: sticky;
|
||||
top: var(--layout-sticky-top, 56px);
|
||||
z-index: 20;
|
||||
overflow: hidden;
|
||||
border-radius: 1.75rem;
|
||||
border: 1px solid var(--surface-border);
|
||||
background: var(--surface-card);
|
||||
padding: 1.5rem;
|
||||
}
|
||||
.limits-hero--stuck {
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
}
|
||||
.limits-hero__blobs {
|
||||
position: absolute; inset: 0; pointer-events: none; overflow: hidden;
|
||||
}
|
||||
.limits-hero__blob {
|
||||
position: absolute; border-radius: 50%; filter: blur(70px);
|
||||
}
|
||||
.limits-hero__blob--1 { width: 20rem; height: 20rem; top: -5rem; right: -4rem; background: rgba(251,146,60,0.12); }
|
||||
.limits-hero__blob--2 { width: 18rem; height: 18rem; top: 1rem; left: -5rem; background: rgba(99,102,241,0.09); }
|
||||
|
||||
.limits-hero__inner {
|
||||
position: relative; z-index: 1;
|
||||
display: flex; align-items: center; gap: 1.25rem; flex-wrap: wrap;
|
||||
}
|
||||
.limits-hero__icon-wrap {
|
||||
flex-shrink: 0;
|
||||
width: 4rem; height: 4rem; border-radius: 1.125rem;
|
||||
border: 2px solid var(--surface-border);
|
||||
background: var(--surface-ground);
|
||||
display: grid; place-items: center;
|
||||
}
|
||||
.limits-hero__icon { font-size: 1.5rem; color: var(--text-color); }
|
||||
|
||||
.limits-hero__info { flex: 1; min-width: 0; }
|
||||
.limits-hero__title {
|
||||
font-size: 1.25rem; font-weight: 700; letter-spacing: -0.025em;
|
||||
color: var(--text-color); line-height: 1.2;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.limits-hero__sub {
|
||||
font-size: 0.78rem; color: var(--text-color-secondary); margin-top: 4px; line-height: 1.5;
|
||||
}
|
||||
|
||||
.limits-hero__actions--desktop {
|
||||
display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap;
|
||||
}
|
||||
.limits-hero__actions--mobile { display: none; }
|
||||
|
||||
@media (max-width: 1199px) {
|
||||
.limits-hero__actions--desktop { display: none; }
|
||||
.limits-hero__actions--mobile { display: flex; }
|
||||
}
|
||||
</style>
|
||||
@@ -1,16 +1,8 @@
|
||||
<script setup>
|
||||
import { ref, onMounted, computed } from 'vue'
|
||||
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
|
||||
import Toolbar from 'primevue/toolbar'
|
||||
import Button from 'primevue/button'
|
||||
import DataTable from 'primevue/datatable'
|
||||
import Column from 'primevue/column'
|
||||
import Dialog from 'primevue/dialog'
|
||||
import InputText from 'primevue/inputtext'
|
||||
import InputNumber from 'primevue/inputnumber'
|
||||
import Toast from 'primevue/toast'
|
||||
import ConfirmDialog from 'primevue/confirmdialog'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
import { useConfirm } from 'primevue/useconfirm'
|
||||
|
||||
@@ -24,20 +16,44 @@ const showDlg = ref(false)
|
||||
const saving = ref(false)
|
||||
const isEdit = ref(false)
|
||||
|
||||
const CORE_PLAN_KEYS = new Set(['clinic_free', 'clinic_pro', 'therapist_free', 'therapist_pro'])
|
||||
|
||||
const targetOptions = [
|
||||
{ label: 'Clínica', value: 'clinic' },
|
||||
{ label: 'Terapeuta', value: 'therapist' },
|
||||
{ label: 'Supervisor', value: 'supervisor' }
|
||||
]
|
||||
|
||||
const targetFilter = ref('all') // 'all' | 'clinic' | 'therapist' | 'supervisor'
|
||||
const targetFilterOptions = [
|
||||
{ label: 'Todos', value: 'all' },
|
||||
{ label: 'Clínica', value: 'clinic' },
|
||||
{ label: 'Terapeuta', value: 'therapist' },
|
||||
{ label: 'Supervisor', value: 'supervisor' }
|
||||
]
|
||||
|
||||
const filteredRows = computed(() => {
|
||||
const t = targetFilter.value
|
||||
if (t === 'all') return rows.value
|
||||
return (rows.value || []).filter(r => r.target === t)
|
||||
})
|
||||
|
||||
const form = ref({
|
||||
id: null,
|
||||
key: '',
|
||||
name: '',
|
||||
price_monthly: null, // em R$ (UI)
|
||||
price_yearly: null // em R$ (UI)
|
||||
target: 'clinic', // 'clinic' | 'therapist' | 'supervisor'
|
||||
price_monthly: null,
|
||||
price_yearly: null,
|
||||
max_supervisees: null // apenas para target=supervisor
|
||||
})
|
||||
|
||||
const hasCreatedAt = computed(() => rows.value?.length && 'created_at' in rows.value[0])
|
||||
|
||||
const isSystemKeyLocked = computed(() => {
|
||||
const k = String(form.value.key || '').trim().toLowerCase()
|
||||
return isEdit.value && (k === 'free' || k === 'pro')
|
||||
})
|
||||
const normalizedKey = computed(() => String(form.value.key || '').trim().toLowerCase())
|
||||
const isCorePlanEditing = computed(() => isEdit.value && CORE_PLAN_KEYS.has(normalizedKey.value))
|
||||
const isTargetLocked = computed(() => isEdit.value) // 🔒 plano existente não troca target
|
||||
const isDeleteLockedRow = (row) => CORE_PLAN_KEYS.has(String(row?.key || '').trim().toLowerCase())
|
||||
|
||||
function isUniqueViolation (err) {
|
||||
if (!err) return false
|
||||
@@ -46,6 +62,13 @@ function isUniqueViolation (err) {
|
||||
return msg.includes('duplicate key value') || msg.includes('unique constraint')
|
||||
}
|
||||
|
||||
function isFkViolation (err) {
|
||||
if (!err) return false
|
||||
if (err.code === '23503') return true
|
||||
const msg = String(err.message || '').toLowerCase()
|
||||
return msg.includes('foreign key') || msg.includes('violates foreign key')
|
||||
}
|
||||
|
||||
// slug técnico para key (sem acento, sem espaço, lowercase, só [a-z0-9_])
|
||||
function slugifyKey (s) {
|
||||
return String(s || '')
|
||||
@@ -75,15 +98,27 @@ function fromCentsToReais (cents) {
|
||||
return Number(cents) / 100
|
||||
}
|
||||
|
||||
function formatTargetLabel (t) {
|
||||
if (t === 'clinic') return 'Clínica'
|
||||
if (t === 'therapist') return 'Terapeuta'
|
||||
if (t === 'supervisor') return 'Supervisor'
|
||||
return t || '—'
|
||||
}
|
||||
|
||||
async function fetchAll () {
|
||||
loading.value = true
|
||||
try {
|
||||
// 1) planos
|
||||
const { data: p, error: ep } = await supabase.from('plans').select('*').order('key', { ascending: true })
|
||||
const { data: p, error: ep } = await supabase
|
||||
.from('plans')
|
||||
.select('*')
|
||||
.order('key', { ascending: true })
|
||||
if (ep) throw ep
|
||||
|
||||
// 2) preços ativos (view)
|
||||
const { data: ap, error: eap } = await supabase.from('v_plan_active_prices').select('*')
|
||||
const { data: ap, error: eap } = await supabase
|
||||
.from('v_plan_active_prices')
|
||||
.select('*')
|
||||
if (eap) throw eap
|
||||
|
||||
const priceMap = new Map()
|
||||
@@ -110,21 +145,28 @@ function openEdit (row) {
|
||||
id: row.id,
|
||||
key: row.key ?? '',
|
||||
name: row.name ?? '',
|
||||
target: row.target || 'clinic',
|
||||
price_monthly: fromCentsToReais(row.monthly_cents),
|
||||
price_yearly: fromCentsToReais(row.yearly_cents)
|
||||
price_yearly: fromCentsToReais(row.yearly_cents),
|
||||
max_supervisees: row.max_supervisees ?? null
|
||||
}
|
||||
showDlg.value = true
|
||||
}
|
||||
|
||||
function openCreate () {
|
||||
isEdit.value = false
|
||||
const suggestedTarget = targetFilter.value !== 'all' ? targetFilter.value : 'clinic'
|
||||
|
||||
form.value = {
|
||||
id: null,
|
||||
key: '',
|
||||
name: '',
|
||||
target: suggestedTarget,
|
||||
price_monthly: null,
|
||||
price_yearly: null
|
||||
price_yearly: null,
|
||||
max_supervisees: null
|
||||
}
|
||||
|
||||
showDlg.value = true
|
||||
}
|
||||
|
||||
@@ -142,22 +184,15 @@ function validate () {
|
||||
return false
|
||||
}
|
||||
|
||||
// preços opcionais — se vierem preenchidos, não podem ser negativos.
|
||||
const m = form.value.price_monthly
|
||||
const y = form.value.price_yearly
|
||||
|
||||
if (m != null && Number(m) < 0) {
|
||||
toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Preço mensal não pode ser negativo.', life: 3000 })
|
||||
return false
|
||||
}
|
||||
if (y != null && Number(y) < 0) {
|
||||
toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Preço anual não pode ser negativo.', life: 3000 })
|
||||
if (!form.value.target || !['clinic', 'therapist', 'supervisor'].includes(form.value.target)) {
|
||||
toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Selecione o público do plano (Clínica, Terapeuta ou Supervisor).', life: 3000 })
|
||||
return false
|
||||
}
|
||||
|
||||
// 🔒 evita key duplicada no frontend (case-insensitive)
|
||||
const exists = rows.value.some(r => String(r.key || '').trim().toLowerCase() === k && r.id !== form.value.id)
|
||||
|
||||
// evita key duplicada no frontend (case-insensitive)
|
||||
const exists = rows.value.some(r =>
|
||||
String(r.key || '').trim().toLowerCase() === k && r.id !== form.value.id
|
||||
)
|
||||
if (exists) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
@@ -174,7 +209,10 @@ function validate () {
|
||||
}
|
||||
|
||||
async function upsertPlanPrice ({ planId, interval, nextCents, prevCents }) {
|
||||
const same = (prevCents == null && nextCents == null) || (Number(prevCents) === Number(nextCents))
|
||||
const same =
|
||||
(prevCents == null && nextCents == null) ||
|
||||
(Number(prevCents) === Number(nextCents))
|
||||
|
||||
if (same) return
|
||||
|
||||
const nowIso = new Date().toISOString()
|
||||
@@ -193,16 +231,14 @@ async function upsertPlanPrice ({ planId, interval, nextCents, prevCents }) {
|
||||
}
|
||||
|
||||
// fecha ativo atual (se existir)
|
||||
if (prevCents != null) {
|
||||
const { error: eClose } = await supabase
|
||||
.from('plan_prices')
|
||||
.update({ is_active: false, active_to: nowIso })
|
||||
.eq('plan_id', planId)
|
||||
.eq('interval', interval)
|
||||
.eq('is_active', true)
|
||||
const { error: eClose } = await supabase
|
||||
.from('plan_prices')
|
||||
.update({ is_active: false, active_to: nowIso })
|
||||
.eq('plan_id', planId)
|
||||
.eq('interval', interval)
|
||||
.eq('is_active', true)
|
||||
|
||||
if (eClose) throw eClose
|
||||
}
|
||||
if (eClose) throw eClose
|
||||
|
||||
// cria novo preço ativo
|
||||
const { error: eIns } = await supabase.from('plan_prices').insert({
|
||||
@@ -219,17 +255,36 @@ async function upsertPlanPrice ({ planId, interval, nextCents, prevCents }) {
|
||||
}
|
||||
|
||||
async function save () {
|
||||
if (saving.value) return
|
||||
if (!validate()) return
|
||||
|
||||
saving.value = true
|
||||
|
||||
try {
|
||||
let planId = form.value.id
|
||||
|
||||
const payload = {
|
||||
key: form.value.key,
|
||||
name: form.value.name,
|
||||
target: form.value.target,
|
||||
max_supervisees: form.value.target === 'supervisor' ? (form.value.max_supervisees ?? null) : null
|
||||
}
|
||||
|
||||
if (isEdit.value) {
|
||||
const { error } = await supabase.from('plans').update({ key: form.value.key, name: form.value.name }).eq('id', form.value.id)
|
||||
// 🔒 target não muda em plano existente (UI já bloqueia; DB trigger garante)
|
||||
const { error } = await supabase
|
||||
.from('plans')
|
||||
.update(payload)
|
||||
.eq('id', form.value.id)
|
||||
|
||||
if (error) throw error
|
||||
} else {
|
||||
const { data, error } = await supabase.from('plans').insert({ key: form.value.key, name: form.value.name }).select('id').single()
|
||||
const { data, error } = await supabase
|
||||
.from('plans')
|
||||
.insert(payload)
|
||||
.select('id')
|
||||
.single()
|
||||
|
||||
if (error) throw error
|
||||
planId = data.id
|
||||
}
|
||||
@@ -263,7 +318,12 @@ async function save () {
|
||||
life: 3500
|
||||
})
|
||||
} else {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 4500 })
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: 'Erro',
|
||||
detail: e.message || String(e),
|
||||
life: 4500
|
||||
})
|
||||
}
|
||||
} finally {
|
||||
saving.value = false
|
||||
@@ -271,6 +331,16 @@ async function save () {
|
||||
}
|
||||
|
||||
function askDelete (row) {
|
||||
if (isDeleteLockedRow(row)) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Ação não permitida',
|
||||
detail: 'Este é um plano padrão do sistema e não pode ser removido.',
|
||||
life: 4200
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
confirm.require({
|
||||
message: `Excluir o plano "${row.key}"?`,
|
||||
header: 'Confirmar exclusão',
|
||||
@@ -280,61 +350,164 @@ function askDelete (row) {
|
||||
})
|
||||
}
|
||||
|
||||
async function doDelete (row) {
|
||||
const { error } = await supabase.from('plans').delete().eq('id', row.id)
|
||||
async function disableActivePrices (planId) {
|
||||
const nowIso = new Date().toISOString()
|
||||
const { error } = await supabase
|
||||
.from('plan_prices')
|
||||
.update({ is_active: false, active_to: nowIso })
|
||||
.eq('plan_id', planId)
|
||||
.eq('is_active', true)
|
||||
|
||||
if (error) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: error.message, life: 4500 })
|
||||
return
|
||||
}
|
||||
|
||||
toast.add({ severity: 'success', summary: 'Ok', detail: 'Plano excluído.', life: 2500 })
|
||||
await fetchAll()
|
||||
if (error) throw error
|
||||
}
|
||||
|
||||
onMounted(fetchAll)
|
||||
async function doDelete (row) {
|
||||
try {
|
||||
await disableActivePrices(row.id)
|
||||
|
||||
const { error } = await supabase
|
||||
.from('plans')
|
||||
.delete()
|
||||
.eq('id', row.id)
|
||||
|
||||
if (error) throw error
|
||||
|
||||
toast.add({ severity: 'success', summary: 'Ok', detail: 'Plano excluído.', life: 2500 })
|
||||
await fetchAll()
|
||||
} catch (e) {
|
||||
const msg = e?.message || String(e)
|
||||
const hint = isFkViolation(e)
|
||||
? 'Esse plano ainda está referenciado (ex.: plan_features, subscriptions ou pricing). Remova vínculos antes de excluir.'
|
||||
: ''
|
||||
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: 'Erro',
|
||||
detail: hint ? `${msg} — ${hint}` : msg,
|
||||
life: 5200
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── Hero sticky ───────────────────────────────────────────
|
||||
const heroEl = ref(null)
|
||||
const heroSentinelRef = ref(null)
|
||||
const heroMenuRef = ref(null)
|
||||
const heroStuck = ref(false)
|
||||
let disconnectStickyObserver = null
|
||||
|
||||
const heroMenuItems = computed(() => [
|
||||
{ label: 'Atualizar', icon: 'pi pi-refresh', command: fetchAll, disabled: loading.value },
|
||||
{ label: 'Adicionar plano', icon: 'pi pi-plus', command: openCreate },
|
||||
{ separator: true },
|
||||
{
|
||||
label: 'Filtrar',
|
||||
items: targetFilterOptions.map(o => ({
|
||||
label: o.label,
|
||||
command: () => { targetFilter.value = o.value }
|
||||
}))
|
||||
}
|
||||
])
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchAll()
|
||||
|
||||
const sentinel = heroSentinelRef.value
|
||||
if (sentinel) {
|
||||
const io = new IntersectionObserver(
|
||||
([entry]) => { heroStuck.value = !entry.isIntersecting },
|
||||
{ rootMargin: `${document.querySelector('.l2-main') ? '0px' : '-56px'} 0px 0px 0px` }
|
||||
)
|
||||
io.observe(sentinel)
|
||||
disconnectStickyObserver = () => io.disconnect()
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
try { disconnectStickyObserver?.() } catch {}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Toast />
|
||||
<ConfirmDialog />
|
||||
|
||||
<div class="p-4">
|
||||
<Toolbar class="mb-4">
|
||||
<template #start>
|
||||
<div class="flex flex-col">
|
||||
<div class="text-xl font-semibold leading-none">Plans</div>
|
||||
<small class="text-color-secondary mt-1">
|
||||
Catálogo de planos do SaaS. A <b>key</b> é a referência estável usada no sistema.
|
||||
</small>
|
||||
</div>
|
||||
</template>
|
||||
<div class="plans-root">
|
||||
|
||||
<template #end>
|
||||
<div class="flex items-center gap-2">
|
||||
<Button label="Atualizar" icon="pi pi-refresh" severity="secondary" outlined :loading="loading" @click="fetchAll" />
|
||||
<Button label="Adicionar" icon="pi pi-plus" @click="openCreate" />
|
||||
</div>
|
||||
</template>
|
||||
</Toolbar>
|
||||
<!-- Info decorativa (scrolls away naturalmente) -->
|
||||
<div class="flex items-start gap-4 px-4 pb-3">
|
||||
<div class="plans-hero__icon-wrap">
|
||||
<i class="pi pi-list plans-hero__icon" />
|
||||
</div>
|
||||
<div class="plans-hero__sub">
|
||||
Catálogo de planos do SaaS. A <b>key</b> é a referência técnica estável.
|
||||
O <b>público</b> indica se o plano é para <b>Clínica</b> ou <b>Terapeuta</b>.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DataTable :value="rows" dataKey="id" :loading="loading" stripedRows responsiveLayout="scroll">
|
||||
<!-- ── HERO ─────────────────────────────────────────────── -->
|
||||
<div ref="heroSentinelRef" class="plans-hero-sentinel" />
|
||||
<div ref="heroEl" class="plans-hero mb-5" :class="{ 'plans-hero--stuck': heroStuck }">
|
||||
<div class="plans-hero__blobs" aria-hidden="true">
|
||||
<div class="plans-hero__blob plans-hero__blob--1" />
|
||||
<div class="plans-hero__blob plans-hero__blob--2" />
|
||||
</div>
|
||||
|
||||
<div class="plans-hero__inner">
|
||||
<!-- Título -->
|
||||
<div class="plans-hero__info min-w-0">
|
||||
<div class="plans-hero__title">Planos e preços</div>
|
||||
</div>
|
||||
|
||||
<!-- Ações desktop (≥ 1200px) -->
|
||||
<div class="plans-hero__actions plans-hero__actions--desktop">
|
||||
<SelectButton
|
||||
v-model="targetFilter"
|
||||
:options="targetFilterOptions"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
size="small"
|
||||
/>
|
||||
<Button label="Atualizar" icon="pi pi-refresh" severity="secondary" outlined size="small" :loading="loading" :disabled="saving" @click="fetchAll" />
|
||||
<Button label="Adicionar plano" icon="pi pi-plus" size="small" :disabled="saving" @click="openCreate" />
|
||||
</div>
|
||||
|
||||
<!-- Ações mobile (< 1200px) -->
|
||||
<div class="plans-hero__actions--mobile">
|
||||
<Button
|
||||
label="Ações"
|
||||
icon="pi pi-ellipsis-v"
|
||||
severity="warn"
|
||||
size="small"
|
||||
aria-haspopup="true"
|
||||
aria-controls="plans_hero_menu"
|
||||
@click="(e) => heroMenuRef.toggle(e)"
|
||||
/>
|
||||
<Menu ref="heroMenuRef" id="plans_hero_menu" :model="heroMenuItems" :popup="true" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="px-4 pb-4">
|
||||
<DataTable :value="filteredRows" dataKey="id" :loading="loading" stripedRows responsiveLayout="scroll">
|
||||
<Column field="name" header="Nome" sortable style="min-width: 14rem" />
|
||||
<Column field="key" header="Key" sortable />
|
||||
|
||||
<Column field="target" header="Público" sortable style="width: 10rem">
|
||||
<template #body="{ data }">
|
||||
<span class="font-medium">{{ formatTargetLabel(data.target) }}</span>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Mensal" sortable style="width: 12rem">
|
||||
<template #body="{ data }">
|
||||
<span class="font-medium">
|
||||
{{ formatBRLFromCents(data.monthly_cents) }}
|
||||
</span>
|
||||
<span class="font-medium">{{ formatBRLFromCents(data.monthly_cents) }}</span>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Anual" sortable style="width: 12rem">
|
||||
<template #body="{ data }">
|
||||
<span class="font-medium">
|
||||
{{ formatBRLFromCents(data.yearly_cents) }}
|
||||
</span>
|
||||
<span class="font-medium">{{ formatBRLFromCents(data.yearly_cents) }}</span>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
@@ -344,69 +517,236 @@ onMounted(fetchAll)
|
||||
<template #body="{ data }">
|
||||
<div class="flex gap-2">
|
||||
<Button icon="pi pi-pencil" severity="secondary" outlined @click="openEdit(data)" />
|
||||
<Button icon="pi pi-trash" severity="danger" outlined @click="askDelete(data)" />
|
||||
<Button
|
||||
icon="pi pi-trash"
|
||||
severity="danger"
|
||||
outlined
|
||||
:disabled="isDeleteLockedRow(data)"
|
||||
:title="isDeleteLockedRow(data) ? 'Plano padrão do sistema não pode ser removido.' : 'Excluir plano'"
|
||||
@click="askDelete(data)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
</DataTable>
|
||||
</div>
|
||||
|
||||
<Dialog v-model:visible="showDlg" modal :header="isEdit ? 'Editar plano' : 'Novo plano'" :style="{ width: '620px' }">
|
||||
<Dialog
|
||||
v-model:visible="showDlg"
|
||||
modal
|
||||
:draggable="false"
|
||||
:header="isEdit ? 'Editar plano' : 'Novo plano'"
|
||||
:style="{ width: '620px' }"
|
||||
class="plans-dialog"
|
||||
>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div>
|
||||
<label class="block mb-2">Key</label>
|
||||
<InputText
|
||||
v-model="form.key"
|
||||
<label class="block mb-2">Público do plano</label>
|
||||
<SelectButton
|
||||
v-model="form.target"
|
||||
:options="targetOptions"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
class="w-full"
|
||||
placeholder="ex.: free, pro, clinic_pro"
|
||||
:disabled="isSystemKeyLocked"
|
||||
:disabled="isTargetLocked || saving"
|
||||
/>
|
||||
<small class="text-color-secondary">
|
||||
A key é técnica e estável (slug). Ex.: "Clínica Pro" vira "clinica_pro".
|
||||
{{ isSystemKeyLocked ? ' Este plano é do sistema (key travada).' : '' }}
|
||||
Planos já existentes não mudam de público. Isso evita inconsistência no catálogo.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block mb-2">Nome do plano</label>
|
||||
<InputText v-model="form.name" class="w-full" placeholder="ex.: Free, Pro, Clínica Pro" />
|
||||
<small class="text-color-secondary">Nome interno para o admin. (O nome público vem depois.)</small>
|
||||
</div>
|
||||
<FloatLabel variant="on" class="w-full">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-tag" />
|
||||
<InputText
|
||||
v-model="form.key"
|
||||
id="plan_key"
|
||||
class="w-full pr-10"
|
||||
variant="filled"
|
||||
placeholder="ex.: clinic_pro"
|
||||
:disabled="(isCorePlanEditing || saving)"
|
||||
@blur="form.key = slugifyKey(form.key)"
|
||||
/>
|
||||
</IconField>
|
||||
<label for="plan_key">Key</label>
|
||||
</FloatLabel>
|
||||
<small class="text-color-secondary -mt-3">
|
||||
Key é técnica e estável (slug). Planos padrão do sistema têm a key protegida.
|
||||
</small>
|
||||
|
||||
<FloatLabel variant="on" class="w-full">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-bookmark" />
|
||||
<InputText
|
||||
v-model="form.name"
|
||||
id="plan_name"
|
||||
class="w-full pr-10"
|
||||
variant="filled"
|
||||
placeholder="ex.: Clínica PRO"
|
||||
:disabled="saving"
|
||||
/>
|
||||
</IconField>
|
||||
<label for="plan_name">Nome</label>
|
||||
</FloatLabel>
|
||||
<small class="text-color-secondary -mt-3">
|
||||
Nome interno para administração. (Nome público vem de <b>plan_public</b>.)
|
||||
</small>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block mb-2">Preço mensal (R$)</label>
|
||||
<InputNumber
|
||||
v-model="form.price_monthly"
|
||||
class="w-full"
|
||||
inputClass="w-full"
|
||||
mode="decimal"
|
||||
:minFractionDigits="2"
|
||||
:maxFractionDigits="2"
|
||||
placeholder="ex.: 39,90"
|
||||
/>
|
||||
<FloatLabel variant="on" class="w-full">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-money-bill" />
|
||||
<InputNumber
|
||||
v-model="form.price_monthly"
|
||||
inputId="price_monthly"
|
||||
class="w-full"
|
||||
inputClass="w-full pr-10"
|
||||
variant="filled"
|
||||
mode="decimal"
|
||||
:minFractionDigits="2"
|
||||
:maxFractionDigits="2"
|
||||
placeholder="ex.: 49,90"
|
||||
:disabled="saving"
|
||||
/>
|
||||
</IconField>
|
||||
<label for="price_monthly">Preço mensal (R$)</label>
|
||||
</FloatLabel>
|
||||
<small class="text-color-secondary">Deixe vazio para “sem preço definido”.</small>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block mb-2">Preço anual (R$)</label>
|
||||
<InputNumber
|
||||
v-model="form.price_yearly"
|
||||
class="w-full"
|
||||
inputClass="w-full"
|
||||
mode="decimal"
|
||||
:minFractionDigits="2"
|
||||
:maxFractionDigits="2"
|
||||
placeholder="ex.: 399,90"
|
||||
/>
|
||||
<FloatLabel variant="on" class="w-full">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-calendar" />
|
||||
<InputNumber
|
||||
v-model="form.price_yearly"
|
||||
inputId="price_yearly"
|
||||
class="w-full"
|
||||
inputClass="w-full pr-10"
|
||||
variant="filled"
|
||||
mode="decimal"
|
||||
:minFractionDigits="2"
|
||||
:maxFractionDigits="2"
|
||||
placeholder="ex.: 490,00"
|
||||
:disabled="saving"
|
||||
/>
|
||||
</IconField>
|
||||
<label for="price_yearly">Preço anual (R$)</label>
|
||||
</FloatLabel>
|
||||
<small class="text-color-secondary">Deixe vazio para “sem preço definido”.</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- max_supervisees: só para planos de supervisor -->
|
||||
<div v-if="form.target === 'supervisor'">
|
||||
<FloatLabel variant="on" class="w-full">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-users" />
|
||||
<InputNumber
|
||||
v-model="form.max_supervisees"
|
||||
inputId="max_supervisees"
|
||||
class="w-full"
|
||||
inputClass="w-full pr-10"
|
||||
variant="filled"
|
||||
:useGrouping="false"
|
||||
:min="1"
|
||||
placeholder="ex.: 3"
|
||||
:disabled="saving"
|
||||
/>
|
||||
</IconField>
|
||||
<label for="max_supervisees">Limite de supervisionados</label>
|
||||
</FloatLabel>
|
||||
<small class="text-color-secondary">Número máximo de terapeutas que podem ser supervisionados neste plano.</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<Button label="Cancelar" severity="secondary" outlined @click="showDlg = false" />
|
||||
<Button label="Cancelar" severity="secondary" outlined @click="showDlg = false" :disabled="saving" />
|
||||
<Button :label="isEdit ? 'Salvar' : 'Criar'" icon="pi pi-check" :loading="saving" @click="save" />
|
||||
</template>
|
||||
</Dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* ─── Root ──────────────────────────────────────────────── */
|
||||
.plans-root { padding: 1rem; }
|
||||
@media (min-width: 768px) { .plans-root { padding: 1.5rem; } }
|
||||
|
||||
/* ─── Hero ──────────────────────────────────────────────── */
|
||||
.plans-hero-sentinel { height: 1px; }
|
||||
|
||||
.plans-hero {
|
||||
position: sticky;
|
||||
top: var(--layout-sticky-top, 56px);
|
||||
z-index: 20;
|
||||
overflow: hidden;
|
||||
border-radius: 1.75rem;
|
||||
border: 1px solid var(--surface-border);
|
||||
background: var(--surface-card);
|
||||
padding: 1.5rem;
|
||||
}
|
||||
.plans-hero--stuck {
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
}
|
||||
.plans-hero__blobs {
|
||||
position: absolute; inset: 0; pointer-events: none; overflow: hidden;
|
||||
}
|
||||
.plans-hero__blob {
|
||||
position: absolute; border-radius: 50%; filter: blur(70px);
|
||||
}
|
||||
.plans-hero__blob--1 { width: 20rem; height: 20rem; top: -5rem; right: -4rem; background: rgba(99,102,241,0.12); }
|
||||
.plans-hero__blob--2 { width: 18rem; height: 18rem; top: 1rem; left: -5rem; background: rgba(52,211,153,0.09); }
|
||||
|
||||
.plans-hero__inner {
|
||||
position: relative; z-index: 1;
|
||||
display: flex; align-items: center; gap: 1.25rem; flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* Ícone */
|
||||
.plans-hero__icon-wrap {
|
||||
flex-shrink: 0;
|
||||
width: 4rem; height: 4rem; border-radius: 1.125rem;
|
||||
border: 2px solid var(--surface-border);
|
||||
background: var(--surface-ground);
|
||||
display: grid; place-items: center;
|
||||
}
|
||||
.plans-hero__icon { font-size: 1.5rem; color: var(--text-color); }
|
||||
|
||||
/* Info */
|
||||
.plans-hero__info { flex: 1; min-width: 0; }
|
||||
.plans-hero__title {
|
||||
font-size: 1.25rem; font-weight: 700; letter-spacing: -0.025em;
|
||||
color: var(--text-color); line-height: 1.2;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.plans-hero__sub {
|
||||
font-size: 0.78rem; color: var(--text-color-secondary); margin-top: 4px; line-height: 1.5;
|
||||
}
|
||||
|
||||
/* Ações */
|
||||
.plans-hero__actions--desktop {
|
||||
display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap;
|
||||
}
|
||||
.plans-hero__actions--mobile { display: none; }
|
||||
|
||||
@media (max-width: 1199px) {
|
||||
.plans-hero__actions--desktop { display: none; }
|
||||
.plans-hero__actions--mobile { display: flex; }
|
||||
}
|
||||
|
||||
/* ─── Dialog: linhas divisórias no header e footer */
|
||||
:deep(.plans-dialog .p-dialog-header) {
|
||||
border-bottom: 1px solid var(--surface-border);
|
||||
}
|
||||
:deep(.plans-dialog .p-dialog-footer) {
|
||||
border-top: 1px solid var(--surface-border);
|
||||
}
|
||||
|
||||
/* Pequena melhoria de leitura */
|
||||
small.text-color-secondary {
|
||||
line-height: 1.35rem;
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,27 +1,36 @@
|
||||
<script setup>
|
||||
import { ref, onMounted, computed } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
|
||||
import Toolbar from 'primevue/toolbar'
|
||||
import Button from 'primevue/button'
|
||||
import DataTable from 'primevue/datatable'
|
||||
import Column from 'primevue/column'
|
||||
import Toast from 'primevue/toast'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
import InputText from 'primevue/inputtext'
|
||||
import Tag from 'primevue/tag'
|
||||
|
||||
const route = useRoute()
|
||||
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
|
||||
const loading = ref(false)
|
||||
const isFetching = ref(false)
|
||||
|
||||
const events = ref([])
|
||||
const plans = ref([])
|
||||
const profiles = ref([])
|
||||
|
||||
const q = ref('')
|
||||
|
||||
// filtro por tipo de owner (clinic/therapist/all)
|
||||
const ownerType = ref('all') // 'all' | 'clinic' | 'therapist'
|
||||
const ownerTypeOptions = [
|
||||
{ label: 'Todos', value: 'all' },
|
||||
{ label: 'Clínica', value: 'clinic' },
|
||||
{ label: 'Terapeuta', value: 'therapist' }
|
||||
]
|
||||
|
||||
const isFocused = computed(() => {
|
||||
return typeof route.query?.q === 'string' && route.query.q.trim().length > 0
|
||||
})
|
||||
|
||||
// ---------- helpers: plano ----------
|
||||
const planKeyById = computed(() => {
|
||||
const m = new Map()
|
||||
for (const p of plans.value) m.set(p.id, p.key)
|
||||
@@ -30,30 +39,55 @@ const planKeyById = computed(() => {
|
||||
|
||||
function planKey (planId) {
|
||||
if (!planId) return '—'
|
||||
return planKeyById.value.get(planId) || planId // fallback pro uuid se não achou
|
||||
return planKeyById.value.get(planId) || planId
|
||||
}
|
||||
|
||||
function typeLabel (t) {
|
||||
if (t === 'plan_changed') return 'Plano alterado'
|
||||
return t || '—'
|
||||
// ---------- helpers: datas ----------
|
||||
function formatWhen (iso) {
|
||||
if (!iso) return '—'
|
||||
const d = new Date(iso)
|
||||
if (Number.isNaN(d.getTime())) return String(iso)
|
||||
return d.toLocaleString('pt-BR')
|
||||
}
|
||||
|
||||
function typeSeverity (t) {
|
||||
if (t === 'plan_changed') return 'info'
|
||||
// ---------- helpers: owner ----------
|
||||
function normalizeOwnerType (t) {
|
||||
const k = String(t || '').toLowerCase()
|
||||
if (k === 'clinic' || k === 'therapist') return k
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
function ownerKeyFromEvent (ev) {
|
||||
const t = normalizeOwnerType(ev.owner_type)
|
||||
const r = String(ev.owner_ref || '').trim()
|
||||
if ((t === 'clinic' || t === 'therapist') && r) return `${t}:${r}`
|
||||
const legacy = String(ev.owner_id || '').trim()
|
||||
return legacy || 'unknown'
|
||||
}
|
||||
|
||||
function parseOwnerKey (raw) {
|
||||
const s = String(raw || '').trim()
|
||||
if (!s) return { kind: 'unknown', id: null, raw: '' }
|
||||
|
||||
const m = s.match(/^(clinic|therapist)\s*:\s*([0-9a-fA-F-]{8,})$/)
|
||||
if (m) return { kind: m[1].toLowerCase(), id: m[2], raw: s }
|
||||
|
||||
return { kind: 'unknown', id: s, raw: s }
|
||||
}
|
||||
|
||||
function ownerTagLabel (t) {
|
||||
if (t === 'clinic') return 'Clínica'
|
||||
if (t === 'therapist') return 'Terapeuta'
|
||||
return '—'
|
||||
}
|
||||
|
||||
function ownerTagSeverity (t) {
|
||||
if (t === 'clinic') return 'info'
|
||||
if (t === 'therapist') return 'success'
|
||||
return 'secondary'
|
||||
}
|
||||
|
||||
function formatWhen (iso) {
|
||||
if (!iso) return '—'
|
||||
try {
|
||||
return new Date(iso).toLocaleString('pt-BR')
|
||||
} catch {
|
||||
return iso
|
||||
}
|
||||
}
|
||||
|
||||
const profiles = ref([])
|
||||
|
||||
// ---------- helpers: profiles ----------
|
||||
const profileById = computed(() => {
|
||||
const m = new Map()
|
||||
for (const p of profiles.value) m.set(p.id, p)
|
||||
@@ -65,11 +99,8 @@ function displayUser (userId) {
|
||||
const p = profileById.value.get(userId)
|
||||
if (!p) return userId
|
||||
|
||||
// tenta achar campos comuns sem assumir
|
||||
const name =
|
||||
p.nome || p.name || p.full_name || p.display_name || p.username || null
|
||||
const email =
|
||||
p.email || p.email_principal || p.user_email || null
|
||||
const name = p.nome || p.name || p.full_name || p.display_name || p.username || null
|
||||
const email = p.email || p.email_principal || p.user_email || null
|
||||
|
||||
if (name && email) return `${name} <${email}>`
|
||||
if (name) return name
|
||||
@@ -77,12 +108,46 @@ function displayUser (userId) {
|
||||
return userId
|
||||
}
|
||||
|
||||
function displayOwner (ev) {
|
||||
const t = normalizeOwnerType(ev.owner_type)
|
||||
const ref = String(ev.owner_ref || '').trim()
|
||||
if (t === 'therapist' && ref) return displayUser(ref)
|
||||
return ownerKeyFromEvent(ev)
|
||||
}
|
||||
|
||||
// ---------- evento ----------
|
||||
function eventLabel (t) {
|
||||
const k = String(t || '').toLowerCase()
|
||||
if (k === 'plan_changed') return 'Plano alterado'
|
||||
if (k === 'canceled') return 'Cancelada'
|
||||
if (k === 'reactivated') return 'Reativada'
|
||||
return t || '—'
|
||||
}
|
||||
|
||||
function eventSeverity (t) {
|
||||
const k = String(t || '').toLowerCase()
|
||||
if (k === 'plan_changed') return 'info'
|
||||
if (k === 'canceled') return 'danger'
|
||||
if (k === 'reactivated') return 'success'
|
||||
return 'secondary'
|
||||
}
|
||||
|
||||
// ---------- navegação ----------
|
||||
function goToSubscriptions (ev) {
|
||||
const key = ownerKeyFromEvent(ev)
|
||||
if (!key || key === 'unknown') return
|
||||
router.push({ path: '/saas/subscriptions', query: { q: key } })
|
||||
}
|
||||
|
||||
// ---------- fetch ----------
|
||||
async function fetchAll () {
|
||||
if (isFetching.value) return
|
||||
isFetching.value = true
|
||||
loading.value = true
|
||||
|
||||
try {
|
||||
const [{ data: p, error: ep }, { data: e, error: ee }] = await Promise.all([
|
||||
supabase.from('plans').select('id,key'),
|
||||
supabase.from('plans').select('id,key').order('key', { ascending: true }),
|
||||
supabase
|
||||
.from('subscription_events')
|
||||
.select('*')
|
||||
@@ -96,21 +161,24 @@ async function fetchAll () {
|
||||
plans.value = p || []
|
||||
events.value = e || []
|
||||
|
||||
// pega ids únicos para buscar profiles
|
||||
// profiles: created_by e owners therapist
|
||||
const ids = new Set()
|
||||
for (const ev of events.value) {
|
||||
if (ev.owner_id) ids.add(ev.owner_id)
|
||||
if (ev.created_by) ids.add(ev.created_by)
|
||||
for (const ev of (events.value || [])) {
|
||||
const createdBy = String(ev.created_by || '').trim()
|
||||
if (createdBy) ids.add(createdBy)
|
||||
|
||||
const t = normalizeOwnerType(ev.owner_type)
|
||||
const ref = String(ev.owner_ref || '').trim()
|
||||
if (t === 'therapist' && ref) ids.add(ref)
|
||||
}
|
||||
|
||||
if (ids.size) {
|
||||
const { data: pr, error: epr } = await supabase
|
||||
.from('profiles')
|
||||
.select('*')
|
||||
.select('id,nome,name,full_name,display_name,username,email,email_principal,user_email')
|
||||
.in('id', Array.from(ids))
|
||||
|
||||
// se profiles tiver RLS restrito, pode falhar; aí só cai no fallback UUID
|
||||
if (!epr) profiles.value = pr || []
|
||||
profiles.value = epr ? [] : (pr || [])
|
||||
} else {
|
||||
profiles.value = []
|
||||
}
|
||||
@@ -118,82 +186,312 @@ async function fetchAll () {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: err.message || String(err), life: 5000 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
isFetching.value = false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ---------- filtro ----------
|
||||
const filtered = computed(() => {
|
||||
const term = String(q.value || '').trim().toLowerCase()
|
||||
if (!term) return events.value
|
||||
let list = events.value || []
|
||||
|
||||
return events.value.filter(ev => {
|
||||
if (ownerType.value !== 'all') {
|
||||
list = list.filter(ev => normalizeOwnerType(ev.owner_type) === ownerType.value)
|
||||
}
|
||||
|
||||
// foco por query (?q=clinic:... / therapist:...)
|
||||
const focus = String(route.query?.q || '').trim()
|
||||
if (focus) {
|
||||
const parsed = parseOwnerKey(focus)
|
||||
if (parsed.kind === 'clinic' || parsed.kind === 'therapist') {
|
||||
list = list.filter(ev =>
|
||||
normalizeOwnerType(ev.owner_type) === parsed.kind &&
|
||||
String(ev.owner_ref || '') === String(parsed.id || '')
|
||||
)
|
||||
} else {
|
||||
const f = focus.toLowerCase()
|
||||
list = list.filter(ev =>
|
||||
ownerKeyFromEvent(ev).toLowerCase().includes(f) ||
|
||||
String(ev.owner_id || '').toLowerCase().includes(f)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (!term) return list
|
||||
|
||||
return list.filter(ev => {
|
||||
const oldKey = planKey(ev.old_plan_id)
|
||||
const newKey = planKey(ev.new_plan_id)
|
||||
|
||||
const ok = ownerKeyFromEvent(ev)
|
||||
const ownerDisp = String(displayOwner(ev) || '')
|
||||
const subId = String(ev.subscription_id || '')
|
||||
const eventType = String(ev.event_type || '')
|
||||
const reason = String(ev.reason || '')
|
||||
|
||||
const meta = ev.metadata ? JSON.stringify(ev.metadata) : ''
|
||||
|
||||
const by = String(ev.created_by || '')
|
||||
const byDisp = String(displayUser(by) || '')
|
||||
|
||||
return (
|
||||
String(ev.owner_id || '').toLowerCase().includes(term) ||
|
||||
String(ev.subscription_id || '').toLowerCase().includes(term) ||
|
||||
String(ev.event_type || '').toLowerCase().includes(term) ||
|
||||
ok.toLowerCase().includes(term) ||
|
||||
ownerDisp.toLowerCase().includes(term) ||
|
||||
subId.toLowerCase().includes(term) ||
|
||||
eventType.toLowerCase().includes(term) ||
|
||||
reason.toLowerCase().includes(term) ||
|
||||
meta.toLowerCase().includes(term) ||
|
||||
String(oldKey || '').toLowerCase().includes(term) ||
|
||||
String(newKey || '').toLowerCase().includes(term)
|
||||
String(newKey || '').toLowerCase().includes(term) ||
|
||||
by.toLowerCase().includes(term) ||
|
||||
byDisp.toLowerCase().includes(term)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
const totalCount = computed(() => (filtered.value || []).length)
|
||||
const changedCount = computed(() => (filtered.value || []).filter(x => String(x?.event_type || '').toLowerCase() === 'plan_changed').length)
|
||||
|
||||
function clearFocus () {
|
||||
router.push({ path: route.path, query: {} })
|
||||
}
|
||||
|
||||
// -------------------------
|
||||
// Hero sticky
|
||||
// -------------------------
|
||||
const heroRef = ref(null)
|
||||
const sentinelRef = ref(null)
|
||||
const heroStuck = ref(false)
|
||||
let heroObserver = null
|
||||
const mobileMenuRef = ref(null)
|
||||
|
||||
const heroMenuItems = computed(() => [
|
||||
{
|
||||
label: 'Voltar para assinaturas',
|
||||
icon: 'pi pi-arrow-left',
|
||||
command: () => router.push('/saas/subscriptions'),
|
||||
disabled: loading.value
|
||||
},
|
||||
{
|
||||
label: 'Recarregar',
|
||||
icon: 'pi pi-refresh',
|
||||
command: fetchAll,
|
||||
disabled: loading.value
|
||||
},
|
||||
{ separator: true },
|
||||
{
|
||||
label: 'Filtros',
|
||||
items: ownerTypeOptions.map(o => ({
|
||||
label: o.label,
|
||||
icon: ownerType.value === o.value ? 'pi pi-check' : 'pi pi-circle',
|
||||
command: () => { ownerType.value = o.value }
|
||||
}))
|
||||
}
|
||||
])
|
||||
|
||||
onMounted(async () => {
|
||||
const initialQ = route.query?.q
|
||||
if (typeof initialQ === 'string' && initialQ.trim()) q.value = initialQ.trim()
|
||||
if (typeof initialQ === 'string' && initialQ.trim()) {
|
||||
q.value = initialQ.trim()
|
||||
const parsed = parseOwnerKey(initialQ)
|
||||
if (parsed.kind === 'clinic') ownerType.value = 'clinic'
|
||||
if (parsed.kind === 'therapist') ownerType.value = 'therapist'
|
||||
}
|
||||
await fetchAll()
|
||||
|
||||
if (sentinelRef.value) {
|
||||
heroObserver = new IntersectionObserver(
|
||||
([entry]) => { heroStuck.value = !entry.isIntersecting },
|
||||
{ rootMargin: `${document.querySelector('.l2-main') ? '0px' : '-56px'} 0px 0px 0px`, threshold: 0 }
|
||||
)
|
||||
heroObserver.observe(sentinelRef.value)
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
heroObserver?.disconnect()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Toast />
|
||||
|
||||
<div class="p-4">
|
||||
<Toolbar class="mb-4">
|
||||
<template #start>
|
||||
<div class="flex flex-col">
|
||||
<div class="text-xl font-semibold leading-none">Histórico de Planos</div>
|
||||
<small class="text-color-secondary mt-1">
|
||||
Auditoria das mudanças de plano (eventos). Read-only.
|
||||
</small>
|
||||
</div>
|
||||
<!-- Info decorativa (scrolls away naturalmente) -->
|
||||
<div class="flex items-start gap-4 px-4 pb-3">
|
||||
<div class="events-hero__icon-wrap">
|
||||
<i class="pi pi-history events-hero__icon" />
|
||||
</div>
|
||||
<div class="events-hero__sub">
|
||||
Auditoria read-only das mudanças de plano e status. Exibe até 500 eventos mais recentes.
|
||||
<template v-if="!loading">
|
||||
• {{ totalCount }} evento(s) • {{ changedCount }} troca(s) de plano
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #end>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="p-input-icon-left">
|
||||
<i class="pi pi-search" />
|
||||
<InputText v-model="q" placeholder="Buscar owner, subscription, plano, tipo..." />
|
||||
</span>
|
||||
<Button label="Recarregar" icon="pi pi-refresh" severity="secondary" outlined :loading="loading" @click="fetchAll" />
|
||||
<!-- sentinel -->
|
||||
<div ref="sentinelRef" style="height: 1px; pointer-events: none;" />
|
||||
|
||||
<!-- hero -->
|
||||
<div
|
||||
ref="heroRef"
|
||||
class="events-hero"
|
||||
:class="{ 'events-hero--stuck': heroStuck }"
|
||||
>
|
||||
<div class="events-hero__blobs" aria-hidden="true">
|
||||
<div class="events-hero__blob events-hero__blob--1" />
|
||||
<div class="events-hero__blob events-hero__blob--2" />
|
||||
</div>
|
||||
|
||||
<div class="events-hero__inner">
|
||||
<!-- Título -->
|
||||
<div class="events-hero__info min-w-0">
|
||||
<div class="events-hero__title">Histórico de assinaturas</div>
|
||||
</div>
|
||||
|
||||
<!-- Ações desktop (≥ 1200px) -->
|
||||
<div class="events-hero__actions events-hero__actions--desktop">
|
||||
<Button
|
||||
label="Voltar para assinaturas"
|
||||
icon="pi pi-arrow-left"
|
||||
severity="secondary"
|
||||
outlined
|
||||
size="small"
|
||||
:disabled="loading"
|
||||
@click="router.push('/saas/subscriptions')"
|
||||
/>
|
||||
<SelectButton
|
||||
v-model="ownerType"
|
||||
:options="ownerTypeOptions"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
size="small"
|
||||
:disabled="loading"
|
||||
/>
|
||||
<Button
|
||||
label="Recarregar"
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
size="small"
|
||||
:loading="loading"
|
||||
@click="fetchAll"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Ações mobile (< 1200px) -->
|
||||
<div class="events-hero__actions--mobile">
|
||||
<Button
|
||||
label="Ações"
|
||||
icon="pi pi-ellipsis-v"
|
||||
severity="warn"
|
||||
size="small"
|
||||
@click="(e) => mobileMenuRef.toggle(e)"
|
||||
/>
|
||||
<Menu ref="mobileMenuRef" :model="heroMenuItems" popup />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- content -->
|
||||
<div class="px-4 pb-4">
|
||||
<!-- Card foco -->
|
||||
<div
|
||||
v-if="isFocused"
|
||||
class="mb-3 overflow-hidden rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)] shadow-sm"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-3 p-4 md:p-5">
|
||||
<div class="min-w-0">
|
||||
<div class="text-lg font-semibold leading-none">Eventos em foco</div>
|
||||
<div class="mt-1 flex flex-wrap items-center gap-2">
|
||||
<Tag value="Filtro ativo" severity="warning" rounded />
|
||||
<small class="text-color-secondary break-all">
|
||||
{{ route.query.q }}
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Toolbar>
|
||||
|
||||
<DataTable :value="filtered" dataKey="id" :loading="loading" stripedRows responsiveLayout="scroll">
|
||||
<Button
|
||||
label="Limpar filtro"
|
||||
icon="pi pi-times"
|
||||
severity="danger"
|
||||
class="font-semibold"
|
||||
raised
|
||||
:disabled="loading"
|
||||
@click="clearFocus"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- busca -->
|
||||
<div class="mb-4">
|
||||
<FloatLabel variant="on" class="w-full">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-search" />
|
||||
<InputText
|
||||
v-model="q"
|
||||
id="events_search"
|
||||
class="w-full pr-10"
|
||||
variant="filled"
|
||||
:disabled="loading"
|
||||
/>
|
||||
</IconField>
|
||||
<label for="events_search">Buscar owner, subscription, plano, tipo, usuário…</label>
|
||||
</FloatLabel>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
:value="filtered"
|
||||
dataKey="id"
|
||||
:loading="loading"
|
||||
stripedRows
|
||||
responsiveLayout="scroll"
|
||||
class="events-table"
|
||||
:rowHover="true"
|
||||
paginator
|
||||
:rows="15"
|
||||
:rowsPerPageOptions="[10,15,25,50]"
|
||||
currentPageReportTemplate="{first}–{last} de {totalRecords}"
|
||||
paginatorTemplate="RowsPerPageDropdown FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport"
|
||||
>
|
||||
<Column header="Quando" style="min-width: 14rem">
|
||||
<template #body="{ data }">
|
||||
{{ formatWhen(data.created_at) }}
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Owner" style="min-width: 22rem">
|
||||
<template #body="{ data }">
|
||||
{{ displayUser(data.owner_id) }}
|
||||
</template>
|
||||
</Column>
|
||||
<!-- Tipo = tipo do OWNER (clínica/terapeuta) -->
|
||||
<Column header="Owner tipo" style="width: 11rem">
|
||||
<template #body="{ data }">
|
||||
<Tag
|
||||
:value="ownerTagLabel(normalizeOwnerType(data.owner_type))"
|
||||
:severity="ownerTagSeverity(normalizeOwnerType(data.owner_type))"
|
||||
rounded
|
||||
/>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Owner" style="min-width: 24rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex flex-col">
|
||||
<span class="font-medium">{{ ownerKeyFromEvent(data) }}</span>
|
||||
<small class="text-color-secondary">
|
||||
{{ displayOwner(data) }}
|
||||
</small>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<!-- Evento = event_type (plan_changed/canceled/reactivated) -->
|
||||
<Column header="Evento" style="min-width: 12rem">
|
||||
<template #body="{ data }">
|
||||
<Tag :value="typeLabel(data.event_type)" :severity="typeSeverity(data.event_type)" />
|
||||
<Tag :value="eventLabel(data.event_type)" :severity="eventSeverity(data.event_type)" />
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="De → Para" style="min-width: 18rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<Tag :value="planKey(data.old_plan_id)" severity="secondary" />
|
||||
<i class="pi pi-arrow-right text-color-secondary" />
|
||||
<Tag :value="planKey(data.new_plan_id)" severity="success" />
|
||||
@@ -201,13 +499,38 @@ onMounted(async () => {
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column field="subscription_id" header="Subscription" style="min-width: 22rem" />
|
||||
<Column field="subscription_id" header="Subscription" style="min-width: 22rem">
|
||||
<template #body="{ data }">
|
||||
<span class="font-mono text-sm">{{ data.subscription_id }}</span>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Alterado por" style="min-width: 22rem">
|
||||
<template #body="{ data }">
|
||||
{{ displayUser(data.created_by) }}
|
||||
</template>
|
||||
</Column>
|
||||
<Column header="Alterado por" style="min-width: 22rem">
|
||||
<template #body="{ data }">
|
||||
{{ displayUser(data.created_by) }}
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Ações" style="width: 12rem">
|
||||
<template #body="{ data }">
|
||||
<Button
|
||||
label="Ver assinatura"
|
||||
icon="pi pi-external-link"
|
||||
size="small"
|
||||
severity="secondary"
|
||||
outlined
|
||||
class="w-full md:w-auto"
|
||||
:disabled="ownerKeyFromEvent(data) === 'unknown'"
|
||||
@click="goToSubscriptions(data)"
|
||||
/>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<template #empty>
|
||||
<div class="p-4 text-color-secondary">
|
||||
Nenhum evento encontrado com os filtros atuais.
|
||||
</div>
|
||||
</template>
|
||||
</DataTable>
|
||||
|
||||
<div class="text-color-secondary mt-3 text-sm">
|
||||
@@ -215,3 +538,76 @@ onMounted(async () => {
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.events-table :deep(.p-paginator) {
|
||||
border-top: 1px solid var(--surface-border);
|
||||
}
|
||||
|
||||
.events-table :deep(.p-datatable-tbody > tr > td) {
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.font-mono {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
}
|
||||
|
||||
/* Hero */
|
||||
.events-hero {
|
||||
position: sticky;
|
||||
top: var(--layout-sticky-top, 56px);
|
||||
z-index: 20;
|
||||
overflow: hidden;
|
||||
border-radius: 1.75rem;
|
||||
border: 1px solid var(--surface-border);
|
||||
background: var(--surface-card);
|
||||
padding: 1.5rem;
|
||||
margin: 1rem;
|
||||
}
|
||||
.events-hero--stuck {
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
}
|
||||
|
||||
.events-hero__blobs {
|
||||
position: absolute; inset: 0; pointer-events: none; overflow: hidden;
|
||||
}
|
||||
.events-hero__blob {
|
||||
position: absolute; border-radius: 50%; filter: blur(70px);
|
||||
}
|
||||
.events-hero__blob--1 { width: 20rem; height: 20rem; top: -5rem; right: -4rem; background: rgba(251,191,36,0.12); }
|
||||
.events-hero__blob--2 { width: 18rem; height: 18rem; top: 1rem; left: -5rem; background: rgba(249,115,22,0.09); }
|
||||
|
||||
.events-hero__inner {
|
||||
position: relative; z-index: 1;
|
||||
display: flex; align-items: center; gap: 1.25rem; flex-wrap: wrap;
|
||||
}
|
||||
.events-hero__icon-wrap {
|
||||
flex-shrink: 0;
|
||||
width: 4rem; height: 4rem; border-radius: 1.125rem;
|
||||
border: 2px solid var(--surface-border);
|
||||
background: var(--surface-ground);
|
||||
display: grid; place-items: center;
|
||||
}
|
||||
.events-hero__icon { font-size: 1.5rem; color: var(--text-color); }
|
||||
|
||||
.events-hero__info { flex: 1; min-width: 0; }
|
||||
.events-hero__title {
|
||||
font-size: 1.25rem; font-weight: 700; letter-spacing: -0.025em;
|
||||
color: var(--text-color); line-height: 1.2;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.events-hero__sub {
|
||||
font-size: 0.78rem; color: var(--text-color-secondary); margin-top: 4px; line-height: 1.5;
|
||||
}
|
||||
|
||||
.events-hero__actions--desktop {
|
||||
display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap;
|
||||
}
|
||||
.events-hero__actions--mobile { display: none; }
|
||||
|
||||
@media (max-width: 1199px) {
|
||||
.events-hero__actions--desktop { display: none; }
|
||||
.events-hero__actions--mobile { display: flex; }
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,32 +1,34 @@
|
||||
<!-- src/views/pages/saas/SubscriptionHealthPage.vue -->
|
||||
<script setup>
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
import { useConfirm } from 'primevue/useconfirm'
|
||||
|
||||
import Toolbar from 'primevue/toolbar'
|
||||
import Button from 'primevue/button'
|
||||
import Toast from 'primevue/toast'
|
||||
import DataTable from 'primevue/datatable'
|
||||
import Column from 'primevue/column'
|
||||
import Tag from 'primevue/tag'
|
||||
import InputText from 'primevue/inputtext'
|
||||
import Divider from 'primevue/divider'
|
||||
import TabView from 'primevue/tabview'
|
||||
import TabPanel from 'primevue/tabpanel'
|
||||
import Message from 'primevue/message'
|
||||
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
const confirm = useConfirm()
|
||||
|
||||
const loading = ref(false)
|
||||
const fixing = ref(false)
|
||||
const fixingOwner = ref(null)
|
||||
const isFetching = ref(false)
|
||||
|
||||
const activeTab = ref(0) // 0 = terapeutas, 1 = clínicas
|
||||
|
||||
const rows = ref([])
|
||||
const q = ref('')
|
||||
|
||||
const total = computed(() => rows.value.length)
|
||||
const totalMissing = computed(() => rows.value.filter(r => r.mismatch_type === 'missing_entitlement').length)
|
||||
const totalUnexpected = computed(() => rows.value.filter(r => r.mismatch_type === 'unexpected_entitlement').length)
|
||||
const personalRows = ref([]) // v_subscription_feature_mismatch
|
||||
const clinicRows = ref([]) // v_tenant_feature_exceptions
|
||||
|
||||
// -----------------------------
|
||||
// Labels / Severities
|
||||
// -----------------------------
|
||||
function severityForMismatch (t) {
|
||||
if (t === 'missing_entitlement') return 'danger'
|
||||
if (t === 'unexpected_entitlement') return 'warning'
|
||||
@@ -34,40 +36,200 @@ function severityForMismatch (t) {
|
||||
}
|
||||
|
||||
function labelForMismatch (t) {
|
||||
if (t === 'missing_entitlement') return 'Missing'
|
||||
if (t === 'unexpected_entitlement') return 'Unexpected'
|
||||
return t || '-'
|
||||
if (t === 'missing_entitlement') return 'Faltando'
|
||||
if (t === 'unexpected_entitlement') return 'Inesperado'
|
||||
return t || '—'
|
||||
}
|
||||
|
||||
async function fetchAll () {
|
||||
loading.value = true
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('v_subscription_feature_mismatch')
|
||||
.select('*')
|
||||
|
||||
if (error) throw error
|
||||
rows.value = data || []
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 5000 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
function helpForMismatch (t) {
|
||||
if (t === 'missing_entitlement') return 'O plano exige, mas não está ativo'
|
||||
if (t === 'unexpected_entitlement') return 'Está ativo, mas não consta no plano'
|
||||
return ''
|
||||
}
|
||||
|
||||
function filteredRows () {
|
||||
function severityForException () {
|
||||
return 'info'
|
||||
}
|
||||
|
||||
function labelForException (t) {
|
||||
if (t === 'commercial_exception') return 'Exceção comercial'
|
||||
return t || 'Exceção'
|
||||
}
|
||||
|
||||
function helpForException () {
|
||||
return 'Feature liberada manualmente fora do plano (exceção controlada)'
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Computeds (Terapeutas)
|
||||
// -----------------------------
|
||||
const totalPersonal = computed(() => personalRows.value.length)
|
||||
const totalPersonalMissing = computed(() => personalRows.value.filter(r => r.mismatch_type === 'missing_entitlement').length)
|
||||
const totalPersonalUnexpected = computed(() => personalRows.value.filter(r => r.mismatch_type === 'unexpected_entitlement').length)
|
||||
const totalPersonalWithoutOwner = computed(() => personalRows.value.filter(r => !r.owner_id).length)
|
||||
|
||||
// -----------------------------
|
||||
// Computeds (Clínicas)
|
||||
// -----------------------------
|
||||
const totalClinic = computed(() => clinicRows.value.length)
|
||||
|
||||
// -----------------------------
|
||||
// Search filtering
|
||||
// -----------------------------
|
||||
const filteredPersonal = computed(() => {
|
||||
const term = String(q.value || '').trim().toLowerCase()
|
||||
if (!term) return rows.value
|
||||
return rows.value.filter(r =>
|
||||
if (!term) return personalRows.value
|
||||
|
||||
return personalRows.value.filter(r =>
|
||||
String(r.owner_id || '').toLowerCase().includes(term) ||
|
||||
String(r.feature_key || '').toLowerCase().includes(term) ||
|
||||
String(r.mismatch_type || '').toLowerCase().includes(term)
|
||||
)
|
||||
})
|
||||
|
||||
const filteredClinic = computed(() => {
|
||||
const term = String(q.value || '').trim().toLowerCase()
|
||||
if (!term) return clinicRows.value
|
||||
|
||||
return clinicRows.value.filter(r =>
|
||||
String(r.tenant_id || '').toLowerCase().includes(term) ||
|
||||
String(r.tenant_name || '').toLowerCase().includes(term) ||
|
||||
String(r.plan_key || '').toLowerCase().includes(term) ||
|
||||
String(r.feature_key || '').toLowerCase().includes(term) ||
|
||||
String(r.exception_type || '').toLowerCase().includes(term)
|
||||
)
|
||||
})
|
||||
|
||||
// -----------------------------
|
||||
// Fetch
|
||||
// -----------------------------
|
||||
async function fetchPersonal () {
|
||||
const { data, error } = await supabase
|
||||
.from('v_subscription_feature_mismatch')
|
||||
.select('*')
|
||||
|
||||
if (error) throw error
|
||||
|
||||
personalRows.value = (data || []).map(r => ({
|
||||
...r,
|
||||
__rowKey: `${r.owner_id || 'no_owner'}|${r.feature_key || 'no_feature'}|${r.mismatch_type || 'no_type'}`
|
||||
}))
|
||||
}
|
||||
|
||||
function openOwnerSubscriptions (ownerId) {
|
||||
if (!ownerId) return
|
||||
router.push({ path: '/saas/subscriptions', query: { q: ownerId } })
|
||||
async function fetchClinic () {
|
||||
const { data, error } = await supabase
|
||||
.from('v_tenant_feature_exceptions')
|
||||
.select('*')
|
||||
|
||||
if (error) throw error
|
||||
|
||||
clinicRows.value = (data || []).map(r => ({
|
||||
...r,
|
||||
__rowKey: `${r.tenant_id || 'no_tenant'}|${r.feature_key || 'no_feature'}|${r.exception_type || 'no_type'}`
|
||||
}))
|
||||
}
|
||||
|
||||
async function fetchAll () {
|
||||
if (isFetching.value) return
|
||||
isFetching.value = true
|
||||
loading.value = true
|
||||
|
||||
try {
|
||||
await Promise.all([fetchPersonal(), fetchClinic()])
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 5000 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
isFetching.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadActiveTab () {
|
||||
if (isFetching.value) return
|
||||
isFetching.value = true
|
||||
loading.value = true
|
||||
|
||||
try {
|
||||
if (activeTab.value === 0) await fetchPersonal()
|
||||
else await fetchClinic()
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 5000 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
isFetching.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Navigation helpers
|
||||
// -----------------------------
|
||||
async function inferOwnerKey (ownerId) {
|
||||
if (!ownerId) return null
|
||||
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('tenants')
|
||||
.select('id')
|
||||
.eq('id', ownerId)
|
||||
.maybeSingle()
|
||||
|
||||
if (!error && data?.id) return `clinic:${ownerId}`
|
||||
} catch (_) {}
|
||||
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('tenant_members')
|
||||
.select('tenant_id')
|
||||
.eq('tenant_id', ownerId)
|
||||
.limit(1)
|
||||
|
||||
if (!error && Array.isArray(data) && data.length) return `clinic:${ownerId}`
|
||||
} catch (_) {}
|
||||
|
||||
return `therapist:${ownerId}`
|
||||
}
|
||||
|
||||
async function openOwnerSubscriptions (ownerId) {
|
||||
if (!ownerId) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Owner ausente',
|
||||
detail: 'Esta linha está sem owner_id. Verifique dados inconsistentes.',
|
||||
life: 4200
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const key = await inferOwnerKey(ownerId)
|
||||
router.push({ path: '/saas/subscriptions', query: { q: key || ownerId } })
|
||||
}
|
||||
|
||||
function openClinicSubscriptions (tenantId) {
|
||||
if (!tenantId) return
|
||||
router.push({ path: '/saas/subscriptions', query: { q: `clinic:${tenantId}` } })
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Fix (Terapeutas)
|
||||
// -----------------------------
|
||||
function askFixOwner (ownerId) {
|
||||
if (!ownerId) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Owner ausente',
|
||||
detail: 'Não é possível corrigir um owner vazio.',
|
||||
life: 4500
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
confirm.require({
|
||||
header: 'Confirmar correção',
|
||||
message: `Reconstruir entitlements para este owner?\n\n${ownerId}\n\nIsso recalcula os recursos ativos com base no plano atual.`,
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptClass: 'p-button-danger',
|
||||
accept: () => fixOwner(ownerId)
|
||||
})
|
||||
}
|
||||
|
||||
async function fixOwner (ownerId) {
|
||||
@@ -89,15 +251,32 @@ async function fixOwner (ownerId) {
|
||||
life: 2500
|
||||
})
|
||||
|
||||
await fetchAll()
|
||||
await fetchPersonal()
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 5000 })
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: 'Erro ao corrigir owner',
|
||||
detail: e?.message || String(e),
|
||||
life: 5200
|
||||
})
|
||||
} finally {
|
||||
fixing.value = false
|
||||
fixingOwner.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function askFixAll () {
|
||||
if (!totalPersonal.value) return
|
||||
|
||||
confirm.require({
|
||||
header: 'Confirmar correção geral',
|
||||
message: `Reconstruir entitlements para TODOS os owners com divergência?\n\nTotal: ${totalPersonal.value}\n\nObs.: linhas sem owner_id indicam dado inconsistente.`,
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptClass: 'p-button-danger',
|
||||
accept: () => fixAll()
|
||||
})
|
||||
}
|
||||
|
||||
async function fixAll () {
|
||||
fixing.value = true
|
||||
try {
|
||||
@@ -106,126 +285,482 @@ async function fixAll () {
|
||||
|
||||
toast.add({
|
||||
severity: 'success',
|
||||
summary: 'Sistema corrigido',
|
||||
summary: 'Correção aplicada',
|
||||
detail: 'Entitlements reconstruídos para todos os owners com divergência.',
|
||||
life: 3000
|
||||
})
|
||||
|
||||
await fetchAll()
|
||||
await fetchPersonal()
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 5000 })
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: 'Erro ao corrigir tudo',
|
||||
detail: e?.message || String(e),
|
||||
life: 5200
|
||||
})
|
||||
} finally {
|
||||
fixing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(fetchAll)
|
||||
// -----------------------------
|
||||
// Exceptions (Clínicas)
|
||||
// -----------------------------
|
||||
function askRemoveException (tenantId, featureKey) {
|
||||
if (!tenantId || !featureKey) return
|
||||
|
||||
confirm.require({
|
||||
header: 'Remover exceção',
|
||||
message: `Desativar a exceção desta clínica?\n\nTenant: ${tenantId}\nFeature: ${featureKey}\n\nIsso desliga a liberação manual fora do plano.`,
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptClass: 'p-button-danger',
|
||||
accept: () => removeException(tenantId, featureKey)
|
||||
})
|
||||
}
|
||||
|
||||
async function removeException (tenantId, featureKey) {
|
||||
fixing.value = true
|
||||
|
||||
try {
|
||||
const { error } = await supabase.rpc('set_tenant_feature_exception', {
|
||||
p_tenant_id: tenantId,
|
||||
p_feature_key: featureKey,
|
||||
p_enabled: false,
|
||||
p_reason: 'Remoção via Saúde das Assinaturas'
|
||||
})
|
||||
if (error) throw error
|
||||
|
||||
toast.add({
|
||||
severity: 'success',
|
||||
summary: 'Exceção removida',
|
||||
detail: 'A liberação manual foi desativada para esta feature.',
|
||||
life: 2800
|
||||
})
|
||||
|
||||
await fetchClinic()
|
||||
} catch (e) {
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: 'Erro ao remover exceção',
|
||||
detail: e?.message || String(e),
|
||||
life: 5200
|
||||
})
|
||||
} finally {
|
||||
fixing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------
|
||||
// Hero sticky
|
||||
// -------------------------
|
||||
const heroRef = ref(null)
|
||||
const sentinelRef = ref(null)
|
||||
const heroStuck = ref(false)
|
||||
let heroObserver = null
|
||||
const mobileMenuRef = ref(null)
|
||||
|
||||
const heroMenuItems = computed(() => [
|
||||
{
|
||||
label: 'Recarregar aba',
|
||||
icon: 'pi pi-refresh',
|
||||
command: reloadActiveTab,
|
||||
disabled: loading.value || fixing.value
|
||||
},
|
||||
{
|
||||
label: 'Recarregar tudo',
|
||||
icon: 'pi pi-sync',
|
||||
command: fetchAll,
|
||||
disabled: loading.value || fixing.value
|
||||
},
|
||||
...(activeTab.value === 0 && totalPersonal.value > 0 ? [{
|
||||
label: 'Corrigir tudo (terapeutas)',
|
||||
icon: 'pi pi-wrench',
|
||||
command: askFixAll,
|
||||
disabled: loading.value || fixing.value
|
||||
}] : [])
|
||||
])
|
||||
|
||||
onMounted(() => {
|
||||
fetchAll()
|
||||
|
||||
if (sentinelRef.value) {
|
||||
heroObserver = new IntersectionObserver(
|
||||
([entry]) => { heroStuck.value = !entry.isIntersecting },
|
||||
{ rootMargin: `${document.querySelector('.l2-main') ? '0px' : '-56px'} 0px 0px 0px`, threshold: 0 }
|
||||
)
|
||||
heroObserver.observe(sentinelRef.value)
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
heroObserver?.disconnect()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Toast />
|
||||
<ConfirmDialog />
|
||||
|
||||
<div class="p-4">
|
||||
<Toolbar class="mb-4">
|
||||
<template #start>
|
||||
<div class="flex flex-col">
|
||||
<div class="text-xl font-semibold leading-none">Subscription Health</div>
|
||||
<small class="text-color-secondary mt-1">
|
||||
Divergências entre Plano (esperado) e Entitlements (atual). Use “Fix” para reconstruir.
|
||||
</small>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #end>
|
||||
<div class="flex items-center gap-2 flex-wrap justify-end">
|
||||
<span class="p-input-icon-left">
|
||||
<i class="pi pi-search" />
|
||||
<InputText v-model="q" placeholder="Buscar owner_id, feature_key..." />
|
||||
</span>
|
||||
|
||||
<Button
|
||||
label="Recarregar"
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:loading="loading"
|
||||
@click="fetchAll"
|
||||
/>
|
||||
|
||||
<Button
|
||||
v-if="total > 0"
|
||||
label="Fix All"
|
||||
icon="pi pi-refresh"
|
||||
severity="danger"
|
||||
:loading="fixing"
|
||||
@click="fixAll"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Toolbar>
|
||||
|
||||
<!-- resumo conceitual -->
|
||||
<div class="surface-100 border-round p-3 mb-4">
|
||||
<div class="flex flex-wrap gap-2 items-center justify-content-between">
|
||||
<div class="flex gap-2 items-center flex-wrap">
|
||||
<Tag :value="`Total: ${total}`" severity="secondary" />
|
||||
<Tag :value="`Missing: ${totalMissing}`" severity="danger" />
|
||||
<Tag :value="`Unexpected: ${totalUnexpected}`" severity="warning" />
|
||||
</div>
|
||||
|
||||
<div class="text-color-secondary text-sm">
|
||||
“Missing” = plano exige, mas não está ativo · “Unexpected” = ativo sem constar no plano
|
||||
</div>
|
||||
</div>
|
||||
<!-- Info decorativa (scrolls away naturalmente) -->
|
||||
<div class="flex items-start gap-4 px-4 pb-3">
|
||||
<div class="health-hero__icon-wrap">
|
||||
<i class="pi pi-shield health-hero__icon" />
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
:value="filteredRows()"
|
||||
dataKey="owner_id"
|
||||
:loading="loading"
|
||||
stripedRows
|
||||
responsiveLayout="scroll"
|
||||
sortField="owner_id"
|
||||
:sortOrder="1"
|
||||
>
|
||||
<Column field="owner_id" header="Owner" style="min-width: 22rem" />
|
||||
|
||||
<Column field="feature_key" header="Feature" style="min-width: 18rem" />
|
||||
|
||||
<Column header="Tipo" style="width: 12rem">
|
||||
<template #body="{ data }">
|
||||
<Tag :severity="severityForMismatch(data.mismatch_type)" :value="labelForMismatch(data.mismatch_type)" />
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Ações" style="min-width: 18rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex gap-2 flex-wrap">
|
||||
<Button
|
||||
icon="pi pi-external-link"
|
||||
severity="secondary"
|
||||
outlined
|
||||
v-tooltip.top="'Abrir subscriptions deste owner (filtro)'"
|
||||
@click="openOwnerSubscriptions(data.owner_id)"
|
||||
/>
|
||||
|
||||
<Button
|
||||
label="Fix owner"
|
||||
icon="pi pi-wrench"
|
||||
severity="danger"
|
||||
outlined
|
||||
:loading="fixing && fixingOwner === data.owner_id"
|
||||
@click="fixOwner(data.owner_id)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
</DataTable>
|
||||
|
||||
<Divider class="my-5" />
|
||||
|
||||
<div class="text-color-secondary text-sm">
|
||||
Dica: se você trocar plano e o cliente não refletir de imediato, essa página te mostra exatamente o que ficou divergente.
|
||||
<div class="health-hero__sub">
|
||||
Terapeutas: divergências entre plano (esperado) e entitlements (atual).
|
||||
Clínicas: exceções comerciais (features liberadas manualmente fora do plano).
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- sentinel -->
|
||||
<div ref="sentinelRef" style="height: 1px; pointer-events: none;" />
|
||||
|
||||
<!-- hero -->
|
||||
<div
|
||||
ref="heroRef"
|
||||
class="health-hero"
|
||||
:class="{ 'health-hero--stuck': heroStuck }"
|
||||
>
|
||||
<div class="health-hero__blobs" aria-hidden="true">
|
||||
<div class="health-hero__blob health-hero__blob--1" />
|
||||
<div class="health-hero__blob health-hero__blob--2" />
|
||||
</div>
|
||||
|
||||
<div class="health-hero__inner">
|
||||
<!-- Título -->
|
||||
<div class="health-hero__info min-w-0">
|
||||
<div class="health-hero__title">Saúde das Assinaturas</div>
|
||||
</div>
|
||||
|
||||
<!-- Ações desktop (≥ 1200px) -->
|
||||
<div class="health-hero__actions health-hero__actions--desktop">
|
||||
<Button
|
||||
label="Recarregar"
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
size="small"
|
||||
:loading="loading"
|
||||
:disabled="fixing"
|
||||
@click="reloadActiveTab"
|
||||
/>
|
||||
<Button
|
||||
label="Recarregar tudo"
|
||||
icon="pi pi-sync"
|
||||
severity="secondary"
|
||||
outlined
|
||||
size="small"
|
||||
:loading="loading"
|
||||
:disabled="fixing"
|
||||
@click="fetchAll"
|
||||
/>
|
||||
<Button
|
||||
v-if="activeTab === 0 && totalPersonal > 0"
|
||||
label="Corrigir tudo (terapeutas)"
|
||||
icon="pi pi-wrench"
|
||||
severity="danger"
|
||||
size="small"
|
||||
:loading="fixing"
|
||||
:disabled="loading"
|
||||
@click="askFixAll"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Ações mobile (< 1200px) -->
|
||||
<div class="health-hero__actions--mobile">
|
||||
<Button
|
||||
label="Ações"
|
||||
icon="pi pi-ellipsis-v"
|
||||
severity="warn"
|
||||
size="small"
|
||||
@click="(e) => mobileMenuRef.toggle(e)"
|
||||
/>
|
||||
<Menu ref="mobileMenuRef" :model="heroMenuItems" popup />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- content -->
|
||||
<div class="px-4 pb-4">
|
||||
<!-- busca -->
|
||||
<div class="mb-4">
|
||||
<FloatLabel variant="on" class="w-full">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-search" />
|
||||
<InputText
|
||||
v-model="q"
|
||||
id="health_search"
|
||||
class="w-full pr-10"
|
||||
variant="filled"
|
||||
:disabled="loading || fixing"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</IconField>
|
||||
<label for="health_search">Buscar...</label>
|
||||
</FloatLabel>
|
||||
</div>
|
||||
|
||||
<TabView v-model:activeIndex="activeTab">
|
||||
<!-- ===================================================== -->
|
||||
<!-- Terapeutas (Personal) -->
|
||||
<!-- ===================================================== -->
|
||||
<TabPanel header="Terapeutas (Pessoal)">
|
||||
<div class="surface-100 border-round p-3 mb-4">
|
||||
<div class="flex flex-wrap gap-2 items-center justify-content-between">
|
||||
<div class="flex gap-2 items-center flex-wrap">
|
||||
<Tag :value="`Divergências: ${totalPersonal}`" severity="secondary" />
|
||||
<Tag :value="`Faltando: ${totalPersonalMissing}`" severity="danger" />
|
||||
<Tag :value="`Inesperado: ${totalPersonalUnexpected}`" severity="warning" />
|
||||
<Tag v-if="totalPersonalWithoutOwner > 0" :value="`Sem owner: ${totalPersonalWithoutOwner}`" severity="warn" />
|
||||
</div>
|
||||
|
||||
<div class="text-color-secondary text-sm">
|
||||
<span class="font-medium">Faltando</span>: o plano exige, mas não está ativo ·
|
||||
<span class="font-medium">Inesperado</span>: está ativo sem constar no plano
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
:value="filteredPersonal"
|
||||
dataKey="__rowKey"
|
||||
:loading="loading"
|
||||
stripedRows
|
||||
responsiveLayout="scroll"
|
||||
sortField="owner_id"
|
||||
:sortOrder="1"
|
||||
>
|
||||
<Column header="Owner (User)" style="min-width: 22rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="font-medium">
|
||||
{{ data.owner_id || '—' }}
|
||||
</span>
|
||||
<Tag v-if="!data.owner_id" value="Sem owner" severity="warn" rounded />
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Recurso" style="min-width: 18rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex flex-col">
|
||||
<span class="font-medium">{{ data.feature_key }}</span>
|
||||
<small class="text-color-secondary">
|
||||
{{ helpForMismatch(data.mismatch_type) || '—' }}
|
||||
</small>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Tipo" style="width: 12rem">
|
||||
<template #body="{ data }">
|
||||
<Tag :severity="severityForMismatch(data.mismatch_type)" :value="labelForMismatch(data.mismatch_type)" />
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Ações" style="min-width: 20rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex gap-2 flex-wrap">
|
||||
<Button
|
||||
icon="pi pi-external-link"
|
||||
severity="secondary"
|
||||
outlined
|
||||
v-tooltip.top="data.owner_id ? 'Abrir assinaturas deste owner (com filtro)' : 'Owner ausente'"
|
||||
:disabled="loading || fixing || !data.owner_id"
|
||||
@click="openOwnerSubscriptions(data.owner_id)"
|
||||
/>
|
||||
|
||||
<Button
|
||||
label="Corrigir owner"
|
||||
icon="pi pi-wrench"
|
||||
severity="danger"
|
||||
outlined
|
||||
v-tooltip.top="data.owner_id ? 'Reconstruir entitlements deste owner' : 'Owner ausente'"
|
||||
:loading="fixing && fixingOwner === data.owner_id"
|
||||
:disabled="loading || !data.owner_id || (fixing && fixingOwner !== data.owner_id)"
|
||||
@click="askFixOwner(data.owner_id)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
</DataTable>
|
||||
|
||||
<Divider class="my-5" />
|
||||
|
||||
<Message severity="info" class="mt-4">
|
||||
<div class="text-sm line-height-3">
|
||||
<p class="mb-0">
|
||||
<span class="font-semibold">Dica:</span>
|
||||
Se você alterar o plano e o acesso não refletir imediatamente, esta aba exibirá as divergências entre o plano ativo e os entitlements atuais.
|
||||
A ação <span class="font-medium">Corrigir</span> reconstrói os entitlements do owner com base no plano vigente e elimina inconsistências.
|
||||
</p>
|
||||
</div>
|
||||
</Message>
|
||||
</TabPanel>
|
||||
|
||||
<!-- ===================================================== -->
|
||||
<!-- Clínicas (Tenant) -->
|
||||
<!-- ===================================================== -->
|
||||
<TabPanel header="Clínicas (Exceções)">
|
||||
<div class="surface-100 border-round p-3 mb-4">
|
||||
<div class="flex flex-wrap gap-2 items-center justify-content-between">
|
||||
<div class="flex gap-2 items-center flex-wrap">
|
||||
<Tag :value="`Exceções ativas: ${totalClinic}`" severity="info" />
|
||||
</div>
|
||||
|
||||
<div class="text-color-secondary text-sm">
|
||||
Exceções comerciais: features liberadas manualmente fora do plano. Útil para testes, suporte e acordos.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
:value="filteredClinic"
|
||||
dataKey="__rowKey"
|
||||
:loading="loading"
|
||||
stripedRows
|
||||
responsiveLayout="scroll"
|
||||
sortField="tenant_id"
|
||||
:sortOrder="1"
|
||||
>
|
||||
<Column header="Clínica (Tenant)" style="min-width: 22rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex flex-col">
|
||||
<span class="font-medium">{{ data.tenant_name || data.tenant_id }}</span>
|
||||
<small class="text-color-secondary">{{ data.tenant_name ? data.tenant_id : '—' }}</small>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Plano" style="width: 12rem">
|
||||
<template #body="{ data }">
|
||||
<Tag :value="data.plan_key || '—'" severity="secondary" />
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Feature" style="min-width: 18rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex flex-col">
|
||||
<span class="font-medium">{{ data.feature_key }}</span>
|
||||
<small class="text-color-secondary">
|
||||
{{ helpForException() }}
|
||||
</small>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Tipo" style="width: 14rem">
|
||||
<template #body="{ data }">
|
||||
<Tag :severity="severityForException()" :value="labelForException(data.exception_type)" />
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Ações" style="min-width: 22rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex gap-2 flex-wrap">
|
||||
<Button
|
||||
icon="pi pi-external-link"
|
||||
severity="secondary"
|
||||
outlined
|
||||
v-tooltip.top="'Abrir assinaturas desta clínica (com filtro)'"
|
||||
:disabled="loading || fixing || !data.tenant_id"
|
||||
@click="openClinicSubscriptions(data.tenant_id)"
|
||||
/>
|
||||
|
||||
<Button
|
||||
label="Remover exceção"
|
||||
icon="pi pi-ban"
|
||||
severity="danger"
|
||||
outlined
|
||||
v-tooltip.top="'Desativar a liberação manual desta feature'"
|
||||
:disabled="loading || fixing || !data.tenant_id || !data.feature_key"
|
||||
@click="askRemoveException(data.tenant_id, data.feature_key)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
</DataTable>
|
||||
|
||||
<Divider class="my-5" />
|
||||
|
||||
<Message severity="info" class="mt-4">
|
||||
<div class="text-sm line-height-3">
|
||||
<p class="mb-2">
|
||||
<span class="font-semibold">Observação:</span>
|
||||
Exceção é uma escolha de negócio. Quando ativa, pode liberar acesso mesmo que o plano não permita.
|
||||
Utilize <span class="font-medium">Remover exceção</span> quando a liberação deixar de fazer sentido.
|
||||
</p>
|
||||
|
||||
<p class="mb-0">
|
||||
<span class="font-semibold">Dica:</span>
|
||||
Exceções comerciais liberam recursos fora do plano.
|
||||
Se o acesso não refletir como esperado, verifique se existe uma exceção ativa para esta clínica.
|
||||
A ação <span class="font-medium">Remover exceção</span> restaura o comportamento estritamente definido pelo plano.
|
||||
</p>
|
||||
</div>
|
||||
</Message>
|
||||
</TabPanel>
|
||||
</TabView>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* Hero */
|
||||
.health-hero {
|
||||
position: sticky;
|
||||
top: var(--layout-sticky-top, 56px);
|
||||
z-index: 20;
|
||||
overflow: hidden;
|
||||
border-radius: 1.75rem;
|
||||
border: 1px solid var(--surface-border);
|
||||
background: var(--surface-card);
|
||||
padding: 1.5rem;
|
||||
margin: 1rem;
|
||||
}
|
||||
.health-hero--stuck {
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
}
|
||||
|
||||
.health-hero__blobs {
|
||||
position: absolute; inset: 0; pointer-events: none; overflow: hidden;
|
||||
}
|
||||
.health-hero__blob {
|
||||
position: absolute; border-radius: 50%; filter: blur(70px);
|
||||
}
|
||||
.health-hero__blob--1 { width: 20rem; height: 20rem; top: -5rem; right: -4rem; background: rgba(248,113,113,0.12); }
|
||||
.health-hero__blob--2 { width: 18rem; height: 18rem; top: 1rem; left: -5rem; background: rgba(251,113,133,0.09); }
|
||||
|
||||
.health-hero__inner {
|
||||
position: relative; z-index: 1;
|
||||
display: flex; align-items: center; gap: 1.25rem; flex-wrap: wrap;
|
||||
}
|
||||
.health-hero__icon-wrap {
|
||||
flex-shrink: 0;
|
||||
width: 4rem; height: 4rem; border-radius: 1.125rem;
|
||||
border: 2px solid var(--surface-border);
|
||||
background: var(--surface-ground);
|
||||
display: grid; place-items: center;
|
||||
}
|
||||
.health-hero__icon { font-size: 1.5rem; color: var(--text-color); }
|
||||
|
||||
.health-hero__info { flex: 1; min-width: 0; }
|
||||
.health-hero__title {
|
||||
font-size: 1.25rem; font-weight: 700; letter-spacing: -0.025em;
|
||||
color: var(--text-color); line-height: 1.2;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.health-hero__sub {
|
||||
font-size: 0.78rem; color: var(--text-color-secondary); margin-top: 4px; line-height: 1.5;
|
||||
}
|
||||
|
||||
.health-hero__actions--desktop {
|
||||
display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap;
|
||||
}
|
||||
.health-hero__actions--mobile { display: none; }
|
||||
|
||||
@media (max-width: 1199px) {
|
||||
.health-hero__actions--desktop { display: none; }
|
||||
.health-hero__actions--mobile { display: flex; }
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,40 +1,129 @@
|
||||
<script setup>
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { supabase } from '@/lib/supabase/client'
|
||||
|
||||
import Toolbar from 'primevue/toolbar'
|
||||
import Button from 'primevue/button'
|
||||
import DataTable from 'primevue/datatable'
|
||||
import Column from 'primevue/column'
|
||||
import Select from 'primevue/select'
|
||||
import Toast from 'primevue/toast'
|
||||
import Dropdown from 'primevue/dropdown'
|
||||
import { useToast } from 'primevue/usetoast'
|
||||
import InputText from 'primevue/inputtext'
|
||||
import Tag from 'primevue/tag'
|
||||
import { useConfirm } from 'primevue/useconfirm'
|
||||
|
||||
const toast = useToast()
|
||||
const confirm = useConfirm()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const loading = ref(false)
|
||||
const savingId = ref(null)
|
||||
const isFetching = ref(false)
|
||||
|
||||
const plans = ref([])
|
||||
const subs = ref([])
|
||||
|
||||
const q = ref('')
|
||||
|
||||
// filtro tipo
|
||||
const typeFilter = ref('all') // 'all' | 'clinic' | 'therapist'
|
||||
const typeOptions = [
|
||||
{ label: 'Todos', value: 'all' },
|
||||
{ label: 'Clínica', value: 'clinic' },
|
||||
{ label: 'Terapeuta', value: 'therapist' }
|
||||
]
|
||||
|
||||
const isFocused = computed(() => {
|
||||
return typeof route.query?.q === 'string' && route.query.q.trim().length > 0
|
||||
})
|
||||
|
||||
// -------------------------
|
||||
// ownerKey helpers
|
||||
// -------------------------
|
||||
function parseOwnerKey (raw) {
|
||||
const s = String(raw || '').trim()
|
||||
if (!s) return { kind: 'unknown', id: null, raw: '' }
|
||||
|
||||
const m = s.match(/^(clinic|therapist)\s*:\s*([0-9a-fA-F-]{8,})$/)
|
||||
if (m) return { kind: m[1].toLowerCase(), id: m[2], raw: s }
|
||||
|
||||
return { kind: 'unknown', id: s, raw: s }
|
||||
}
|
||||
|
||||
function subscriptionType (s) {
|
||||
if (s?.tenant_id) return 'clinic'
|
||||
if (s?.user_id && !s?.tenant_id) return 'therapist'
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
function ownerKey (s) {
|
||||
const t = subscriptionType(s)
|
||||
if (t === 'clinic') return `clinic:${s.tenant_id}`
|
||||
if (t === 'therapist') return `therapist:${s.user_id}`
|
||||
return String(s?.user_id || s?.tenant_id || '(desconhecido)')
|
||||
}
|
||||
|
||||
function typeLabel (t) {
|
||||
if (t === 'clinic') return 'Clínica'
|
||||
if (t === 'therapist') return 'Terapeuta'
|
||||
return '—'
|
||||
}
|
||||
|
||||
function typeSeverity (t) {
|
||||
if (t === 'clinic') return 'info'
|
||||
if (t === 'therapist') return 'success'
|
||||
return 'secondary'
|
||||
}
|
||||
|
||||
function statusLabel (st) {
|
||||
const s = String(st || '').toLowerCase()
|
||||
if (s === 'active') return 'Ativa'
|
||||
if (s === 'trialing') return 'Teste'
|
||||
if (s === 'past_due') return 'Em atraso'
|
||||
if (s === 'canceled' || s === 'cancelled') return 'Cancelada'
|
||||
if (!s) return '—'
|
||||
return st
|
||||
}
|
||||
|
||||
function statusSeverity (st) {
|
||||
const s = String(st || '').toLowerCase()
|
||||
if (s === 'active') return 'success'
|
||||
if (s === 'trialing') return 'info'
|
||||
if (s === 'past_due') return 'warning'
|
||||
if (s === 'canceled' || s === 'cancelled') return 'danger'
|
||||
return 'secondary'
|
||||
}
|
||||
|
||||
function intervalLabel (itv) {
|
||||
const s = String(itv || '').toLowerCase()
|
||||
if (!s) return '—'
|
||||
if (s === 'month') return 'Mensal'
|
||||
if (s === 'year') return 'Anual'
|
||||
return s
|
||||
}
|
||||
|
||||
function fmtDate (v) {
|
||||
if (!v) return '—'
|
||||
const d = new Date(v)
|
||||
if (Number.isNaN(d.getTime())) return String(v)
|
||||
return d.toLocaleString('pt-BR')
|
||||
}
|
||||
|
||||
// -------------------------
|
||||
// fetch
|
||||
// -------------------------
|
||||
async function fetchAll () {
|
||||
if (isFetching.value) return
|
||||
isFetching.value = true
|
||||
loading.value = true
|
||||
|
||||
try {
|
||||
const [{ data: p, error: ep }, { data: s, error: es }] = await Promise.all([
|
||||
supabase.from('plans').select('*').order('key', { ascending: true }),
|
||||
supabase.from('subscriptions').select('*').order('updated_at', { ascending: false })
|
||||
supabase
|
||||
.from('plans')
|
||||
.select('id,key,target,is_active')
|
||||
.order('key', { ascending: true }),
|
||||
|
||||
supabase
|
||||
.from('subscriptions')
|
||||
.select('id,tenant_id,user_id,plan_id,status,interval,current_period_start,current_period_end,updated_at,created_at,plan_key')
|
||||
.order('updated_at', { ascending: false })
|
||||
])
|
||||
|
||||
if (ep) throw ep
|
||||
@@ -46,19 +135,84 @@ async function fetchAll () {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 5000 })
|
||||
} finally {
|
||||
loading.value = false
|
||||
isFetching.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function planKey (planId) {
|
||||
const p = plans.value.find(x => x.id === planId)
|
||||
return p?.key || '(sem plano)'
|
||||
// -------------------------
|
||||
// plans helpers
|
||||
// -------------------------
|
||||
function planById (planId) {
|
||||
return plans.value.find(x => String(x.id) === String(planId)) || null
|
||||
}
|
||||
|
||||
function planKeyById (planId) {
|
||||
return planById(planId)?.key || null
|
||||
}
|
||||
|
||||
function planLabelForRow (subRow) {
|
||||
return planKeyById(subRow?.plan_id) || subRow?.plan_key || '(sem plano)'
|
||||
}
|
||||
|
||||
function severityForPlan (key) {
|
||||
if (!key) return 'secondary'
|
||||
if (key === 'free') return 'secondary'
|
||||
if (key === 'pro') return 'success'
|
||||
return 'info'
|
||||
const k = String(key || '').toLowerCase()
|
||||
if (!k) return 'secondary'
|
||||
return k.includes('pro') ? 'success' : 'info'
|
||||
}
|
||||
|
||||
function plansForSub (subRow) {
|
||||
const t = subscriptionType(subRow)
|
||||
if (t !== 'clinic' && t !== 'therapist') return []
|
||||
|
||||
return (plans.value || []).filter(p => {
|
||||
if (p?.target && p.target !== t) return false
|
||||
if (p?.is_active === false) return false
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
function canChangePlan (subRow) {
|
||||
const t = subscriptionType(subRow)
|
||||
return t === 'clinic' || t === 'therapist'
|
||||
}
|
||||
|
||||
function canCancel (row) {
|
||||
const s = String(row?.status || '').toLowerCase()
|
||||
return s === 'active' || s === 'trialing' || s === 'past_due'
|
||||
}
|
||||
|
||||
// -------------------------
|
||||
// update plan (com confirmação)
|
||||
// -------------------------
|
||||
function confirmUpdatePlan (subRow, nextPlanId) {
|
||||
if (!nextPlanId) return
|
||||
if (String(nextPlanId) === String(subRow.plan_id)) return
|
||||
if (loading.value || savingId.value) return
|
||||
|
||||
const t = subscriptionType(subRow)
|
||||
const owner = ownerKey(subRow)
|
||||
const next = planById(nextPlanId)
|
||||
const prevKey = planLabelForRow(subRow)
|
||||
|
||||
if (!next) return
|
||||
|
||||
if (next.target && next.target !== t) {
|
||||
toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Plano incompatível',
|
||||
detail: `Essa assinatura é ${typeLabel(t)}. Selecione um plano ${typeLabel(t)}.`,
|
||||
life: 4200
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
confirm.require({
|
||||
header: 'Confirmar mudança de plano',
|
||||
message: `Trocar de "${prevKey}" para "${next.key}" em ${owner}?`,
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptClass: 'p-button-warning',
|
||||
accept: () => updatePlan(subRow, nextPlanId)
|
||||
})
|
||||
}
|
||||
|
||||
async function updatePlan (subRow, nextPlanId) {
|
||||
@@ -75,12 +229,9 @@ async function updatePlan (subRow, nextPlanId) {
|
||||
|
||||
if (data?.plan_id) subRow.plan_id = data.plan_id
|
||||
|
||||
toast.add({
|
||||
severity: 'success',
|
||||
summary: 'Ok',
|
||||
detail: 'Plano atualizado (transação + histórico).',
|
||||
life: 2500
|
||||
})
|
||||
toast.add({ severity: 'success', summary: 'Ok', detail: 'Plano atualizado.', life: 2500 })
|
||||
|
||||
await fetchAll()
|
||||
} catch (e) {
|
||||
subRow.plan_id = prev
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 5000 })
|
||||
@@ -89,7 +240,23 @@ async function updatePlan (subRow, nextPlanId) {
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelSubscription(row) {
|
||||
// -------------------------
|
||||
// cancel / reactivate (com confirmação)
|
||||
// -------------------------
|
||||
function confirmCancel (row) {
|
||||
if (!row?.id) return
|
||||
const owner = ownerKey(row)
|
||||
|
||||
confirm.require({
|
||||
header: 'Confirmar cancelamento',
|
||||
message: `Cancelar assinatura de ${owner}?`,
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptClass: 'p-button-danger',
|
||||
accept: () => cancelSubscription(row)
|
||||
})
|
||||
}
|
||||
|
||||
async function cancelSubscription (row) {
|
||||
savingId.value = row.id
|
||||
try {
|
||||
const { error } = await supabase.rpc('cancel_subscription', {
|
||||
@@ -100,13 +267,26 @@ async function cancelSubscription(row) {
|
||||
toast.add({ severity: 'success', summary: 'Cancelada', life: 2500 })
|
||||
await fetchAll()
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message })
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 5000 })
|
||||
} finally {
|
||||
savingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function reactivateSubscription(row) {
|
||||
function confirmReactivate (row) {
|
||||
if (!row?.id) return
|
||||
const owner = ownerKey(row)
|
||||
|
||||
confirm.require({
|
||||
header: 'Confirmar reativação',
|
||||
message: `Reativar assinatura de ${owner}?`,
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptClass: 'p-button-success',
|
||||
accept: () => reactivateSubscription(row)
|
||||
})
|
||||
}
|
||||
|
||||
async function reactivateSubscription (row) {
|
||||
savingId.value = row.id
|
||||
try {
|
||||
const { error } = await supabase.rpc('reactivate_subscription', {
|
||||
@@ -117,51 +297,201 @@ async function reactivateSubscription(row) {
|
||||
toast.add({ severity: 'success', summary: 'Reativada', life: 2500 })
|
||||
await fetchAll()
|
||||
} catch (e) {
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message })
|
||||
toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 5000 })
|
||||
} finally {
|
||||
savingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function goToSubscriptionsForOwner (ownerId) {
|
||||
if (!ownerId) return
|
||||
router.push({ path: '/saas/subscriptions', query: { q: ownerId } })
|
||||
// -------------------------
|
||||
// foco por query
|
||||
// -------------------------
|
||||
function matchesFocused (s, rawQ) {
|
||||
const parsed = parseOwnerKey(rawQ)
|
||||
if (parsed.kind === 'clinic') return String(s.tenant_id || '') === String(parsed.id || '')
|
||||
if (parsed.kind === 'therapist') return String(s.user_id || '') === String(parsed.id || '')
|
||||
|
||||
const hay = [
|
||||
ownerKey(s),
|
||||
s.tenant_id,
|
||||
s.user_id,
|
||||
s.status,
|
||||
s.interval,
|
||||
planLabelForRow(s)
|
||||
].map(x => String(x || '').toLowerCase())
|
||||
|
||||
return hay.some(x => x.includes(String(rawQ || '').toLowerCase()))
|
||||
}
|
||||
|
||||
function filteredSubs () {
|
||||
// -------------------------
|
||||
// filtro + busca
|
||||
// -------------------------
|
||||
const filteredSubs = computed(() => {
|
||||
const term = String(q.value || '').trim().toLowerCase()
|
||||
if (!term) return subs.value
|
||||
return subs.value.filter(s =>
|
||||
String(s.owner_id || '').toLowerCase().includes(term) ||
|
||||
String(s.status || '').toLowerCase().includes(term) ||
|
||||
String(planKey(s.plan_id)).toLowerCase().includes(term)
|
||||
)
|
||||
let list = subs.value || []
|
||||
|
||||
if (typeFilter.value !== 'all') {
|
||||
list = list.filter(s => subscriptionType(s) === typeFilter.value)
|
||||
}
|
||||
|
||||
const rawQ = String(route.query?.q || '').trim()
|
||||
if (rawQ) {
|
||||
list = list.filter(s => matchesFocused(s, rawQ))
|
||||
}
|
||||
|
||||
if (!term) return list
|
||||
|
||||
return list.filter(s => {
|
||||
const a = String(ownerKey(s) || '').toLowerCase()
|
||||
const b = String(s.status || '').toLowerCase()
|
||||
const c = String(planLabelForRow(s) || '').toLowerCase()
|
||||
const d = String(s.interval || '').toLowerCase()
|
||||
const e = String(s.tenant_id || '').toLowerCase()
|
||||
const f = String(s.user_id || '').toLowerCase()
|
||||
|
||||
return a.includes(term) || b.includes(term) || c.includes(term) || d.includes(term) || e.includes(term) || f.includes(term)
|
||||
})
|
||||
})
|
||||
|
||||
const totalCount = computed(() => (filteredSubs.value || []).length)
|
||||
const activeCount = computed(() => (filteredSubs.value || []).filter(x => String(x?.status || '').toLowerCase() === 'active').length)
|
||||
|
||||
function clearFocus () {
|
||||
router.push({ path: route.path, query: {} })
|
||||
}
|
||||
|
||||
// -------------------------
|
||||
// Hero sticky
|
||||
// -------------------------
|
||||
const heroRef = ref(null)
|
||||
const sentinelRef = ref(null)
|
||||
const heroStuck = ref(false)
|
||||
let heroObserver = null
|
||||
const mobileMenuRef = ref(null)
|
||||
|
||||
const heroMenuItems = computed(() => [
|
||||
{
|
||||
label: 'Recarregar',
|
||||
icon: 'pi pi-refresh',
|
||||
command: fetchAll,
|
||||
disabled: loading.value || savingId.value !== null
|
||||
},
|
||||
{ separator: true },
|
||||
{
|
||||
label: 'Filtros',
|
||||
items: typeOptions.map(o => ({
|
||||
label: o.label,
|
||||
icon: typeFilter.value === o.value ? 'pi pi-check' : 'pi pi-circle',
|
||||
command: () => { typeFilter.value = o.value }
|
||||
}))
|
||||
}
|
||||
])
|
||||
|
||||
onMounted(async () => {
|
||||
const initialQ = route.query?.q
|
||||
if (typeof initialQ === 'string' && initialQ.trim()) {
|
||||
q.value = initialQ.trim()
|
||||
|
||||
const parsed = parseOwnerKey(initialQ)
|
||||
if (parsed.kind === 'clinic') typeFilter.value = 'clinic'
|
||||
if (parsed.kind === 'therapist') typeFilter.value = 'therapist'
|
||||
}
|
||||
|
||||
await fetchAll()
|
||||
|
||||
if (sentinelRef.value) {
|
||||
heroObserver = new IntersectionObserver(
|
||||
([entry]) => { heroStuck.value = !entry.isIntersecting },
|
||||
{ rootMargin: `${document.querySelector('.l2-main') ? '0px' : '-56px'} 0px 0px 0px`, threshold: 0 }
|
||||
)
|
||||
heroObserver.observe(sentinelRef.value)
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
heroObserver?.disconnect()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Toast />
|
||||
<ConfirmDialog />
|
||||
|
||||
<div class="p-4">
|
||||
<!-- Info decorativa (scrolls away naturalmente) -->
|
||||
<div class="flex items-start gap-4 px-4 pb-3">
|
||||
<div class="subs-hero__icon-wrap">
|
||||
<i class="pi pi-credit-card subs-hero__icon" />
|
||||
</div>
|
||||
<div class="subs-hero__sub">
|
||||
Painel operacional do SaaS: revise plano, status e período (Clínica x Terapeuta) com segurança.
|
||||
<template v-if="!loading">
|
||||
<br />{{ totalCount }} registro(s) • {{ activeCount }} ativa(s)
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- sentinel -->
|
||||
<div ref="sentinelRef" style="height: 1px; pointer-events: none;" />
|
||||
|
||||
<!-- hero -->
|
||||
<div
|
||||
ref="heroRef"
|
||||
class="subs-hero"
|
||||
:class="{ 'subs-hero--stuck': heroStuck }"
|
||||
>
|
||||
<div class="subs-hero__blob subs-hero__blob--1" />
|
||||
<div class="subs-hero__blob subs-hero__blob--2" />
|
||||
|
||||
<div class="subs-hero__inner">
|
||||
<!-- Título -->
|
||||
<div class="subs-hero__info min-w-0">
|
||||
<div class="subs-hero__title">Assinaturas</div>
|
||||
</div>
|
||||
|
||||
<!-- Ações desktop (≥ 1200px) -->
|
||||
<div class="subs-hero__actions subs-hero__actions--desktop">
|
||||
<SelectButton
|
||||
v-model="typeFilter"
|
||||
:options="typeOptions"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
size="small"
|
||||
:disabled="loading || savingId !== null"
|
||||
/>
|
||||
<Button
|
||||
label="Recarregar"
|
||||
icon="pi pi-refresh"
|
||||
severity="secondary"
|
||||
outlined
|
||||
size="small"
|
||||
:loading="loading"
|
||||
:disabled="savingId !== null"
|
||||
@click="fetchAll"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Ações mobile (< 1200px) -->
|
||||
<div class="subs-hero__actions--mobile">
|
||||
<Button
|
||||
label="Ações"
|
||||
icon="pi pi-ellipsis-v"
|
||||
severity="warn"
|
||||
size="small"
|
||||
@click="(e) => mobileMenuRef.toggle(e)"
|
||||
/>
|
||||
<Menu ref="mobileMenuRef" :model="heroMenuItems" popup />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- content -->
|
||||
<div class="px-4 pb-4">
|
||||
<!-- Header foco -->
|
||||
<div v-if="isFocused" class="mb-3 p-3 surface-100 border-round">
|
||||
<div class="flex align-items-center justify-content-between">
|
||||
<div class="flex align-items-center justify-content-between gap-3 flex-wrap">
|
||||
<div>
|
||||
<div class="text-lg font-semibold">
|
||||
Subscription em foco
|
||||
</div>
|
||||
<small class="text-color-secondary">
|
||||
Owner: {{ route.query.q }}
|
||||
</small>
|
||||
<div class="text-lg font-semibold">Assinatura em foco</div>
|
||||
<small class="text-color-secondary">Filtro: {{ route.query.q }}</small>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
@@ -169,103 +499,217 @@ onMounted(async () => {
|
||||
icon="pi pi-times"
|
||||
severity="secondary"
|
||||
outlined
|
||||
@click="$router.push('/saas/subscriptions')"
|
||||
:disabled="loading || savingId !== null"
|
||||
@click="clearFocus"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Toolbar class="mb-4">
|
||||
<template #start>
|
||||
<div class="flex flex-col">
|
||||
<div class="text-xl font-semibold leading-none">Subscriptions</div>
|
||||
<small class="text-color-secondary mt-1">
|
||||
Painel operacional SaaS.
|
||||
</small>
|
||||
</div>
|
||||
</template>
|
||||
<!-- busca -->
|
||||
<div class="mb-4">
|
||||
<FloatLabel variant="on" class="w-full">
|
||||
<IconField class="w-full">
|
||||
<InputIcon class="pi pi-search" />
|
||||
<InputText
|
||||
v-model="q"
|
||||
id="subs_search"
|
||||
class="w-full pr-10"
|
||||
variant="filled"
|
||||
:disabled="loading"
|
||||
/>
|
||||
</IconField>
|
||||
<label for="subs_search">Buscar owner, status, intervalo, plano…</label>
|
||||
</FloatLabel>
|
||||
</div>
|
||||
|
||||
<template #end>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="p-input-icon-left">
|
||||
<i class="pi pi-search" />
|
||||
<InputText v-model="q" placeholder="Buscar por owner_id, status, plano..." />
|
||||
</span>
|
||||
<Button label="Recarregar" icon="pi pi-refresh" severity="secondary" outlined :loading="loading" @click="fetchAll" />
|
||||
</div>
|
||||
</template>
|
||||
</Toolbar>
|
||||
|
||||
<DataTable :value="filteredSubs()" dataKey="id" :loading="loading" stripedRows responsiveLayout="scroll">
|
||||
|
||||
<Column field="owner_id" header="Owner" style="min-width: 22rem" />
|
||||
|
||||
<Column header="Plano" style="min-width: 14rem">
|
||||
<DataTable
|
||||
:value="filteredSubs"
|
||||
dataKey="id"
|
||||
:loading="loading"
|
||||
stripedRows
|
||||
responsiveLayout="scroll"
|
||||
class="subs-table"
|
||||
:rowHover="true"
|
||||
paginator
|
||||
:rows="15"
|
||||
:rowsPerPageOptions="[10,15,25,50]"
|
||||
currentPageReportTemplate="{first}–{last} de {totalRecords}"
|
||||
paginatorTemplate="RowsPerPageDropdown FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport"
|
||||
>
|
||||
<Column header="Tipo" style="width: 10rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex items-center gap-2">
|
||||
<Tag :value="planKey(data.plan_id)" :severity="severityForPlan(planKey(data.plan_id))" />
|
||||
|
||||
<Select
|
||||
:modelValue="data.plan_id"
|
||||
:options="plans"
|
||||
optionLabel="key"
|
||||
optionValue="id"
|
||||
placeholder="Selecione..."
|
||||
class="w-14rem"
|
||||
:disabled="savingId === data.id"
|
||||
@update:modelValue="(val) => updatePlan(data, val)"
|
||||
/>
|
||||
</div>
|
||||
<Tag :value="typeLabel(subscriptionType(data))" :severity="typeSeverity(subscriptionType(data))" rounded />
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Período" style="min-width: 16rem">
|
||||
<Column header="Owner" style="min-width: 22rem">
|
||||
<template #body="{ data }">
|
||||
<div>
|
||||
<div>{{ data.current_period_start || '-' }}</div>
|
||||
<div class="flex flex-col">
|
||||
<span class="font-medium">{{ ownerKey(data) }}</span>
|
||||
<small class="text-color-secondary">
|
||||
até {{ data.current_period_end || '-' }}
|
||||
{{ data.tenant_id ? `tenant_id: ${data.tenant_id}` : `user_id: ${data.user_id || '—'}` }}
|
||||
</small>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column field="status" header="Status" style="width: 10rem" />
|
||||
|
||||
<Column field="updated_at" header="Atualizado" style="min-width: 14rem" />
|
||||
|
||||
<Column header="Ações" style="min-width: 14rem">
|
||||
<Column header="Plano" style="min-width: 18rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex gap-2 flex-wrap">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<Tag :value="planLabelForRow(data)" :severity="severityForPlan(planLabelForRow(data))" />
|
||||
|
||||
<Button
|
||||
icon="pi pi-history"
|
||||
severity="secondary"
|
||||
outlined
|
||||
@click="$router.push('/saas/subscription-events?q=' + data.owner_id)"
|
||||
/>
|
||||
|
||||
<Button
|
||||
v-if="data.status === 'active'"
|
||||
icon="pi pi-ban"
|
||||
severity="danger"
|
||||
outlined
|
||||
:loading="savingId === data.id"
|
||||
@click="cancelSubscription(data)"
|
||||
/>
|
||||
|
||||
<Button
|
||||
v-if="data.status !== 'active'"
|
||||
icon="pi pi-refresh"
|
||||
severity="success"
|
||||
outlined
|
||||
:loading="savingId === data.id"
|
||||
@click="reactivateSubscription(data)"
|
||||
<Dropdown
|
||||
v-if="canChangePlan(data)"
|
||||
:modelValue="data.plan_id"
|
||||
:options="plansForSub(data)"
|
||||
optionLabel="key"
|
||||
optionValue="id"
|
||||
placeholder="Selecione..."
|
||||
class="w-14rem"
|
||||
:disabled="savingId === data.id || loading"
|
||||
@update:modelValue="(val) => confirmUpdatePlan(data, val)"
|
||||
/>
|
||||
|
||||
<Tag v-else value="tipo inválido" severity="warning" />
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Intervalo" style="width: 10rem">
|
||||
<template #body="{ data }">
|
||||
<Tag :value="intervalLabel(data.interval)" severity="secondary" />
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Período" style="min-width: 18rem">
|
||||
<template #body="{ data }">
|
||||
<div>
|
||||
<div>{{ fmtDate(data.current_period_start) }}</div>
|
||||
<small class="text-color-secondary">
|
||||
até {{ fmtDate(data.current_period_end) }}
|
||||
</small>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Status" style="width: 10rem">
|
||||
<template #body="{ data }">
|
||||
<Tag :value="statusLabel(data.status)" :severity="statusSeverity(data.status)" />
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Atualizado" style="min-width: 14rem">
|
||||
<template #body="{ data }">
|
||||
{{ fmtDate(data.updated_at) }}
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<Column header="Ações" style="min-width: 14rem">
|
||||
<template #body="{ data }">
|
||||
<div class="flex gap-2 flex-wrap">
|
||||
<Button
|
||||
icon="pi pi-history"
|
||||
severity="secondary"
|
||||
outlined
|
||||
:disabled="loading || savingId !== null"
|
||||
v-tooltip.top="'Ver histórico'"
|
||||
@click="router.push('/saas/subscription-events?q=' + ownerKey(data))"
|
||||
/>
|
||||
|
||||
<Button
|
||||
v-if="canCancel(data)"
|
||||
icon="pi pi-ban"
|
||||
severity="danger"
|
||||
outlined
|
||||
v-tooltip.top="'Cancelar'"
|
||||
:loading="savingId === data.id"
|
||||
:disabled="loading || (savingId !== null && savingId !== data.id)"
|
||||
@click="confirmCancel(data)"
|
||||
/>
|
||||
|
||||
<Button
|
||||
v-else
|
||||
icon="pi pi-refresh"
|
||||
severity="success"
|
||||
outlined
|
||||
v-tooltip.top="'Reativar'"
|
||||
:loading="savingId === data.id"
|
||||
:disabled="loading || (savingId !== null && savingId !== data.id)"
|
||||
@click="confirmReactivate(data)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</Column>
|
||||
|
||||
<template #empty>
|
||||
<div class="p-4 text-color-secondary">
|
||||
Nenhuma assinatura encontrada com os filtros atuais.
|
||||
</div>
|
||||
</template>
|
||||
</DataTable>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.subs-table :deep(.p-paginator) {
|
||||
border-top: 1px solid var(--surface-border);
|
||||
}
|
||||
.subs-table :deep(.p-datatable-tbody > tr > td) {
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
/* Hero */
|
||||
.subs-hero {
|
||||
position: sticky;
|
||||
top: var(--layout-sticky-top, 56px);
|
||||
z-index: 20;
|
||||
overflow: hidden;
|
||||
border-radius: 1.75rem;
|
||||
border: 1px solid var(--surface-border);
|
||||
background: var(--surface-card);
|
||||
padding: 1.5rem;
|
||||
margin: 1rem;
|
||||
}
|
||||
.subs-hero--stuck {
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
}
|
||||
.subs-hero__blob {
|
||||
position: absolute; border-radius: 50%; filter: blur(70px);
|
||||
}
|
||||
.subs-hero__blob--1 { width: 20rem; height: 20rem; top: -5rem; right: -4rem; background: rgba(96,165,250,0.12); }
|
||||
.subs-hero__blob--2 { width: 18rem; height: 18rem; top: 1rem; left: -5rem; background: rgba(99,102,241,0.09); }
|
||||
|
||||
.subs-hero__inner {
|
||||
position: relative; z-index: 1;
|
||||
display: flex; align-items: center; gap: 1.25rem; flex-wrap: wrap;
|
||||
}
|
||||
.subs-hero__icon-wrap {
|
||||
flex-shrink: 0;
|
||||
width: 4rem; height: 4rem; border-radius: 1.125rem;
|
||||
border: 2px solid var(--surface-border);
|
||||
background: var(--surface-ground);
|
||||
display: grid; place-items: center;
|
||||
}
|
||||
.subs-hero__icon { font-size: 1.5rem; color: var(--text-color); }
|
||||
|
||||
.subs-hero__info { flex: 1; min-width: 0; }
|
||||
.subs-hero__title {
|
||||
font-size: 1.25rem; font-weight: 700; letter-spacing: -0.025em;
|
||||
color: var(--text-color); line-height: 1.2;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.subs-hero__sub {
|
||||
font-size: 0.78rem; color: var(--text-color-secondary); margin-top: 4px; line-height: 1.5;
|
||||
}
|
||||
|
||||
.subs-hero__actions--desktop {
|
||||
display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap;
|
||||
}
|
||||
.subs-hero__actions--mobile { display: none; }
|
||||
|
||||
@media (max-width: 1199px) {
|
||||
.subs-hero__actions--desktop { display: none; }
|
||||
.subs-hero__actions--mobile { display: flex; }
|
||||
}
|
||||
</style>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
40
src/views/pages/supervisor/SupervisaoSalaPage.vue
Normal file
40
src/views/pages/supervisor/SupervisaoSalaPage.vue
Normal file
@@ -0,0 +1,40 @@
|
||||
<script setup>
|
||||
// SupervisaoSalaPage.vue — Fase 1 placeholder
|
||||
// Fase 2: listar supervisionados, convidar, gerenciar sessões
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="p-6">
|
||||
<div class="max-w-2xl mx-auto text-center py-16">
|
||||
<div
|
||||
class="w-20 h-20 mx-auto mb-6 rounded-2xl border-2 border-dashed border-[var(--surface-border)]
|
||||
flex items-center justify-center"
|
||||
>
|
||||
<i class="pi pi-users text-4xl opacity-40" />
|
||||
</div>
|
||||
|
||||
<h1 class="text-2xl font-bold mb-2">Sala de Supervisão</h1>
|
||||
<p class="text-[var(--text-color-secondary)] mb-8 leading-relaxed">
|
||||
Aqui você gerenciará seus supervisionados, enviará convites e
|
||||
acompanhará o progresso de cada terapeuta.
|
||||
<br />
|
||||
<span class="opacity-60 text-sm">Em construção — disponível em breve.</span>
|
||||
</p>
|
||||
|
||||
<div class="flex flex-col sm:flex-row gap-3 justify-center">
|
||||
<Button
|
||||
label="Convidar terapeuta"
|
||||
icon="pi pi-user-plus"
|
||||
disabled
|
||||
/>
|
||||
<Button
|
||||
label="Ver supervisionados"
|
||||
icon="pi pi-list"
|
||||
severity="secondary"
|
||||
outlined
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
33
src/views/pages/supervisor/SupervisorDashboard.vue
Normal file
33
src/views/pages/supervisor/SupervisorDashboard.vue
Normal file
@@ -0,0 +1,33 @@
|
||||
<script setup>
|
||||
import StatsWidget from '@/components/dashboard/StatsWidget.vue';
|
||||
import NotificationsWidget from '@/components/dashboard/NotificationsWidget.vue';
|
||||
import RevenueStreamWidget from '@/components/dashboard/RevenueStreamWidget.vue';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="card mb-0">
|
||||
<div class="flex justify-between mb-4">
|
||||
<div>
|
||||
<span class="text-primary font-medium">Área</span>
|
||||
<span class="text-muted-color"> do Supervisor</span>
|
||||
</div>
|
||||
<div class="flex items-center justify-center bg-purple-100 dark:bg-purple-400/10 rounded-border" style="width: 2.5rem; height: 2.5rem">
|
||||
<i class="pi pi-eye text-purple-500 text-xl!"></i>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-muted-color text-sm mt-0">
|
||||
Supervisione sessões, evolução dos pacientes e indicadores da clínica.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-12 gap-8">
|
||||
<StatsWidget />
|
||||
|
||||
<div class="col-span-12 xl:col-span-6">
|
||||
<RevenueStreamWidget />
|
||||
</div>
|
||||
<div class="col-span-12 xl:col-span-6">
|
||||
<NotificationsWidget />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
Reference in New Issue
Block a user