This commit is contained in:
Leonardo
2026-03-06 06:37:13 -03:00
parent d58dc21297
commit f733db8436
146 changed files with 43436 additions and 12779 deletions
+638 -96
View File
@@ -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 existir anual, MRR = anual/12; se 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>
+385 -172
View File
@@ -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, é 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
View 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>
+454 -114
View File
@@ -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 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: 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>
+563 -119
View File
@@ -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