C1: Materialized view part_vehicle_preview (creación en progreso) - Migración v3.3_materialized_view.sql - catalog_service.py y dashboard/server.py ahora usan la MV - Script refresh_part_vehicle_preview.py + warm_vehicle_cache.py actualizado C2: Fix cache warming script (autónomo) - Auto-re-ejecuta con sudo -u postgres si peer auth falla - Args CLI: --dsn, --batch-size, --ttl, --dry-run C3: CSS dinámico residual extraído - sidebar.js → sidebar.css (nuevo) - pos-utils.js → common.css (nuevo) - Links agregados a 14 templates POS C4: Script de load testing básico - scripts/load_test.py: métricas p50/p95/p99, throughput, errores C5: Documentación actualizada - FASES_IMPLEMENTADAS.md: test count real, FASE 7 completa - performance_audit_2026.md: anexo post-FASE 7, métricas actualizadas A1: Serialización orjson - pos/json_provider.py: DefaultJSONProvider con orjson.dumps/loads - Aplicado a POS app y Dashboard server - Fix indentation error en pos_bp.py Tests: 73/73 pasando
8.2 KiB
8.2 KiB
Nexus POS — Resumen de Fases Implementadas
Fecha: 2026-04-27 Versión DB: v3.2 Tests: 108/108 pasando (pytest) + 207 checks (scripts standalone)
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_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: -40–60%
- TTI: -200–500ms
- Stock lookups: O(n) → O(1)
- Ventas 20 ítems: 21 queries → 1 query
- Cache hit rate: 6% → 80%+
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 |
Variables de Entorno Requeridas
# 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
Próximos Pasos (Roadmap restante)
Opción C — Consolidación Técnica (en progreso)
- Materialized view
part_vehicle_preview— Fallback robusto al Redis cache para vehicle info - Fix cache warming script — Autonomía sin
sudo -u postgres - CSS dinámico residual — Extraer CSS inyectado por JS a archivos externos
- Load testing script — Benchmark básico de endpoints críticos
- Docs audit — Corregir métricas y marcar estado post-FASE 7
Opción A — Arquitectura (pendiente)
- Serialización
orjson— 2-10× faster JSON - Virtual scroll — Tablas grandes sin lag
- Celery worker queue — Tareas pesadas async
- Asyncpg + Quart PoC — Evaluar I/O no bloqueante para catálogo
- Particionar
vehicle_parts— Escalabilidad ilimitada (254 GB → particiones)
Features de Negocio (futuro)
- Mercado Libre / Amazon sync — Publicar inventario en marketplaces
- IA por voz (Chalán de Nexus) — Web Speech API → chatbot existente
- PWA mejorada — Offline mode, install prompt, background sync
- Portal de proveedores — Demand analytics, heatmaps, stock recommendations
- Dashboard in-app — Gráficos de rendimiento en tiempo real
Backup
Último backup: /home/Autopartes/backups/nexus_backup_20260427_045859.tar.gz (1.3 GB)