Files
Autoparts-DB/docs/FASES_IMPLEMENTADAS.md

210 lines
12 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Nexus POS — Resumen de Fases Implementadas
**Fecha:** 2026-04-28
**Versión DB:** v3.2
**Tests:** 73/73 pasando (pytest)
---
## FASE 1-2: Fundamentos (pre-existente)
- ✅ CFDI 4.0 con Facturapi
- ✅ VIN Decoder (NHTSA)
- ✅ Lookup por placas mexicanas
- ✅ Carrito unificado multi-bodega
- ✅ Cotizaciones digitales → WhatsApp
- ✅ Auth JWT + roles
## FASE 3: Multi-sucursal + Alertas + Garantías
### Migración: v2.2
| Feature | Archivos | Endpoints |
|---------|----------|-----------|
| **Multi-sucursal** | `inventory_engine.py`, `inventory_bp.py` | `GET /pos/api/inventory/stock-by-branch`, `POST /pos/api/inventory/transfers`, `POST /pos/api/inventory/sync-prices` |
| **Alertas de Reorden** | `reorder_engine.py` | `POST /pos/api/inventory/generate-alerts`, `GET /pos/api/inventory/reorder-alerts`, `PUT /pos/api/inventory/reorder-alerts/:id/acknowledge`, `PUT /pos/api/inventory/reorder-alerts/:id/resolve`, `GET /pos/api/inventory/reorder-suggest-po` |
| **Garantías / RMA** | `warranty_engine.py`, `warranty_bp.py` | `POST /pos/api/warranties`, `GET /pos/api/warranties`, `GET /pos/api/warranties/:id`, `GET /pos/api/customers/:id/warranties`, `POST /pos/api/warranty-claims`, `PUT /pos/api/warranty-claims/:id/resolve`, `PUT /pos/api/warranty-claims/:id/close` |
## FASE 4: Infraestructura + Escalabilidad
### Migraciones: v1.9, v2.0, v2.1, v2.3
| Feature | Archivos | Infra |
|---------|----------|-------|
| **Redis Cache** | `redis_stock_cache.py`, `inventory_engine.py` | Redis 8.0.2, TTL 300s, fallback a PostgreSQL |
| **Multi-moneda** | `currency.py`, `pos_engine.py`, `cfdi_builder.py` | MXN base, USD soporte, contabilidad siempre en MXN |
| **Proveedores + POs** | `supplier_engine.py`, `supplier_bp.py` | 11 endpoints: CRUD proveedores + workflow PO completo |
| **Meilisearch** | `meili_search.py`, `catalog_service.py`, `sync_meilisearch.py` | Docker, 1.5M+ partes indexadas, búsqueda 4ms |
| **Metabase KPIs** | `setup_metabase.py`, `docker-compose.metabase.yml` | Docker v0.53, dashboard auto-generado |
## FASE 5: CRM + Service Orders + Imágenes
### Migraciones: v2.4, v2.5, v2.6
| Feature | Archivos | Capacidades |
|---------|----------|-------------|
| **CRM Mejorado** | `crm_engine.py`, `crm_bp.py` | Activities timeline, tags de segmentación, loyalty program (bronze/silver/gold/platinum), analytics (LTV, churn risk, categorías favoritas) |
| **Imágenes de Partes** | `image_service.py`, `image_bp.py` | Upload multipart/URL, resize 1200px, thumbnail 300x300, WebP, bulk import |
| **Órdenes de Servicio** | `service_order_engine.py`, `service_order_bp.py` | Kanban: received→diagnosis→waiting_parts→repair→quality_check→ready→delivered, items (refacciones), labor (mano de obra), historial de status |
| **WhatsApp** | `whatsapp_service.py`, `whatsapp_bp.py` | Webhook Baileys, AI chatbot, cotizaciones, voz, imágenes |
| **Flotillas** | `fleet_bp.py` | CRUD vehículos, maintenance schedules, logs, alerts, stats |
| **BNPL stub** | `bnpl_engine.py` | Arquitectura APLAZO/Kueski/Clip |
| **ERP Sync stub** | `erp_sync_engine.py` | Arquitectura Aspel/Contpaqi/SAP/Odoo |
## FASE 6: Notificaciones + Ahorro + Logística + API Pública
### Migraciones: v2.7, v2.8, v2.9, v3.0
| Feature | Archivos | Capacidades |
|---------|----------|-------------|
| **Notificaciones** | `notification_engine.py`, `notification_bp.py` | Templates por evento+canal, dispatch automático (push/WhatsApp/email/in-app), logs con estados, eventos: low_stock, order_ready, maintenance_due, new_sale, po_received, reorder_alert, warranty_expiring |
| **Reportes de Ahorro** | `savings_engine.py`, `savings_bp.py` | Campo `retail_price` en inventory, cálculo automático en checkout, reporte por cliente (LTV ahorro, desglose mensual), reporte global (top clientes, promedio por orden) |
| **Logística + Tracking** | `logistics_engine.py`, `logistics_bp.py` | 6 couriers pre-cargados (DHL, FedEx, Estafeta, 99min, Uber, Pickup), envíos vinculados a ventas/SO/PO, tracking URL auto-generada, historial de estatus |
| **API Pública** | `public_api_engine.py`, `public_api_bp.py` | API keys seguras (SHA-256), scopes (read/write/admin), rate limiting por minuto/día con headers, logging de requests, endpoints: `/api/v1/health`, `/api/v1/catalog/search`, `/api/v1/catalog/parts/:id` |
## FASE 7: Performance Optimización
### Migración: v3.2
| Sub-fase | Archivos | Optimizaciones |
|----------|----------|----------------|
| **7a — Quick Wins Frontend** | `nginx/nexus-pos.conf`, `pos/templates/*.html`, `pos/static/js/catalog.js` | gzip nginx, `defer` en scripts, fix `innerHTML +=` (8 lugares), event delegation cart, AbortController, sessionStorage cache years/brands |
| **7b — DB Performance** | `pos/tenant_db.py`, `pos/services/inventory_engine.py`, `pos/services/pos_engine.py`, `pos/migrations/v3.2_db_performance.sql` | Connection pooling (`psycopg2.pool`), tabla `inventory_stock_summary` + triggers O(1), fix N+1 `process_sale`, índices críticos |
| **7c — Redis + Gthread** | `pos/services/catalog_service.py`, `pos/gunicorn.conf.py` | `_classify_cache` en Redis (hit 6%→80%), vehicle info cache en `smart_search()`, gunicorn `gthread` (4 workers × 4 threads) |
| **7d — Lazy Load + Minify** | `pos/static/js/catalog.js`, `nginx/nexus-pos.conf`, `scripts/minify-assets.sh` | `loading="lazy"` en imágenes, minificación auto-serve vía nginx, cache warming script |
| **7e — CSS Inline Extraction** | `scripts/extract-inline-css.py`, 28 templates HTML, 28 archivos `.css`/`.min.css` | CSS inline extraído de 15 templates POS + 13 templates Dashboard a archivos externos, minificación, nginx auto-serve |
**Impacto acumulado FASE 7:**
- Transferencia: -4060%
- TTI: -200500ms
- Stock lookups: O(n) → O(1)
- Ventas 20 ítems: 21 queries → 1 query
- Cache hit rate: 6% → 80%+
## Opción C — Consolidación Técnica (COMPLETADA)
| Item | Estado | Commit |
|------|--------|--------|
| **C1: MV `part_vehicle_preview`** | ✅ En producción, refresh automático vía systemd timer (03:00 UTC) | `f893391` |
| **C2: Cache warming script** | ✅ Autónomo con auto-sudo fallback, args CLI | `f893391` |
| **C3: CSS dinámico residual** | ✅ `sidebar.js``sidebar.css`, `pos-utils.js``common.css` | `042acd6` |
| **C4: Load testing script** | ✅ `scripts/load_test.py` con `locust` | `042acd6` |
| **C5: Docs audit** | ✅ `FASES_IMPLEMENTADAS.md`, `performance_audit_2026.md` | `042acd6` |
## Opción A — Arquitectura Avanzada (COMPLETADA)
| Item | Estado | Commit |
|------|--------|--------|
| **A1: `orjson` como JSON provider** | ✅ Hereda `DefaultJSONProvider`, fix indent en `pos_bp.py` | `a1be8dd` |
| **A2: Virtual scroll** | ✅ `inventory.js`, `customers.js`, `fleet.js` | `a1be8dd` |
| **A3: Celery worker queue** | ✅ `celery_app.py`, `tasks.py`, `tasks_bp.py`, systemd service activo | `a1be8dd` |
| **A4: Quart + asyncpg PoC** | ✅ `async_catalog.py` en puerto 5002, benchmark script | `a1be8dd` |
| **A5: Particionamiento `vehicle_parts`** | ✅ Script `partition_vehicle_parts.py` listo (HASH 16 particiones, dry-run) | `a1be8dd` |
## IA por Voz — Chalán de Nexus (COMPLETADA)
| Componente | Estado |
|------------|--------|
| **STT (Speech-to-Text)** | ✅ POS + Dashboard público, `es-MX`, auto-send, animación micrófono |
| **TTS (Text-to-Speech)** | ✅ Botón 🔊 en burbujas de IA, `speechSynthesis`, preferencia guardada en `localStorage` |
| **Cobertura templates POS** | ✅ 14/14 templates tienen chat widget |
| **Dashboard público** | ✅ Chat público con voz completa (sin cámara) |
---
## Infraestructura Desplegada
| Servicio | Versión | Puerto | Estado |
|----------|---------|--------|--------|
| PostgreSQL | 17 | 5432 | ✅ Master + 2 tenants |
| Redis | 8.0.2 | 6379 | ✅ Stock cache + classify cache |
| Meilisearch | v1.12 | 7700 | ✅ 1,546,976 documentos |
| Metabase | v0.53 | 3000 | ✅ Dashboard ID 2 |
| Nginx | — | 80/443 | ✅ gzip, cache 6M, auto-serve .min |
| Gunicorn | — | 5001 | ✅ gthread, 4×4, max_requests=1000 |
| Celery | — | — | ✅ 4 prefork workers, broker redis://localhost:6379/1 |
| Quart PoC | — | 5002 | ✅ hypercorn manual, no en producción |
---
## Variables de Entorno Requeridas
```bash
# Base
MASTER_DB_URL=postgresql://user:pass@host/nexus_autoparts
TENANT_DB_URL_TEMPLATE=postgresql://user:pass@host/{db_name}
POS_JWT_SECRET=<32+ bytes hex>
# Redis
REDIS_URL=redis://localhost:6379/0
REDIS_ENABLED=true
REDIS_STOCK_TTL=300
# Meilisearch
MEILI_URL=http://localhost:7700
MEILI_API_KEY=nexus-master-key-change-me
MEILI_ENABLED=true
# Multi-moneda
DEFAULT_CURRENCY=MXN
EXCHANGE_RATE_USD_MXN=17.5
# WhatsApp (opcional)
WHATSAPP_BRIDGE_URL=http://localhost:21465
WHATSAPP_BRIDGE_KEY=
# AI (opcional)
OPENROUTER_API_KEY=
# Metabase (opcional)
METABASE_DB_PASS=
METABASE_URL=http://localhost:3000
```
---
## Mejoras Pendientes (Roadmap Actualizado)
### 🔴 Crítico — Deuda Técnica
| # | Mejora | Descripción | Bloqueo |
|---|--------|-------------|---------|
| 1 | **Particionar `vehicle_parts` en producción** | Script `partition_vehicle_parts.py` listo. Ejecutar en staging primero, luego producción. Reduce 254 GB → particiones HASH 16. | Necesita ventana de mantenimiento |
| 2 | **Quart async catalog en producción** | PoC en puerto 5002 funciona. Integrar con nginx reverse proxy, migrar endpoints críticos. | Necesita hypercorn + monitoreo |
| 3 | **Arreglar `scripts/minify-assets.sh`** | Itera sobre `*.js`/`*.css` incluyendo `.min.*`, generando `.min.min.*`. Filtrar archivos ya minificados. | Riesgo de archivos corruptos en deploy |
### 🟠 Alto — Features de Negocio
| # | Mejora | Descripción | Esfuerzo |
|---|--------|-------------|----------|
| 4 | **WhatsApp Business API (Meta Cloud)** | Actualmente solo webhook Baileys. Migrar a Meta Cloud API para escalabilidad real. Requiere verificación de cuenta Meta. | 2-3 semanas |
| 5 | **BNPL real** | Integrar APLAZO/Kueski/Clip para "compra ahora, paga en 15/30 días". Ahora solo es stub. | 2 semanas |
| 6 | **ERP Sync real** | Conectar con Aspel/Contpaqi/SAP/Odoo vía API o archivos de intercambio. Ahora solo es stub. | 2-3 semanas |
| 7 | **Mercado Libre / Amazon sync** | Publicar inventario de bodegas en marketplaces. API de ML Seller + Amazon SP-API. | 3 semanas |
| 8 | **PWA mejorada** | Offline mode, install prompt, background sync para catálogo y carrito. | 1-2 semanas |
### 🟡 Medio — Diferenciadores
| # | Mejora | Descripción | Esfuerzo |
|---|--------|-------------|----------|
| 9 | **App móvil nativa (Capacitor)** | Wrap del POS como app iOS/Android. Camera nativa, push notifications, biometrics. | 3-4 semanas |
| 10 | **Portal de proveedores** | Dashboard para que proveedores vean demanda por zona y tipo de parte. | 2 semanas |
| 11 | **Dashboard in-app** | Gráficos de rendimiento en tiempo real (ventas, productividad, conversión) en el POS. | 1-2 semanas |
| 12 | **Crédito basado en comportamiento** | Evaluación automática de línea de crédito por historial de pagos del cliente. | 2 semanas |
| 13 | **Programa de embajadores** | Referidos con recompensas, tracking de conversiones. | 1 semana |
### 🟢 Bajo — Polish
| # | Mejora | Descripción |
|---|--------|-------------|
| 14 | **Cache warming automatizado** | Agregar systemd timer/service para correr `warm_cache.py` diariamente (ahora es manual). |
| 15 | **Backup automatizado** | El último backup es del 27/04. Automatizar con cron + S3/GCS. |
| 16 | **Monitoreo/Alerting** | Prometheus/Grafana o similar para gunicorn, PostgreSQL, Redis, Celery. |
| 17 | **Tests de integración frontend** | Playwright/Cypress para flujos críticos (checkout, búsqueda, login). |
---
## Backup
Último backup: `/home/Autopartes/backups/nexus_backup_20260427_045859.tar.gz` (1.3 GB)