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