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
+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>