feat: importar csv y auditar ediciones

This commit is contained in:
mono
2026-10-25 18:20:04 -05:00
parent 8e286d6fec
commit 01b5ee64cc
23 changed files with 483 additions and 19 deletions

View File

@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-25

View File

@@ -0,0 +1,41 @@
# Design
## Context
La app usa Vue Router, Vuetify y Dexie offline-first. El Layout actual sólo ofrece el drawer; las vistas no comparten contexto de ruta ni controles de historial. Productores, productos y ventas se guardan directamente desde las vistas y no existe una bitácora general de cambios.
## Goals / Non-Goals
**Goals:**
- Hacer evidente cómo volver a Inicio o a la vista anterior en cualquier tamaño de pantalla.
- Procesar CSV localmente, sin backend, con errores por fila y resumen de importación.
- Mantener registros originales y almacenar auditorías inmutables de las ediciones.
- Reutilizar diálogos y tablas Vuetify para editar sin perder el contexto.
**Non-Goals:**
- Control de usuarios, autenticación o sincronización remota.
- Edición destructiva sin confirmación.
- Interpretar formatos de hoja de cálculo distintos de CSV UTF-8/compatible con separador coma o punto y coma.
## Decisions
- **Navegación en Layout:** usar `router-link`, `router.back()` y `router.push('/')` en un encabezado compartido. Se elige un encabezado sobre botones duplicados en vistas para garantizar consistencia.
- **Importación CSV en servicio:** parsear encabezados con normalización Unicode NFD, validar cada fila y ejecutar una transacción Dexie. Se rechazan filas inválidas sin abortar las válidas y se entrega un resumen.
- **Auditoría append-only:** agregar una tabla `auditorias` con entidad, registro, operación, actor, motivo, fecha y snapshots JSON. Las ediciones actualizan el registro y agregan la auditoría en una misma transacción.
- **Ventas editables como corrección controlada:** conservar el id y registrar diferencias de líneas/inventario; exigir motivo y actor antes de persistir.
- **Compatibilidad de datos:** nueva versión Dexie agrega la tabla sin borrar datos existentes; exportación incluirá auditorías y podrá importar archivos previos sin auditorías como lista vacía.
## Risks / Trade-offs
- [CSV ambiguo] Separador o codificación inesperada puede producir columnas incorrectas -> detectar separador, normalizar BOM y mostrar errores por fila antes de confirmar.
- [Edición de ventas] Puede alterar stock y reportes históricos -> registrar snapshots y movimientos compensatorios en transacción.
- [Historial atrás] Puede salir de la app si no existe historial -> fallback explícito a Inicio.
- [Datos grandes] Auditar snapshots incrementa almacenamiento local -> aceptar el costo por trazabilidad de la POC y exportarlo junto con los datos.
## Migration Plan
1. Migrar Dexie agregando `auditorias`.
2. Mantener importación de exportaciones antiguas con auditorías vacías.
3. Validar navegación, importación y edición en web; después ejecutar build y APK.

View File

@@ -0,0 +1,35 @@
# Proposal
## Why
La aplicación permite abrir módulos, pero el usuario puede quedar atrapado en una vista porque no tiene una ruta visible de regreso, historial atrás ni migas de pan. Además, el catálogo inicial debe poder cargarse rápidamente desde una hoja CSV y los cambios a datos operativos deben conservar trazabilidad para proteger la confianza en los reportes.
## What Changes
- Añadir navegación global consistente con Inicio, Atrás, migas de pan y menú móvil/desktop.
- Cubrir con Playwright la navegación entre Inicio, Jornada, Inventario y regreso atrás.
- Importar inventario inicial desde CSV con columnas `Nombre de producto`, `Nombre Productor`, `precio unitario` y `cantidad`.
- Comparar nombres ignorando mayúsculas, tildes y espacios redundantes; crear productores y productos faltantes.
- Permitir editar productores, productos y ventas desde la UI.
- Registrar auditoría de cada edición con persona, fecha, motivo, valores anteriores y nuevos.
- Mejorar formularios, tablas, diálogos y mensajes usando Vuetify.
## Capabilities
### New Capabilities
- `navigation`: navegación global y orientación contextual en todas las vistas.
- `inventory-csv-import`: carga e importación validada de inventario inicial en CSV.
- `auditable-edits`: edición de productores, productos y ventas con trazabilidad.
### Modified Capabilities
- `toldo-poc`: amplía persistencia, inventario inicial y experiencia de uso sin conexión.
## Impact
- `apps/toldo-app`: Layout, router, vistas, diálogos, tablas y pruebas Playwright.
- `packages/core`: entidad de auditoría y reglas de normalización/validación.
- `packages/data`: tabla Dexie y migración de auditorías.
- `packages/services`: importador CSV y servicios de edición auditada.
- No requiere backend ni cambia el formato de exportación de forma incompatible.

View File

@@ -0,0 +1,31 @@
# Spec Delta
## Purpose
Garantiza que cambios posteriores al registro original de productores, productos y ventas sean explicables y aparezcan en la información exportada y reportada.
## ADDED Requirements
### Requirement: Editar registros operativos
The system SHALL allow editing producers, products, and sales from the application UI.
#### Scenario: Editar producto
- **WHEN** user edits a product and confirms with actor and reason
- **THEN** the product stores the new values
- **AND** the edit appears in the audit history
### Requirement: Auditoría obligatoria
The system SHALL require actor and non-empty reason for every edit and SHALL store before and after values with timestamp.
#### Scenario: Edición sin motivo
- **WHEN** user attempts to save an edit without actor or reason
- **THEN** the edit is not persisted
- **AND** an inline validation message identifies the missing data
### Requirement: Corrección de venta trazable
The system SHALL update inventory consistently when an existing sale is edited and SHALL preserve the original and corrected sale snapshots.
#### Scenario: Cambiar cantidad vendida
- **WHEN** user changes a sale line quantity with a valid audit reason
- **THEN** compensating inventory movement is recorded
- **AND** the audit entry identifies the original and new sale values

View File

@@ -0,0 +1,33 @@
# Spec Delta
## Purpose
Permite cargar rápidamente el inventario inicial desde archivos CSV locales, creando sólo las entidades que no existen y evitando duplicados por diferencias de formato en los nombres.
## ADDED Requirements
### Requirement: Importar inventario CSV
The system SHALL import CSV rows with product name, producer name, unit price, and optional quantity columns.
#### Scenario: Importación válida
- **GIVEN** a CSV with the required headers
- **WHEN** user previews and confirms the import
- **THEN** missing producers and products are created
- **AND** a positive quantity creates an initial inventory movement
- **AND** empty or zero quantity creates no movement
### Requirement: Comparación normalizada
The system SHALL match producer and product names ignoring case, accents, BOM, and redundant surrounding whitespace.
#### Scenario: Evitar duplicado
- **GIVEN** an existing producer `La Familia González`
- **WHEN** CSV contains ` la familia gonzalez `
- **THEN** the row uses the existing producer instead of creating a duplicate
### Requirement: Errores de importación
The system SHALL report invalid rows without persisting invalid records and SHALL show a summary of created, reused, skipped, and failed rows.
#### Scenario: Precio inválido
- **WHEN** a row has a non-numeric or negative price
- **THEN** that row is rejected with its line number and reason
- **AND** valid rows remain importable

View File

@@ -0,0 +1,28 @@
# Spec Delta
## Purpose
Permite que una persona siempre entienda dónde está y pueda volver a Inicio o al paso anterior sin depender del botón físico del dispositivo.
## ADDED Requirements
### Requirement: Navegación global visible
The system SHALL show a shared navigation context with a home action, back action, and breadcrumbs on every application view.
#### Scenario: Volver desde Jornada
- **WHEN** user navigates from Inicio to Jornada
- **THEN** the view shows the breadcrumb `Inicio > Jornada`
- **AND** selecting Inicio returns to the dashboard
- **AND** selecting Atrás returns to the previous route
#### Scenario: Fallback de Atrás
- **GIVEN** the user opened a deep link without router history
- **WHEN** user selects Atrás
- **THEN** the system navigates to Inicio instead of leaving the application
### Requirement: Navegación responsive
The system SHALL expose the same destinations through a visible desktop menu and an accessible mobile menu.
#### Scenario: Menú móvil
- **WHEN** viewport width is narrow
- **THEN** user can open the menu, choose Inventario, close it, and return to Inicio

View File

@@ -0,0 +1,26 @@
# Tasks
## 1. Navegación y orientación
- [x] 1.1 Añadir encabezado compartido con Inicio, Atrás, breadcrumbs y fallback seguro; verificar navegación manual en todas las rutas
- [x] 1.2 Mejorar menú desktop/móvil con destinos accesibles y estado activo; verificar con Playwright en viewport móvil
- [x] 1.3 Añadir pruebas Playwright para Inicio -> Jornada -> Inicio, Atrás, Inicio -> Inventario -> Atrás y menú móvil
## 2. Importación CSV
- [x] 2.1 Implementar normalización Unicode de nombres, detección de separador y validación de encabezados; cubrir con tests unitarios
- [x] 2.2 Implementar servicio transaccional de importación con resumen por fila y movimientos iniciales; cubrir cantidades vacías/0 y errores
- [x] 2.3 Añadir versión Dexie para auditorías y soportar importación/exportación compatible con datos existentes
- [x] 2.4 Incorporar flujo Vuetify de selección, previsualización, confirmación y resultado de CSV en Inventario
## 3. Edición auditable
- [x] 3.1 Crear entidad/repositorio/servicio de auditoría append-only y exigir actor/motivo; verificar snapshots
- [x] 3.2 Añadir edición de productores y productos con diálogos Vuetify y confirmación auditada
- [x] 3.3 Añadir edición de ventas con actualización compensatoria de inventario y auditoría
- [x] 3.4 Mostrar historial de cambios y exportarlo; cubrir edición sin motivo y edición válida con tests
## 4. Verificación y entrega
- [x] 4.1 Ejecutar tests unitarios, `vue-tsc` y Playwright; verificar navegación e importación en web
- [x] 4.2 Generar build web, sincronizar Capacitor y generar APK debug; verificar artefacto