Files
ToldoConjunto/apps/toldo-app/src/views/Inventario.vue
2026-10-25 18:40:00 -05:00

170 lines
11 KiB
Vue

<template>
<div>
<h1 class="text-h4 mb-4">Inventario y Productos</h1>
<v-alert v-if="mensaje" :type="tipoMensaje" variant="tonal" class="mb-4">{{ mensaje }}</v-alert>
<v-card class="mb-4" variant="tonal" color="info">
<v-card-title><v-icon icon="mdi-file-delimited" class="mr-2" />Importar inventario inicial</v-card-title>
<v-card-text><div class="text-body-2 mb-3">CSV con: Nombre de producto, Nombre Productor, precio unitario y cantidad.</div><v-file-input v-model="csvFile" accept=".csv,text/csv" label="Seleccionar CSV" density="compact" prepend-icon="mdi-paperclip" @update:model-value="previsualizarCsv" /><v-alert v-if="previewRows.length" variant="outlined" density="compact" class="mb-3"><div class="text-caption font-weight-bold mb-1">Previsualización</div><div v-for="(row, index) in previewRows" :key="index" class="text-caption text-truncate">{{ row }}</div></v-alert><v-btn :disabled="!csvFile || !previewRows.length" color="info" @click="importarCsv" prepend-icon="mdi-upload">Confirmar importación</v-btn></v-card-text>
</v-card>
<v-row>
<v-col cols="12" md="6">
<v-card class="mb-4">
<v-card-title>Productores</v-card-title>
<v-card-text>
<v-row>
<v-col cols="8">
<v-text-field v-model="nuevoProductor" label="Nombre del productor" density="compact"></v-text-field>
</v-col>
<v-col cols="4">
<v-btn @click="crearProductor" color="primary" block>Agregar</v-btn>
</v-col>
</v-row>
<v-text-field v-model="busquedaProductores" label="Buscar productor" prepend-inner-icon="mdi-magnify" clearable density="compact" />
<v-list>
<v-list-item v-for="p in productoresFiltrados" :key="p.id" :title="p.nombre"><template #append><v-btn icon="mdi-pencil-outline" color="primary" variant="tonal" size="small" :aria-label="`Editar ${p.nombre}`" @click="editarProductor(p)" /></template></v-list-item>
</v-list>
</v-card-text>
</v-card>
</v-col>
<v-col cols="12" md="6">
<v-card class="mb-4">
<v-card-title>Productos</v-card-title>
<v-card-text>
<v-select v-model="productorSel" :items="productores" item-title="nombre" item-value="id" label="Productor" density="compact" class="mb-2"></v-select>
<v-text-field v-model="nombreProd" label="Nombre/Presentación (ej: Café molido 250gr)" density="compact" class="mb-2"></v-text-field>
<v-text-field v-model.number="precioProd" label="Precio unitario" type="number" density="compact" class="mb-2"></v-text-field>
<v-btn @click="crearProducto" color="primary" block>Agregar Producto</v-btn>
<v-text-field v-model="busquedaProductos" label="Buscar producto" prepend-inner-icon="mdi-magnify" clearable density="compact" class="mt-3" />
<v-list class="mt-3">
<v-list-item v-for="prod in productosFiltrados" :key="prod.id" :title="prod.nombrePresentacion" :subtitle="'$' + prod.precioUnitario"><template #append><v-btn icon="mdi-pencil-outline" color="primary" variant="tonal" size="small" :aria-label="`Editar ${prod.nombrePresentacion}`" @click="editarProducto(prod)" /></template></v-list-item>
</v-list>
</v-card-text>
</v-card>
</v-col>
</v-row>
<v-row>
<v-col cols="12" md="6">
<v-card>
<v-card-title>Ingreso Inicial del Día</v-card-title>
<v-card-text>
<v-select v-model="prodInv" :items="productos" item-title="nombrePresentacion" item-value="id" label="Producto" density="compact" class="mb-2"></v-select>
<v-text-field v-model.number="cantInv" label="Cantidad" type="number" density="compact" class="mb-2"></v-text-field>
<v-btn @click="ingresoInicial" color="success" block>Registrar Ingreso Inicial</v-btn>
</v-card-text>
</v-card>
</v-col>
<v-col cols="12" md="6">
<v-card>
<v-card-title>Ingreso entre Semana</v-card-title>
<v-card-text>
<v-select v-model="prodInv2" :items="productos" item-title="nombrePresentacion" item-value="id" label="Producto" density="compact" class="mb-2"></v-select>
<v-text-field v-model.number="cantInv2" label="Cantidad" type="number" density="compact" class="mb-2"></v-text-field>
<v-text-field v-model="recibidoPor" label="Recibido por" density="compact" class="mb-2"></v-text-field>
<v-btn @click="ingresoSemana" color="info" block>Registrar Ingreso</v-btn>
</v-card-text>
</v-card>
</v-col>
</v-row>
<v-dialog v-model="dialogoEdicion" max-width="520"><v-card><v-card-title>Editar {{ entidadEdicion === 'PRODUCTOR' ? 'productor' : 'producto' }}</v-card-title><v-card-text><v-text-field v-if="entidadEdicion === 'PRODUCTOR'" v-model="edicionProductor.nombre" label="Nombre" /><template v-else><v-text-field v-model="edicionProducto.nombrePresentacion" label="Nombre / presentación" /><v-text-field v-model.number="edicionProducto.precioUnitario" type="number" label="Precio unitario" /></template><v-divider class="my-3" /><v-text-field v-model="actor" label="Quién realiza el cambio" /><v-textarea v-model="motivo" label="Motivo del cambio" rows="2" /></v-card-text><v-card-actions><v-spacer /><v-btn variant="text" @click="dialogoEdicion = false">Cancelar</v-btn><v-btn color="primary" @click="guardarEdicion">Guardar cambio</v-btn></v-card-actions></v-card></v-dialog>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { db } from '@toldo/data';
import { InventarioService, ImportInventarioCsvService, EdicionService } from '@toldo/services';
const invService = new InventarioService();
const productores = ref<any[]>([]);
const productos = ref<any[]>([]);
const nuevoProductor = ref('');
const productorSel = ref('');
const nombreProd = ref('');
const precioProd = ref(0);
const prodInv = ref('');
const cantInv = ref(0);
const prodInv2 = ref('');
const cantInv2 = ref(0);
const recibidoPor = ref('');
const mensaje = ref('');
const tipoMensaje = ref<'success' | 'error'>('success');
const csvFile = ref<File | File[] | null>(null);
const previewRows = ref<string[]>([]);
const csvService = new ImportInventarioCsvService();
const edicionService = new EdicionService();
const dialogoEdicion = ref(false);
const entidadEdicion = ref<'PRODUCTOR' | 'PRODUCTO'>('PRODUCTOR');
const edicionProductor = ref<any>({});
const edicionProducto = ref<any>({});
const originalEdicion = ref<any>({});
const actor = ref('');
const motivo = ref('');
const busquedaProductores = ref('');
const busquedaProductos = ref('');
const productoresFiltrados = computed(() => productores.value.filter((productor) => !busquedaProductores.value.trim() || productor.nombre.toLocaleLowerCase().includes(busquedaProductores.value.trim().toLocaleLowerCase())));
const productosFiltrados = computed(() => productos.value.filter((producto) => !busquedaProductos.value.trim() || producto.nombrePresentacion.toLocaleLowerCase().includes(busquedaProductos.value.trim().toLocaleLowerCase())));
function avisar(texto: string, tipo: 'success' | 'error' = 'error') { mensaje.value = texto; tipoMensaje.value = tipo; }
function editarProductor(productor: any) { entidadEdicion.value = 'PRODUCTOR'; originalEdicion.value = { ...productor }; edicionProductor.value = { ...productor }; actor.value = ''; motivo.value = ''; dialogoEdicion.value = true; }
function editarProducto(producto: any) { entidadEdicion.value = 'PRODUCTO'; originalEdicion.value = { ...producto }; edicionProducto.value = { ...producto }; actor.value = ''; motivo.value = ''; dialogoEdicion.value = true; }
async function guardarEdicion() {
try {
if (entidadEdicion.value === 'PRODUCTOR') await edicionService.editarProductor(edicionProductor.value, originalEdicion.value, { modificadoPor: actor.value, motivo: motivo.value });
else await edicionService.editarProducto(edicionProducto.value, originalEdicion.value, { modificadoPor: actor.value, motivo: motivo.value });
dialogoEdicion.value = false; await cargar(); avisar('Cambio guardado y auditado.', 'success');
} catch (error: any) { avisar(error.message); }
}
async function importarCsv() {
const archivo = Array.isArray(csvFile.value) ? csvFile.value[0] : csvFile.value;
if (!archivo) return;
try { const resultado = await csvService.importar(await archivo.text()); csvFile.value = null; await cargar(); avisar(`Importación finalizada: ${resultado.creados} creados, ${resultado.movimientos} movimientos, ${resultado.errores.length} errores.`, resultado.errores.length ? 'error' : 'success'); }
catch (error: any) { avisar(error.message); }
}
async function previsualizarCsv() {
const archivo = Array.isArray(csvFile.value) ? csvFile.value[0] : csvFile.value;
previewRows.value = archivo ? (await archivo.text()).split(/\r?\n/).filter((linea) => linea.trim()).slice(0, 6) : [];
}
async function cargar() {
productores.value = await db.productores.toArray();
productos.value = await db.productos.toArray();
}
async function crearProductor() {
if (!nuevoProductor.value.trim()) return avisar('Escribe el nombre del productor.');
await db.productores.add({ id: crypto.randomUUID(), nombre: nuevoProductor.value, activo: true, createdAt: new Date() } as any);
nuevoProductor.value = '';
await cargar();
avisar('Productor creado.', 'success');
}
async function crearProducto() {
if (!productorSel.value || !nombreProd.value.trim() || precioProd.value <= 0) return avisar('Selecciona productor, nombre y un precio mayor que cero.');
await db.productos.add({ id: crypto.randomUUID(), productorId: productorSel.value, nombrePresentacion: nombreProd.value, precioUnitario: Number(precioProd.value), activo: true, createdAt: new Date() } as any);
nombreProd.value = '';
precioProd.value = 0;
await cargar();
avisar('Producto creado.', 'success');
}
async function ingresoInicial() {
if (!prodInv.value || cantInv.value <= 0) return avisar('Selecciona un producto y una cantidad mayor que cero.');
await invService.registrarIngresoInicial(prodInv.value, Number(cantInv.value), new Date());
cantInv.value = 0;
avisar('Ingreso inicial registrado.', 'success');
}
async function ingresoSemana() {
if (!prodInv2.value || cantInv2.value <= 0 || !recibidoPor.value.trim()) return avisar('Completa producto, cantidad y persona que recibe.');
await invService.registrarIngresoSemana(prodInv2.value, Number(cantInv2.value), new Date(), recibidoPor.value);
cantInv2.value = 0;
recibidoPor.value = '';
avisar('Ingreso entre semana registrado.', 'success');
}
onMounted(cargar);
</script>