Cambios implementados:
1. Lazy loading de imágenes:
- catalog.js: loading="lazy" decoding="async" en part cards y detail panel
- inventory.js: lazy loading en imagen de detalle de item
2. Minificación de assets:
- scripts/minify-assets.sh: minifica JS (terser) y CSS para POS y Dashboard
- 25 archivos .min.js + 5 .min.css generados en pos/static/
- 14 archivos .min.js + 8 .min.css generados en dashboard/
3. Nginx auto-serve minified:
- try_files $1.min.js antes de servir .js original
- try_files $1.min.css antes de servir .css original
- Transparente para los templates HTML (cero cambios en HTML)
4. Cache warming script:
- scripts/warm_vehicle_cache.py: pobla Redis con vehicle info por batches
- Mitiga DISTINCT ON + 4 JOINs sobre 2B filas
- Corre en background, procesa ~1.5M parts
Tests: 73/73 pasando
Cambios implementados:
1. Redis cache para _classify_cache (catalog_service.py):
- Reemplaza dict in-memory por Redis compartido entre workers
- TTL 5 minutos para clasificación Nexpart
- classify_cache_clear() y classify_cache_stats() actualizados
- Hit rate pasa de ~6% (15 cachés separados) a ~80%+ (cache unificado)
2. Redis cache para vehicle info en smart_search():
- Verifica Redis antes de ejecutar DISTINCT ON + 4 JOINs sobre 2B filas
- Cache miss: query solo para los part_ids faltantes
- TTL 1 hora por part_id
- Impacto: búsquedas repetidas pasan de 500ms–2s a < 50ms
3. Gunicorn gthread (gunicorn.conf.py):
- worker_class = 'gthread' con 4 threads por worker
- 4 workers × 4 threads = 16 requests concurrentes
- max_requests = 1000 para reciclar workers y prevenir memory leaks
Tests: 73/73 pasando
Cambios implementados:
1. Connection pooling (tenant_db.py):
- psycopg2.pool.ThreadedConnectionPool para master y tenants
- Wrapper _PooledConnection que devuelve al pool en .close()
- Cero cambios en blueprints (backward compatible)
2. Tabla inventory_stock_summary + triggers (v3.2):
- O(1) stock lookup en vez de SUM() sobre historial completo
- Trigger AFTER INSERT en inventory_operations recalcula stock
- Poblada inicialmente en ambos tenants
- Refactor en 6 archivos de servicios para usar la nueva tabla
3. Fix N+1 en process_sale (pos_engine.py):
- Precarga retail_price en bulk query FOR UPDATE
- Elimina SELECT individual por item en loop
4. Índices críticos:
- idx_parts_name_part + pattern_ops (master)
- idx_inv_ops_inventory_branch_created (tenants)
- idx_wi_part_stock_positive (master, ya existía desde Fase 1)
Tests: 73/73 pasando (compat + fase3 + fase5 + fase6)
Migración: v3.2_db_performance.sql
- Nueva tabla inventory_vehicle_compat (v3.1)
- Motor inventory_vehicle_compat.py: auto-match + gestión manual
- catalog_service.get_parts_local() ahora incluye piezas locales vinculadas
- inventory_bp: auto-match en create/update + endpoints REST /vehicles
- Frontend catalog.js: badge 'Stock Local' para piezas nativas del tenant
- Frontend inventory.js: panel de vehículos compatibles con auto-match
- Tests: test_compatibility.py (9/9 pasan)
Piezas locales aparecen en navegación por vehículo aunque no estén en TecDoc.
Auto-match busca part_number en parts/aftermarket_parts y copia MYEs compatibles.
Replaced hardcoded values (4,817 SKUs, $2.4M, 1,284 clients, $842,190
invoiced, $2,847,320 assets, etc.) with $0 / 0 placeholders with IDs
so the JS can populate them from real API data.
Affected: inventory.html, customers.html, invoicing.html, accounting.html
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Eliminado: diagrams_bp, ruta /pos/diagrams, link en sidebar,
boton "Ver diagramas" en catalogo. Los archivos SVG y blueprint
se mantienen en el repo por si se reactivan en el futuro.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Blueprint with API endpoints: list, detail, SVG serve, vehicle-linked diagrams
- Interactive SVG viewer with zoom/pan (mouse wheel, drag, touch, keyboard)
- Clickable hotspots that highlight on hover and show part detail panel
- Parts sidebar listing all callout numbers with catalog search integration
- 3 placeholder SVG diagrams: braking system, suspension, engine components
- Seeded diagrams, hotspots, and vehicle_diagrams in DB
- Added to sidebar nav, i18n (ES/EN), and "Ver diagramas" link in catalog
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Kiosk mode: fullscreen, wake lock, auto-login, context menu block, PWA/Capacitor detection
- AI vision: camera photos analyzed by Gemma 3 27B vision model via OpenRouter
- AI part classification: auto-suggest name/brand/category when entering part number
- Public catalog chatbot: /api/chat endpoint with rate limiting, chat widget on catalog page
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Reemplaza /instance/status → /status, /instance/create → /connect, etc.
Lee QR de data.qr (formato del bridge) ademas de data.base64 (Evolution).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Reemplaza Evolution API con bridge Node.js propio usando Baileys.
QR se genera en ~10 segundos. Auto-reply con chatbot IA.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Switch from Meta Business Cloud API to Evolution API for WhatsApp integration.
Evolution API is self-hosted, free, and connects via WhatsApp Web QR code scan.
- Add docker-compose for Evolution API deployment
- Rewrite whatsapp_service.py for Evolution API endpoints
- Add instance management (create, QR, status, logout) to blueprint
- Add QR code scanning UI with connection status indicator
- Add duplicate message prevention in webhook handler
- Update config.py with EVOLUTION_API_URL/KEY (remove old Meta vars)
- Add setup documentation
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Demo/sample rows in HTML tables were visible on first render before JS
populated real data. Replaced all hardcoded tbody rows and finance cards
with empty containers that JS populates from API on load.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- i18n.js with 130+ translation keys for es/en, loaded in all 11 templates
- sidebar.js uses t() for all nav labels, adds MX/US language toggle
- app-init.js role labels use i18n
- currency.py service with convert() and format_currency()
- config.py adds DEFAULT_CURRENCY and EXCHANGE_RATE_USD_MXN settings
- config_bp.py adds GET/PUT /pos/api/config/currency endpoints
- config.html adds currency/exchange-rate section (Section 8)
- config.js adds loadCurrency/saveCurrency with localStorage sync
- pos.js fmt() reads pos_currency from localStorage for USD/MXN display
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Gunicorn production server with auto-scaled workers, run.sh, updated systemd service
- Marketplace B2B: cross-tenant inventory search, ordering, seller management with full UI
- Subscription billing: plan limits enforced on products/employees/branches, billing API + upgrade flow
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add thermal_printer.py service generating raw ESC/POS bytes for 58mm/80mm printers
- Add /pos/api/sales/<id>/print endpoint (escpos_raw or browser mode)
- Add printer.js with WebUSB and Web Serial support for direct browser-to-printer
- Add thermal print button in ticket modal with connect/print workflow
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Chat now fetches tenant inventory summary (brands, counts, low-stock)
and injects it into the AI system prompt so responses prioritize local
stock. VIN decoder uses free NHTSA vPIC API to decode 17-char VINs and
auto-fills the vehicle selector dropdowns when a catalog match is found.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1. Spanish translations for TecDoc catalog (translations.py) applied to
catalog_service.py and dashboard server.py endpoints
2. Printable quotation HTML endpoint (/pos/api/quotations/<id>/pdf) with
@media print CSS for clean browser-to-PDF output
3. Web Push notifications to owner/admin on sale cancellation, stock zero,
and cash register differences > $500. Includes service worker, VAPID
key management, and subscription endpoints.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1. Auto dark mode: detect system prefers-color-scheme, auto-switch industrial/modern theme
2. Email quotation endpoint: POST /quotations/:id/email sends HTML email via SMTP
3. Camera barcode scanner: BarcodeDetector API with getUserMedia overlay in catalog
4. Returns with warranty: POST /returns endpoint with stock restoration and sale status tracking
5. Partial offline catalog: cache top 500 parts in IndexedDB, search when offline
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1. Symptom diagnosis: AI now detects vehicle symptoms and suggests probable parts
2. Smart quotations: "cotizame frenos completos" returns multiple search_queries (pipe-separated), backend searches each term and deduplicates
3. Photo identification: camera button in chat widget uploads image and sends placeholder prompt (ready for vision model)
4. Multilanguage: AI detects user language and responds accordingly, search_query always in English
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Build debug APK (8.3MB) con Capacitor + Android SDK 34.
Carga desde nexus.consultoria-as.com/pos con PWA offline.
Incluye plugins: camera, push notifications, haptics, status bar.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Set up Capacitor to wrap the Nexus POS web app as a native mobile app.
The app loads from the remote server URL so no bundling is needed.
Includes native-bridge.js for camera, push notifications, haptics,
and status bar integration when running inside the native shell.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add full fleet management (Feature 13): database migration for fleet_vehicles,
fleet_maintenance_schedules, and fleet_maintenance_logs tables; REST API blueprint
with CRUD, scheduling, logging, alerts, and stats endpoints; frontend with tabbed
UI (vehicles grid, maintenance schedules, history, overdue alerts); sidebar nav entry.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add full WhatsApp Cloud API integration for Nexus POS:
- Service layer (whatsapp_service.py): send text, templates, quotations,
order confirmations, stock alerts; process incoming webhooks with AI auto-reply
- Blueprint (whatsapp_bp.py): public webhook endpoints for Meta verification +
incoming messages; authenticated endpoints for send, send-quote, conversations
- Conversation UI (whatsapp.html + whatsapp.js): split-panel messenger with
conversation list, chat bubbles, send input, quote sending; both themes
- Migration v1.4: whatsapp_messages table with phone/direction/status indexes
- Config: WHATSAPP_TOKEN, WHATSAPP_PHONE_ID, WHATSAPP_VERIFY_TOKEN env vars
- Sidebar: WhatsApp nav item under Gestion with message-bubble icon
- Ready for Meta Business credentials (infrastructure complete, no API keys needed)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add POST/DELETE /items/{id}/image endpoints with Pillow processing (resize 800px, thumbnail 300px, JPEG 85%)
- Validate file type (jpg/png/webp) and size (max 5MB)
- Show image in product detail modal with upload/delete buttons
- Enrich catalog parts list with local inventory image when available
- Image directory created automatically on first upload (pos/static/images/parts/)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Replace static demo data with live API calls across all four report tabs:
- Ventas: sales by period/employee/payment method with date filters
- Inventario: valuation, ABC classification, low stock, no movement
- Clientes: accounts receivable aging report
- Financieros: income statement, balance sheet, trial balance, register history
All tabs use lazy loading (fetch on first visit) and JWT auth.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Replace all hardcoded/demo data with live API calls:
- KPIs from /pos/api/register/daily-summary (ventas, tickets, promedio, cajas)
- Inventory alerts from /pos/api/inventory/alerts (zero, low, over stock)
- Top products aggregated from /pos/api/sales detail items
- Weekly bar chart from 7-day daily summaries
- Recent sales table with real items from sale detail endpoint
- Auto-refresh every 2 minutes, manual refresh button
- Dynamic greeting with time-of-day and JWT user name
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Replace hardcoded demo data in the config page with real API calls.
Branches and employees now load from /pos/api/config/* endpoints,
with create modals for both. Business data tab reads tenant_config
(read-only). Theme selector was already working and is preserved.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Proxy was using resp.raw.headers (urllib3) which could miss Content-Type;
switched to resp.headers. SW now skips /pos/api/auth/ to prevent stale
token caching, scopes fetch to /pos/ only, and bumps cache to v2.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
3 reintentos con espera 5s/10s/15s. Si agota reintentos,
muestra mensaje amigable en vez de error.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Manejo de historial con pushState/popState. Cada nivel de navegacion
se registra en el historial del navegador. El boton atras regresa al
nivel anterior en vez de salir del catalogo.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Remueve codigos de generacion, numeros romanos, tipos de carroceria.
Deduplica por display_name. Toyota: 236 → 73 modelos limpios.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- catalog.js: state → nav (variable correcta del catalogo)
- vsClearAll: resetea nav en vez de state inexistente
- favicon.ico: sirve icon-192.png del PWA
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Al seleccionar ano, solo muestra marcas/modelos disponibles para ese ano.
Toyota 2020: 92 modelos vs 625 sin filtro.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Validacion _validate_model() verifica que el modelo termine en ':free'.
Si alguien cambia MODEL a uno de pago, el chatbot lanza error en vez
de generar costos. Alternativas documentadas en comentario.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Barra de 4 dropdowns arriba del catalogo que se habilitan en cascada.
Al completar los 4, muestra categorias y partes para ese vehiculo.
Boton de limpiar para resetear. Endpoint /years-all para cargar anos.
Estilos con design system tokens (ambos temas).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
El chatbot ahora busca primero en el inventario local del tenant
y luego en el catalogo TecDoc. Resultados muestran badge:
- Verde "MI INVENTARIO" para partes locales
- Azul "CATALOGO" para partes del catalogo TecDoc
Busqueda local funciona en español e inglés.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Al abrir el detalle de un producto, se cargan automaticamente:
- Disponibilidad en bodegas (stock + precio)
- Partes equivalentes aftermarket (cross-references del catalogo TecDoc)
Usa catalog_part_id o busqueda por part_number contra el catalogo central.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- System prompt: SIEMPRE devuelve search_query en ingles
- Diccionario de traducciones (balatas→Brake Pad, etc.)
- Busca directo sin preguntar mas info
- Fallback: extrae keywords si AI no da search_query
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>