Files
analiticaNucleo/nuxt4-app/app/pages/panorama.vue
josedario87 db1a12d100
All checks were successful
build-and-deploy / build-and-deploy (push) Successful in 46s
Refactor: simplificar indicadores de cambios pendientes
Cambios realizados:
- Alerta más compacta con variant 'soft' en lugar de 'solid'
- Eliminado botón 'Actualizar ahora' redundante de la alerta
- Eliminado emoji de advertencia del botón 'Actualizar'
- Simplificado borde del card (solo borde amarillo sutil)
- Eliminadas sombras y rings del card
- Eliminada animación pulse del botón
- Mantenido punto amarillo pulsante en la alerta

El indicador ahora es más discreto pero sigue siendo evidente.
2025-10-29 17:18:47 -06:00

383 lines
14 KiB
Vue

<template>
<div class="flex flex-col gap-8">
<!-- Loading State -->
<UCard v-if="loading && !data" class="brand-card border border-transparent">
<div class="flex flex-col items-center justify-center gap-4 py-10 text-[var(--brand-text-muted)]">
<div class="flex items-center gap-3">
<span class="inline-flex h-8 w-8 animate-spin rounded-full border-2 border-[#c08040] border-t-transparent align-middle" aria-hidden="true" />
<span class="text-sm uppercase tracking-[0.3em]">Cargando datos...</span>
</div>
</div>
</UCard>
<!-- Error State -->
<div v-else-if="error" class="rounded-lg border border-red-500/40 bg-red-500/18 p-4 text-sm text-red-200">
<p>Error al cargar datos: {{ error }}</p>
<UButton class="mt-4" :loading="loading" :disabled="loading" @click="loadData" color="primary">
Reintentar
</UButton>
</div>
<!-- Initial State - No data loaded yet -->
<template v-else-if="!data && !loading">
<!-- Card de Filtros -->
<UCard class="brand-card border border-transparent">
<template #header>
<div class="flex flex-col gap-3">
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<h2 class="text-xl font-bold brand-section-title">Filtros y Configuraciones</h2>
<p class="text-xs text-[var(--brand-text-muted)] mt-1">
Aplicados a <code>created_at</code> de ingresos y rechazos
</p>
</div>
<div class="flex items-center gap-2">
<UCheckbox v-model="includeAnulados" label="Incluir anulados" @update:model-value="onToggleAnulados" />
</div>
</div>
<!-- Alerta roja cuando incluye anulados -->
<UAlert
v-if="includeAnulados"
color="error"
variant="solid"
icon="i-lucide-alert-triangle"
title="Incluir anulados activado"
description="Los cálculos incluyen registros anulados. Esto puede afectar los resultados financieros."
/>
</div>
</template>
<DateRangeSelector
:selected-preset="selectedPreset"
:fecha-desde="fechaDesde"
:fecha-hasta="fechaHasta"
@update:selected-preset="onUpdatePreset"
@update:fecha-desde="onUpdateFechaDesde"
@update:fecha-hasta="onUpdateFechaHasta"
/>
<template #footer>
<div class="flex flex-col sm:flex-row items-center justify-between gap-3">
<div class="text-xs text-[var(--brand-text-muted)]">
Rango activo: {{ rangoLegible }}
</div>
<UButton
:loading="loading"
:disabled="loading"
:ui="{ base: 'bg-[#c08040] text-[#1b1209] border border-[#d99a56] hover:bg-[#d99a56] hover:border-[#f0c07c] disabled:opacity-50 disabled:cursor-not-allowed' }"
size="sm"
@click="loadData"
>
<template #leading>
<UIcon name="i-lucide-refresh-cw" :class="{ 'animate-spin': loading }" />
</template>
Actualizar
</UButton>
</div>
</template>
</UCard>
<!-- Mensaje de bienvenida -->
<UCard class="brand-card border border-transparent">
<div class="flex flex-col items-center justify-center gap-4 py-16 text-center">
<div class="rounded-full bg-[#c08040]/10 p-6">
<UIcon name="i-lucide-bar-chart-3" class="w-12 h-12 text-[#c08040]" />
</div>
<div class="flex flex-col gap-2">
<h3 class="text-lg font-semibold text-[var(--brand-text)]">
Panorama Facturador
</h3>
<p class="text-sm text-[var(--brand-text-muted)] max-w-md">
Configura los filtros y haz clic en el botón "Actualizar" para cargar los datos financieros
</p>
</div>
</div>
</UCard>
</template>
<!-- Main Content -->
<template v-else-if="data">
<!-- Card de Filtros -->
<UCard
:class="[
'brand-card border transition-all duration-300',
hasPendingChanges
? 'border-yellow-500/60'
: 'border-transparent'
]"
>
<template #header>
<div class="flex flex-col gap-3">
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<h2 class="text-xl font-bold brand-section-title">Filtros y Configuraciones</h2>
<p class="text-xs text-[var(--brand-text-muted)] mt-1">
Aplicados a <code>created_at</code> de ingresos y rechazos
</p>
</div>
<div class="flex items-center gap-2">
<UCheckbox v-model="includeAnulados" label="Incluir anulados" @update:model-value="onToggleAnulados" />
</div>
</div>
<!-- Alerta de cambios pendientes -->
<UAlert
v-if="hasPendingChanges"
color="warning"
variant="soft"
class="py-2"
>
<template #title>
<div class="flex items-center justify-between gap-3 text-sm">
<div class="flex items-center gap-2">
<span class="inline-flex h-2 w-2 rounded-full bg-yellow-500 animate-pulse"></span>
<span class="font-medium">Cambios pendientes - Haz clic en "Actualizar" para aplicar</span>
</div>
</div>
</template>
</UAlert>
<!-- Alerta roja cuando incluye anulados -->
<UAlert
v-if="includeAnulados"
color="error"
variant="solid"
icon="i-lucide-alert-triangle"
title="Incluir anulados activado"
description="Los cálculos incluyen registros anulados. Esto puede afectar los resultados financieros."
/>
</div>
</template>
<DateRangeSelector
:selected-preset="selectedPreset"
:fecha-desde="fechaDesde"
:fecha-hasta="fechaHasta"
@update:selected-preset="onUpdatePreset"
@update:fecha-desde="onUpdateFechaDesde"
@update:fecha-hasta="onUpdateFechaHasta"
/>
<template #footer>
<div class="flex flex-col sm:flex-row items-center justify-between gap-3">
<div class="text-xs text-[var(--brand-text-muted)]">
Rango activo: {{ rangoLegible }} · Registros considerados: Ingresos {{ data.conteos.ingresos_filtrados }}/{{ data.conteos.ingresos_total }} · Rechazos {{ data.conteos.rechazos_filtrados }}/{{ data.conteos.rechazos_total }}
</div>
<UButton
:loading="loading"
:disabled="loading"
:ui="{
base: hasPendingChanges
? 'bg-yellow-500 text-black border border-yellow-600 hover:bg-yellow-400 hover:border-yellow-500 disabled:opacity-50 disabled:cursor-not-allowed'
: 'bg-[#c08040] text-[#1b1209] border border-[#d99a56] hover:bg-[#d99a56] hover:border-[#f0c07c] disabled:opacity-50 disabled:cursor-not-allowed'
}"
size="sm"
@click="loadData"
>
<template #leading>
<UIcon name="i-lucide-refresh-cw" :class="{ 'animate-spin': loading }" />
</template>
Actualizar
</UButton>
</div>
</template>
</UCard>
<!-- Totales Financieros - Resumen Principal -->
<UCard class="brand-card border border-transparent">
<template #header>
<div>
<h2 class="text-2xl font-bold brand-section-title">Totales Financieros</h2>
<p class="text-sm text-[var(--brand-text-muted)] mt-1">Vista general de ingresos, inversiones y rechazos</p>
</div>
</template>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div class="rounded-lg border border-[#3a2a16] bg-[#1c140c] px-6 py-4">
<div class="text-xs text-[var(--brand-text-muted)] uppercase tracking-wide mb-1">Total Invertido en Café</div>
<div class="text-3xl font-bold text-[var(--brand-primary)]">
{{ formatCurrency(data.financieros.total_invertido_cafe) }}
</div>
</div>
<div class="rounded-lg border border-[#3a2a16] bg-[#1c140c] px-6 py-4">
<div class="text-xs text-[var(--brand-text-muted)] uppercase tracking-wide mb-1">Total Rechazos</div>
<div class="text-3xl font-bold text-green-400">
{{ formatCurrency(data.financieros.total_rechazos) }}
</div>
</div>
<div class="rounded-lg border border-[#3a2a16] bg-[#1c140c] px-6 py-4">
<div class="text-xs text-[var(--brand-text-muted)] uppercase tracking-wide mb-1">Balance Neto</div>
<div class="text-3xl font-bold text-[var(--brand-text)]">
{{ formatCurrency(data.financieros.balance_neto) }}
</div>
</div>
</div>
<template #footer>
<div class="text-xs text-[var(--brand-text-muted)]">
Última actualización: {{ lastUpdated }}
</div>
</template>
</UCard>
<!-- Secciones de Ingresos -->
<SecosVendidos :data="data.secosVendidos" />
<TotalesIngresoCompra :data="data.ingresoCompra" />
<TotalesMonetarios :data="data.monetarios" />
<TotalesVerde :data="data.verde" />
<!-- Sección de Rechazos -->
<RechazosSubproductos :data="data.rechazos" />
</template>
</div>
</template>
<script setup lang="ts">
// Define page metadata
definePageMeta({
layout: 'informe',
title: 'Panorama Facturador'
})
// Reactive state
const data = ref<any>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const lastUpdated = ref<string>('')
// Filtros
const includeAnulados = ref(false)
type PresetValue =
| '' | 'custom' | 'hoy' | 'semana' | 'mes' | 'ytd'
| 'cosecha-20-21' | 'cosecha-21-22' | 'cosecha-22-23'
| 'cosecha-23-24' | 'cosecha-24-25' | 'cosecha-25-26'
const selectedPreset = ref<PresetValue>('cosecha-25-26')
const fechaDesde = ref<string | null>(null)
const fechaHasta = ref<string | null>(null)
// Filtros aplicados (los que se usaron en la última carga de datos)
const appliedFilters = ref<{
fechaDesde: string | null
fechaHasta: string | null
includeAnulados: boolean
} | null>(null)
// Computed
const rangoLegible = computed(() => {
if (!fechaDesde.value && !fechaHasta.value) return 'Sin filtro de fecha'
const f = fechaDesde.value ?? '—'
const t = fechaHasta.value ?? '—'
return `${f}${t}`
})
// Detectar si hay cambios pendientes sin aplicar
const hasPendingChanges = computed(() => {
// Si no hay datos cargados, no hay cambios pendientes
if (!appliedFilters.value) return false
// Comparar filtros actuales con los aplicados
return (
fechaDesde.value !== appliedFilters.value.fechaDesde ||
fechaHasta.value !== appliedFilters.value.fechaHasta ||
includeAnulados.value !== appliedFilters.value.includeAnulados
)
})
// Format currency helper
const formatCurrency = (value: number) => {
if (!value) return 'L 0.00'
return new Intl.NumberFormat('es-HN', {
style: 'currency',
currency: 'HNL',
minimumFractionDigits: 2,
maximumFractionDigits: 2
}).format(value).replace('HNL', 'L')
}
// Methods
async function loadData() {
// Prevenir múltiples peticiones simultáneas
if (loading.value) {
console.warn('Ya hay una petición en proceso, ignorando nueva solicitud')
return
}
loading.value = true
error.value = null
try {
const result = await $fetch('/api/metabase/panorama', {
method: 'POST',
body: {
fecha_desde: fechaDesde.value,
fecha_hasta: fechaHasta.value,
incluir_anulados: includeAnulados.value
}
})
data.value = result
lastUpdated.value = new Date().toLocaleString('es-ES', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
})
// Guardar los filtros aplicados
appliedFilters.value = {
fechaDesde: fechaDesde.value,
fechaHasta: fechaHasta.value,
includeAnulados: includeAnulados.value
}
} catch (err: any) {
error.value = err.message || 'Error al cargar datos'
console.error('Error loading panorama data:', err)
} finally {
loading.value = false
}
}
async function onToggleAnulados(newValue: boolean | 'indeterminate') {
if (newValue === true) {
// Pedir confirmación al activar
const confirmed = confirm(
'⚠️ ADVERTENCIA\n\n' +
'Está a punto de incluir registros ANULADOS en los cálculos.\n\n' +
'Esto puede afectar significativamente los resultados financieros y métricas.\n\n' +
'¿Está seguro de que desea continuar?'
)
if (!confirmed) {
// Si cancela, revertir el cambio
includeAnulados.value = false
return
}
}
// NO recargar automáticamente - el usuario debe hacer clic en "Actualizar"
}
function onUpdatePreset(value: PresetValue) {
selectedPreset.value = value
}
function onUpdateFechaDesde(value: string | null) {
fechaDesde.value = value
}
function onUpdateFechaHasta(value: string | null) {
fechaHasta.value = value
}
// Inicializar preset por defecto sin cargar datos
onMounted(() => {
// Default preset: cosecha 25-26
selectedPreset.value = 'cosecha-25-26'
// NO cargar datos automáticamente - el usuario debe hacer clic en "Actualizar"
})
</script>