Preficicação, Convenio, Ajustes Agenda, Configurações Excessões

This commit is contained in:
Leonardo
2026-03-13 16:03:08 -03:00
parent f4b185ae17
commit 06fb369beb
30 changed files with 24851 additions and 307 deletions

View File

@@ -1,70 +1,116 @@
<!-- src/layout/configuracoes/ConfiguracoesPrecificacaoPage.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import { ref, computed, onMounted } from 'vue'
import { supabase } from '@/lib/supabase/client'
import { useTenantStore } from '@/stores/tenantStore'
import { useToast } from 'primevue/usetoast'
import { useServices } from '@/features/agenda/composables/useServices'
const toast = useToast()
const tenantStore = useTenantStore()
const loading = ref(true)
const saving = ref(false)
const ownerId = ref(null)
const tenantId = ref(null)
const { services, loading, error: servicesError, load, save, remove } = useServices()
// ── Tipos de compromisso do tenant ─────────────────────────────────
const commitments = ref([]) // [{ id, label, native_key }]
const ownerId = ref(null)
const tenantId = ref(null)
const slotMode = ref('fixed')
const pageLoading = ref(true)
// ── Preços: Map<commitmentId | '__default__', { price, notes }> ────
// '__default__' = linha com determined_commitment_id IS NULL
const prices = ref({}) // { [key]: { price: number|null, notes: '' } }
const isDynamic = computed(() => slotMode.value === 'dynamic')
// ── Carregar commitments do tenant ─────────────────────────────────
async function loadCommitments () {
if (!tenantId.value) return
const { data, error } = await supabase
.from('determined_commitments')
.select('id, name, native_key, active')
.eq('tenant_id', tenantId.value)
.eq('active', true)
.order('name')
// ── Formulário novo serviço ──────────────────────────────────────────
const emptyForm = () => ({ name: '', description: '', price: null, duration_min: null })
if (error) throw error
const newForm = ref(emptyForm())
const addingNew = ref(false)
const savingNew = ref(false)
commitments.value = data || []
}
// ── Edição inline ────────────────────────────────────────────────────
const editingId = ref(null)
const editForm = ref({})
const savingEdit = ref(false)
// ── Carregar preços existentes ──────────────────────────────────────
async function loadPrices (uid) {
const { data, error } = await supabase
.from('professional_pricing')
.select('id, determined_commitment_id, price, notes')
.eq('owner_id', uid)
if (error) throw error
const map = {}
for (const row of (data || [])) {
const key = row.determined_commitment_id ?? '__default__'
map[key] = { price: row.price != null ? Number(row.price) : null, notes: row.notes ?? '' }
}
prices.value = map
}
// ── Garantir que todos os commitments + default têm entrada no mapa
function ensureDefaults () {
if (!prices.value['__default__']) {
prices.value['__default__'] = { price: null, notes: '' }
}
for (const c of commitments.value) {
if (!prices.value[c.id]) {
prices.value[c.id] = { price: null, notes: '' }
}
function startEdit (svc) {
editingId.value = svc.id
editForm.value = {
id: svc.id,
owner_id: ownerId.value,
tenant_id: tenantId.value,
name: svc.name,
description: svc.description ?? '',
price: svc.price != null ? Number(svc.price) : null,
duration_min: svc.duration_min ?? null,
}
}
// ── Mount ───────────────────────────────────────────────────────────
function cancelEdit () {
editingId.value = null
editForm.value = {}
}
async function saveEdit () {
if (!editForm.value.name?.trim() || editForm.value.price == null) {
toast.add({ severity: 'warn', summary: 'Campos obrigatórios', detail: 'Nome e preço são obrigatórios.', life: 3000 })
return
}
savingEdit.value = true
try {
await save({
...editForm.value,
name: editForm.value.name.trim(),
description: editForm.value.description?.trim() || null,
duration_min: isDynamic.value ? (editForm.value.duration_min ?? null) : null,
})
await load(ownerId.value)
cancelEdit()
toast.add({ severity: 'success', summary: 'Salvo', detail: 'Serviço atualizado.', life: 3000 })
} catch {
toast.add({ severity: 'error', summary: 'Erro', detail: servicesError.value || 'Falha ao salvar.', life: 4000 })
} finally {
savingEdit.value = false
}
}
async function saveNew () {
if (!newForm.value.name?.trim() || newForm.value.price == null) {
toast.add({ severity: 'warn', summary: 'Campos obrigatórios', detail: 'Nome e preço são obrigatórios.', life: 3000 })
return
}
savingNew.value = true
try {
await save({
owner_id: ownerId.value,
tenant_id: tenantId.value,
name: newForm.value.name.trim(),
description: newForm.value.description?.trim() || null,
price: newForm.value.price,
duration_min: isDynamic.value ? (newForm.value.duration_min ?? null) : null,
})
await load(ownerId.value)
newForm.value = emptyForm()
addingNew.value = false
toast.add({ severity: 'success', summary: 'Adicionado', detail: 'Serviço criado com sucesso.', life: 3000 })
} catch {
toast.add({ severity: 'error', summary: 'Erro', detail: servicesError.value || 'Falha ao criar.', life: 4000 })
} finally {
savingNew.value = false
}
}
async function confirmRemove (id) {
try {
await remove(id)
toast.add({ severity: 'success', summary: 'Removido', detail: 'Serviço removido.', life: 3000 })
} catch {
toast.add({ severity: 'error', summary: 'Erro', detail: servicesError.value || 'Falha ao remover.', life: 4000 })
}
}
function fmtBRL (v) {
if (v == null || v === '') return '—'
return Number(v).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })
}
onMounted(async () => {
try {
const uid = tenantStore.user?.id || (await supabase.auth.getUser()).data?.user?.id
@@ -73,78 +119,21 @@ onMounted(async () => {
ownerId.value = uid
tenantId.value = tenantStore.activeTenantId || null
await Promise.all([
loadCommitments(),
loadPrices(uid),
])
const { data: cfg } = await supabase
.from('agenda_configuracoes')
.select('slot_mode')
.eq('owner_id', uid)
.maybeSingle()
ensureDefaults()
slotMode.value = cfg?.slot_mode ?? 'fixed'
await load(uid)
} catch (e) {
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao carregar.', life: 4000 })
} finally {
loading.value = false
pageLoading.value = false
}
})
// ── Salvar todos os preços configurados ────────────────────────────
async function save () {
if (!ownerId.value) return
saving.value = true
try {
const uid = ownerId.value
const tid = tenantId.value
const rows = []
// Linha padrão (NULL commitment)
const def = prices.value['__default__']
if (def?.price != null && def.price !== '') {
rows.push({
owner_id: uid,
tenant_id: tid,
determined_commitment_id: null,
price: Number(def.price),
notes: def.notes?.trim() || null,
})
}
// Linhas por tipo de compromisso
for (const c of commitments.value) {
const entry = prices.value[c.id]
if (entry?.price != null && entry.price !== '') {
rows.push({
owner_id: uid,
tenant_id: tid,
determined_commitment_id: c.id,
price: Number(entry.price),
notes: entry.notes?.trim() || null,
})
}
}
if (!rows.length) {
toast.add({ severity: 'warn', summary: 'Aviso', detail: 'Nenhum preço configurado para salvar.', life: 3000 })
return
}
const { error } = await supabase
.from('professional_pricing')
.upsert(rows, { onConflict: 'owner_id,determined_commitment_id' })
if (error) throw error
toast.add({ severity: 'success', summary: 'Salvo', detail: 'Precificação atualizada!', life: 3000 })
} catch (e) {
toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao salvar.', life: 4000 })
} finally {
saving.value = false
}
}
function fmtBRL (v) {
if (v == null || v === '') return '—'
return Number(v).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })
}
</script>
<template>
@@ -152,7 +141,7 @@ function fmtBRL (v) {
<div class="flex flex-col gap-4">
<!-- Header card -->
<!-- Header -->
<Card>
<template #content>
<div class="flex items-center justify-between gap-3 flex-wrap">
@@ -161,140 +150,174 @@ function fmtBRL (v) {
<i class="pi pi-tag text-lg" />
</div>
<div>
<div class="text-900 font-semibold text-lg">Precificação</div>
<div class="text-600 text-sm">Defina o valor padrão da sessão e valores específicos por tipo de compromisso.</div>
<div class="text-900 font-semibold text-lg">Serviços e Precificação</div>
<div class="text-600 text-sm">
Gerencie os serviços que você oferece e seus respectivos preços.
</div>
</div>
</div>
<Button
label="Salvar preços"
icon="pi pi-check"
:loading="saving"
:disabled="loading"
@click="save"
label="Novo serviço"
icon="pi pi-plus"
:disabled="pageLoading || addingNew"
@click="addingNew = true; cancelEdit()"
/>
</div>
</template>
</Card>
<!-- Loading -->
<div v-if="loading" class="flex justify-center py-10">
<div v-if="pageLoading || loading" class="flex justify-center py-10">
<ProgressSpinner style="width:40px;height:40px" />
</div>
<template v-else>
<!-- Preço padrão -->
<Card>
<template #content>
<div class="flex flex-col gap-3">
<div class="flex items-center gap-2">
<i class="pi pi-star text-primary-500" />
<span class="font-semibold text-900">Preço padrão (fallback)</span>
</div>
<div class="text-600 text-sm">
Aplicado quando o tipo de compromisso da sessão não tem um preço específico cadastrado.
</div>
<Message v-if="isDynamic" severity="info" :closable="false">
<span class="text-sm">
Modo <b>dinâmico</b> ativo a duração da sessão é definida pelo serviço selecionado.
</span>
</Message>
<div class="grid grid-cols-12 gap-3 mt-1">
<div class="col-span-12 sm:col-span-5">
<!-- Formulário novo serviço -->
<Card v-if="addingNew">
<template #title>
<div class="flex items-center gap-2">
<i class="pi pi-plus-circle text-primary-500" />
<span>Novo serviço</span>
</div>
</template>
<template #content>
<div class="grid grid-cols-12 gap-3">
<div class="col-span-12 sm:col-span-4">
<FloatLabel variant="on">
<InputText v-model="newForm.name" inputId="new-name" class="w-full" />
<label for="new-name">Nome *</label>
</FloatLabel>
</div>
<div class="col-span-12 sm:col-span-3">
<FloatLabel variant="on">
<InputNumber
v-model="newForm.price"
inputId="new-price"
mode="currency"
currency="BRL"
locale="pt-BR"
:min="0"
:minFractionDigits="2"
fluid
/>
<label for="new-price">Preço (R$) *</label>
</FloatLabel>
</div>
<div v-if="isDynamic" class="col-span-12 sm:col-span-2">
<FloatLabel variant="on">
<InputNumber v-model="newForm.duration_min" inputId="new-duration" :min="1" :max="480" fluid />
<label for="new-duration">Duração (min)</label>
</FloatLabel>
</div>
<div class="col-span-12 sm:col-span-3">
<FloatLabel variant="on">
<InputText v-model="newForm.description" inputId="new-desc" class="w-full" />
<label for="new-desc">Descrição (opcional)</label>
</FloatLabel>
</div>
</div>
<div class="flex gap-2 justify-end mt-4">
<Button label="Cancelar" severity="secondary" outlined @click="addingNew = false; newForm = emptyForm()" />
<Button label="Salvar" icon="pi pi-check" :loading="savingNew" @click="saveNew" />
</div>
</template>
</Card>
<!-- Lista vazia -->
<Card v-if="!services.length && !addingNew">
<template #content>
<div class="text-center py-6 text-color-secondary">
<i class="pi pi-tag text-4xl opacity-30 mb-3 block" />
<div class="font-medium mb-1">Nenhum serviço cadastrado</div>
<div class="text-sm">Clique em "Novo serviço" para começar.</div>
</div>
</template>
</Card>
<!-- Lista de serviços -->
<Card v-for="svc in services" :key="svc.id">
<template #content>
<!-- Modo edição -->
<template v-if="editingId === svc.id">
<div class="grid grid-cols-12 gap-3">
<div class="col-span-12 sm:col-span-4">
<FloatLabel variant="on">
<InputText v-model="editForm.name" :inputId="`edit-name-${svc.id}`" class="w-full" />
<label :for="`edit-name-${svc.id}`">Nome *</label>
</FloatLabel>
</div>
<div class="col-span-12 sm:col-span-3">
<FloatLabel variant="on">
<InputNumber
v-model="prices['__default__'].price"
inputId="price-default"
v-model="editForm.price"
:inputId="`edit-price-${svc.id}`"
mode="currency"
currency="BRL"
locale="pt-BR"
:min="0"
:max="99999"
:minFractionDigits="2"
fluid
placeholder="R$ 0,00"
/>
<label for="price-default">Valor da sessão (R$)</label>
<label :for="`edit-price-${svc.id}`">Preço (R$) *</label>
</FloatLabel>
</div>
<div class="col-span-12 sm:col-span-7">
<div v-if="isDynamic" class="col-span-12 sm:col-span-2">
<FloatLabel variant="on">
<InputText
v-model="prices['__default__'].notes"
inputId="notes-default"
class="w-full"
placeholder="Ex: Particular, valor padrão"
/>
<label for="notes-default">Observação (opcional)</label>
<InputNumber v-model="editForm.duration_min" :inputId="`edit-dur-${svc.id}`" :min="1" :max="480" fluid />
<label :for="`edit-dur-${svc.id}`">Duração (min)</label>
</FloatLabel>
</div>
<div class="col-span-12 sm:col-span-3">
<FloatLabel variant="on">
<InputText v-model="editForm.description" :inputId="`edit-desc-${svc.id}`" class="w-full" />
<label :for="`edit-desc-${svc.id}`">Descrição (opcional)</label>
</FloatLabel>
</div>
</div>
</div>
</template>
</Card>
<div class="flex gap-2 justify-end mt-4">
<Button label="Cancelar" severity="secondary" outlined @click="cancelEdit" />
<Button label="Salvar" icon="pi pi-check" :loading="savingEdit" @click="saveEdit" />
</div>
</template>
<!-- Preços por tipo de compromisso -->
<Card v-if="commitments.length">
<template #title>
<div class="flex items-center gap-2">
<i class="pi pi-list" />
<span>Por tipo de compromisso</span>
</div>
</template>
<template #content>
<div class="text-600 text-sm mb-4">
Valores específicos sobrepõem o preço padrão quando o tipo de compromisso coincide.
</div>
<div class="flex flex-col gap-4">
<div
v-for="c in commitments"
:key="c.id"
class="commitment-row"
>
<div class="commitment-label">
<div class="font-medium text-900">{{ c.name }}</div>
<div v-if="prices[c.id]?.price != null" class="text-xs text-color-secondary mt-0.5">
{{ fmtBRL(prices[c.id]?.price) }}
<!-- Modo leitura -->
<template v-else>
<div class="flex items-center justify-between gap-3 flex-wrap">
<div class="flex items-center gap-3">
<div class="cfg-icon-box-sm">
<i class="pi pi-tag" />
</div>
<div>
<div class="font-semibold text-900">{{ svc.name }}</div>
<div class="text-sm text-color-secondary flex flex-wrap gap-x-3 gap-y-0.5 mt-0.5">
<span><b class="text-primary-500">{{ fmtBRL(svc.price) }}</b></span>
<span v-if="svc.duration_min">{{ svc.duration_min }}min</span>
<span v-if="svc.description" class="italic">{{ svc.description }}</span>
</div>
</div>
</div>
<div class="grid grid-cols-12 gap-3 flex-1">
<div class="col-span-12 sm:col-span-5">
<FloatLabel variant="on">
<InputNumber
v-model="prices[c.id].price"
:inputId="`price-${c.id}`"
mode="currency"
currency="BRL"
locale="pt-BR"
:min="0"
:max="99999"
:minFractionDigits="2"
fluid
placeholder="R$ 0,00"
/>
<label :for="`price-${c.id}`">Valor (R$)</label>
</FloatLabel>
</div>
<div class="col-span-12 sm:col-span-7">
<FloatLabel variant="on">
<InputText
v-model="prices[c.id].notes"
:id="`notes-${c.id}`"
class="w-full"
placeholder="Ex: Convênio, valor reduzido..."
/>
<label :for="`notes-${c.id}`">Observação (opcional)</label>
</FloatLabel>
</div>
<div class="flex items-center gap-2">
<Tag value="Ativo" severity="success" />
<Button icon="pi pi-pencil" severity="secondary" outlined size="small" v-tooltip.top="'Editar'" @click="startEdit(svc)" />
<Button icon="pi pi-trash" severity="danger" outlined size="small" v-tooltip.top="'Remover'" @click="confirmRemove(svc.id)" />
</div>
</div>
</div>
</template>
</template>
</Card>
<!-- Dica -->
<Message severity="info" :closable="false">
<span class="text-sm">
O preço configurado aqui é preenchido automaticamente ao criar uma sessão na agenda.
Você ainda pode ajustá-lo manualmente no diálogo de cada evento.
Os serviços cadastrados aqui aparecem para seleção ao criar ou editar um evento na agenda.
</span>
</Message>
@@ -314,19 +337,14 @@ function fmtBRL (v) {
flex-shrink: 0;
}
.commitment-row {
display: flex;
align-items: flex-start;
gap: 1rem;
padding: 0.75rem;
border-radius: 0.75rem;
border: 1px solid var(--surface-border);
background: var(--surface-ground);
}
.commitment-label {
min-width: 9rem;
.cfg-icon-box-sm {
display: grid;
place-items: center;
width: 2rem;
height: 2rem;
border-radius: 0.625rem;
background: color-mix(in srgb, var(--p-primary-500, #6366f1) 10%, transparent);
color: var(--p-primary-500, #6366f1);
flex-shrink: 0;
padding-top: 0.5rem;
}
</style>
</style>