Commit Graph

63 Commits

Author SHA1 Message Date
ea29cc31c0 feat(catalog): supplier catalog cleanup, fuzzy matching, and navigation fixes
- Cleaned 137+ fake engine-displacement models from supplier imports
  (v3/v4 scripts: Chevrolet, Ford, Chrysler, Dodge, Jeep, Nissan, etc.)
- Removed 1,251+ corrupted models (INT. prefixes, year-suffix, torque specs,
  empty names, trailing-year variants)
- Migrated supplier tables to master DB (supplier_catalog,
  supplier_catalog_compat, supplier_catalog_interchange)
- Fixed _get_mye_ids_with_parts() to query supplier_catalog_compat from
  master DB so supplier-only vehicles appear for all tenants
- Added fuzzy model matcher with parenthesis stripping, noise suffix removal,
  compact matching, prefix/substring fallback, model aliases, and ±3 year
  proximity
- Matched compat rows: KEEP GREEN +14,152, KNADIAN +3,021, VAZLO +127,500,
  LUK +477, RAYBESTOS +1,743
- Added KNADIAN catalog importer with year-range expansion and future-year
  filtering
- Added VAZLO catalog importer with position parsing and SKU-in-model cleanup
- Added Keep Green, LUK, Yokomitsu, Raybestos catalog importers
- Cache clearing after cleanups (_classify_cache_*, nexus:mye_ids:*,
  nexus:brand_mye_counts:*)

Final match rates:
- KEEP GREEN: 90.3%
- VAZLO: 93.6%
- YOKOMITSU: 100.0%
- KNADIAN: 57.4%
- LUK: 51.0%
- RAYBESTOS: 55.9%
2026-06-09 07:47:42 +00:00
718fa06888 feat: module toggles in POS config and Instance Manager
- Add GET/PUT /pos/api/config/modules endpoints in POS config_bp.py
- Update sidebar.js to filter nav items based on enabled modules
- Add Modules section to POS config.html with toggles for WhatsApp, Marketplace, MercadoLibre
- Add module load/save logic to POS config.js
- Preload modules in app-init.js for sidebar caching

- Add tenant module management to Instance Manager
  - get_tenant_modules / update_tenant_modules in tenant_service.py
  - GET/PUT /api/tenants/<id>/modules endpoints in tenants_bp.py
  - Add modules modal to manager index.html
  - Add module editing UI and logic to manager.js
  - Add toggle-switch CSS to manager.css
2026-05-28 00:21:52 +00:00
61bf84b2dc fix(alerts): limit alerts to 500 per type in SQL + frontend pagination with 'Ver más' + summary bar 2026-05-26 09:12:09 +00:00
584cc385b9 feat: add custom/not_specified shipping modes with cost input for ML publish
- build_item_payload supports shipping_cost for custom mode with costs array
- Add shipping mode selector: me2, custom, not_specified
- Show shipping cost input when custom is selected
- Backend passes shipping_cost through custom_data to payload builder
2026-05-26 06:32:21 +00:00
314075021e fix: simplify shipping payload, remove forced local_pick_up/free_shipping
- build_item_payload now sends only mode in shipping payload by default
- Let ML determine free_shipping/local_pick_up based on account config
- Better error message for mandatory free shipping scenario
2026-05-26 06:13:50 +00:00
f742cdaa42 fix: ML shipping config check + improved payload + actionable error messages
- Add get_shipping_preferences to meli_service.py
- Add check_meli_shipping_config to validate ME2 adoption before publishing
- Include local_pick_up and free_shipping in item payload
- Translate ME2/mode errors to actionable Spanish messages
- Check shipping config in both validate_items and publish_items
2026-05-26 05:26:47 +00:00
b314a781a1 feat: robust ML publish with pre-flight, preview, validation, async
- Add /inventory-check endpoint for local pre-flight validation
- Add /listings/validate endpoint using ML /items/validate API
- Add /categories/<id>/attributes endpoint for required attrs
- Add /listings/async + polling for background publishing via Celery
- Editable preview: title (0/60 counter), price, stock per item
- Pre-flight checks: image, stock, price, duplicate detection
- Image upload directly from publish modal (uses existing /items/<id>/image)
- Dynamic required attributes form based on selected ML category
- Frontend: validate button, async polling with progress, detailed error display
- Backend: build_item_payload supports custom_title, extra_attributes
2026-05-26 04:37:05 +00:00
a236187f3a feat: MercadoLibre integration + inventory bulk publish + WhatsApp bridge fixes
- Add MercadoLibre OAuth, listings, orders, webhooks and category search
- New marketplace_external_bp.py, meli_service.py, marketplace_external_service.py
- New marketplace_external.html/js with ML management UI
- Inventory: bulk publish to ML with category autocomplete, listing type and shipping selectors
- Inventory: new .btn--meli styles, select/label CSS fixes
- WhatsApp bridge: rate limiting, 440/515/408 error handling, stale watchdog
- DB migration v3.4_meli_integration.sql for marketplace_listings, orders, sync_queue
- Add Celery tasks for ML sync and webhook processing
- Sidebar: MercadoLibre navigation link
2026-05-26 04:24:07 +00:00
50c0dbe7d4 feat(inventory): Qwen vehicle compatibility — store AI unmatched vehicles as text, Celery background sync, fix brand filter fallback, increase vehicle limits 2026-05-18 19:32:35 +00:00
36dd6634e3 feat(whatsapp): per-tenant WhatsApp configuration
- Refactor whatsapp_service.py to accept bridge_url parameter
- whatsapp_bp.py: remove hardcoded tenant_id=11, use g.tenant_id
- whatsapp_bp.py: webhook now accepts ?tenant_id param with fallback
- config_bp.py: add GET/PUT /config/whatsapp endpoints
- Each tenant can now have its own Baileys bridge URL and settings
2026-05-18 04:38:47 +00:00
ff45905b49 feat(whatsapp): QWEN primary AI backend, Hermes fallback, conversation history, vehicle persistence, demo prompts
- Add QWEN (qwen3.6) as primary AI backend with short system prompt
- Hermes remains as fallback with 45s timeout
- Increase QWEN timeout to 35s, max_tokens to 4000
- Add conversation history loading from whatsapp_messages (last 4 msgs)
- Persist detected vehicle in whatsapp_sessions table
- Add 'limpiar chat' / 'nuevo chat' / 'reset' commands to clear history
- Fix CSS conflict: rename whatsapp chat-panel classes to wa-chat-panel
- Fix JS ID conflicts with chat.js widget (waChatPanel, waChatMessages, etc.)
- Improve no-stock response: conversational with alternatives
- Split search_query by | for multi-part lookups
- Add DEMO_PROMPTS.md and DEMO_PROMPTS_V2.md
2026-05-06 20:27:14 +00:00
371d72887e refactor: centralize QWEN fitment saving via save_qwen_fitment()
- Added save_qwen_fitment() in inventory_vehicle_compat.py to centralize
  inserting QWEN results into inventory_vehicle_compat
- Simplified inventory_bp.py create_item() and auto_match_item_vehicles()
  to use the centralized function, removing duplicated INSERT logic
2026-05-01 07:03:04 +00:00
af7b010e55 feat: configurable vehicle compatibility source (TecDoc / QWEN / Both)
Backend:
- Added GET/PUT /pos/api/config/vehicle-compat-source endpoints
- Added get_compat_source() helper reading from tenant_config
- create_item() now respects config: runs TecDoc and/or QWEN accordingly
- auto_match_item_vehicles() respects config: runs only configured source

Frontend:
- Added 'Compatibilidad de Vehiculos' section in config.html
- Added loadVehicleCompatSource() / saveVehicleCompatSource() in config.js
- Regenerated config.min.js
2026-05-01 06:52:06 +00:00
5421c47ffc fix(compat): get_compatibility used wrong connection for master tables
inventory_vehicle_compat.get_compatibility was trying to JOIN tenant
inventory_vehicle_compat with master tables (model_year_engine, brands,
models, years, engines) on a single tenant connection. Those tables only
exist in the master DB, causing the query to fail silently.

Fix: split into two queries:
  1. Fetch MYE IDs from tenant's inventory_vehicle_compat
  2. Resolve vehicle details from master DB via ANY(%s)
  3. Merge results

Also fixes the argument mismatch: inventory_bp passed (tenant, master,
item_id) but the function only accepted 2 args.
2026-05-01 06:41:22 +00:00
2e80ba7400 feat(auto_match): exhaustive multi-strategy vehicle compatibility search
Replaced simple exact-match with 8-layer fallback strategy:

1. Exact normalized part number (parts.oem_part_number)
2. Exact normalized aftermarket part number
3. Exact normalized cross-reference number
4. Partial ILIKE match on OEM numbers
5. Partial ILIKE match on aftermarket numbers
6. Partial ILIKE match on cross-reference numbers
7. Separator-stripped fallback (KYB-343412 → KYB343412)
8. Name-based search on parts.name_part / parts.name_es
   and aftermarket_parts.name_aftermarket_parts when no part_number hit

Brand-aware filtering: when brand hint is provided and not 'GENERAL',
only returns MYEs for vehicles of that brand.

Limits: max 20 part IDs per layer, max 200 MYEs total.

Test: BPR5ES + TOYOTA → matched True, 2 parts, 200 MYEs inserted.
2026-05-01 06:22:17 +00:00
0e549e7746 fix: connection pool exhaustion + cross_ref column name
- tenant_db.py: add rollback() before returning conn to pool to prevent
  'idle in transaction (aborted)' state that exhausts the pool
- tenant_db.py: increase pool maxconn from 10 to 20 for better concurrency
- inventory_vehicle_compat.py: fix column name cross_ref_number ->
  cross_reference_number to match actual schema
2026-05-01 02:25:58 +00:00
b27dd720aa feat(catalog): expand LOCAL_BODEGA_BRANDS to 96 Nort America brands
- Added all brands with vehicles >= 1980 relevant to Mexico-USA-Canada
- Covers: American, Japanese, Korean, German, UK, Italian, French,
  Swedish, Spanish, Chinese (with MX presence), Indian, and commercial
- All 96 brands verified against master DB with year >= 1980
2026-04-30 07:43:39 +00:00
623c57bb08 fix(qwen_fitment): resolve DB schema mismatch and double-fetchone bug
- Fixed column names: brands.name_brand, models.name_model, engines.name_engine
- Added fuzzy model matching with ILIKE %%pattern%% for TecDoc-style names
- Removed erroneous double cur.fetchone() that always returned None
- Added retry logic (3 attempts) for QWEN API empty responses
- Added fallback engine-less query when engine description doesn't match DB
- Protected _extract_json against None input
2026-04-29 08:38:17 +00:00
042acd6207 OPCIÓN C + A1: Consolidación técnica + orjson
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
2026-04-27 09:36:03 +00:00
e21722a3a9 FASE 7c: Redis Cache + Gthread Workers
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
2026-04-27 08:28:03 +00:00
e3c85fd647 FASE 7b: DB Performance — Pooling, Stock Summary, N+1 fix
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
2026-04-27 07:34:31 +00:00
efbd763e43 Opción C: Vinculación híbrida de inventario local con vehículos
- 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.
2026-04-27 06:52:30 +00:00
Nexus Dev
9ff3dc4c8b FASE 4-5-6: Infraestructura, CRM, Service Orders, Notificaciones, Ahorro, Logistica, API Publica
FASE 4:
- Redis cache de stock con fallback graceful
- Multi-moneda (MXN/USD) con contabilidad en MXN
- Proveedores y ordenes de compra completo
- Meilisearch 1.5M+ partes indexadas
- Metabase KPIs con dashboard auto-generado

FASE 5:
- CRM mejorado: activities, tags, loyalty program, analytics
- Imagenes de partes: upload, resize, thumbnails WebP
- Ordenes de servicio Kanban: received->diagnosis->repair->ready->delivered
- Garantias/RMA, alertas de reorden, multi-sucursal
- Stubs BNPL (APLAZO) y ERP Sync (Aspel/Contpaqi)

FASE 6:
- Notificaciones automaticas: push/WhatsApp/email/in-app
- Reportes de ahorro vs retail_price
- Logistica + tracking: DHL, FedEx, Estafeta, 99min, Uber
- API Publica: API keys, rate limiting, catalog search

Migraciones: v1.9-v3.0
Tests: 93/93 pasando
Backup: nexus_backup_20260427_045859.tar.gz
2026-04-27 05:23:30 +00:00
e95f7cf684 feat: complete session — catalog, marketplace, WhatsApp, peer-to-peer, install scripts
Major features:
- Pixel-Perfect glassmorphism design (landing + POS + public catalog)
- OEM/Local catalog toggle with Nexpart taxonomy (14 groups, 108 subgroups, 558 part types)
- Marketplace B2B Phase 1 (bodegas, POs, status machine, WA+email notifications)
- Peer-to-peer inventory (multi-instance, LAN discovery)
- WhatsApp: photo→Vision AI, voice→Whisper, conversational quotations
- Smart unified search (VIN/plate/part_number/keyword auto-detect)
- Shop Supplies tab (vehicle-independent parts)
- Chatbot AI fallback chain (5 models) + response cache
- CSV inventory import tool + setup_instance.sh installer
- Tablet-responsive CSS + sidebar toggle
- Filters, export CSV, employee edit, business data save
- Quotation system (WA→POS) with auto-print on confirmation
- Live stats on landing page

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-18 05:35:53 +00:00
5a88d7c7ff feat(pos): add kiosk mode, AI vision, AI part classification, public chatbot (#19 #25 #30 #29)
- 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>
2026-04-05 04:18:37 +00:00
4cc2c66208 feat(pos): add plate lookup (#8), 326 translations (#12), bulk image import (#11)
- Plate lookup: new plate_vehicles table (v1.7 migration), plate_lookup
  service with Mexican plate validation, GET/POST endpoints on catalog_bp,
  plate search UI in catalog vehicle selector
- Translations: extend PART_TRANSLATIONS from ~80 to 326 entries covering
  brake, engine, fuel, cooling, electrical, drivetrain, suspension, steering,
  exhaust, A/C, lighting, body, interior, fluids, and category translations
- Bulk images: image_scraper service with download+resize+placeholder
  generation, bulk-images and auto-image endpoints on inventory_bp

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 04:17:55 +00:00
e43894b7a4 feat: WhatsApp bridge con Baileys directo — QR funcional
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>
2026-04-05 04:02:16 +00:00
5f92fe83ba feat(pos): replace Meta Cloud API WhatsApp with Evolution API (self-hosted)
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>
2026-04-05 03:15:52 +00:00
c1d0638b45 feat(pos): add multi-language i18n (#37) and multi-currency USD/MXN (#38)
- 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>
2026-04-04 08:19:18 +00:00
e00dce7d5a feat(pos): add gunicorn, marketplace B2B, and subscription billing (#7, #8, #12)
- 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>
2026-04-04 08:17:33 +00:00
ecdc3526a6 feat(pos): add real thermal ticket printing via ESC/POS (#21)
- 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>
2026-04-04 08:16:44 +00:00
f9589f4a4e feat(pos): add inventory-aware chat context (#31) and VIN decoder (#17)
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>
2026-04-04 08:14:45 +00:00
5d5a2777eb feat(pos): add 3 improvements — Spanish translations, PDF quotes, push notifications
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>
2026-04-04 08:05:11 +00:00
39f2aaf98f feat(pos/chat): add 4 AI chatbot improvements — symptom diagnosis, smart quotes, photo ID, multilanguage
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>
2026-04-04 08:00:41 +00:00
c645bc03f3 feat(pos): WhatsApp Business API integration — send/receive messages, quotations
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>
2026-04-04 02:42:17 +00:00
840790a4d0 feat(pos): sistema de imagenes — upload, thumbnail, display en inventario y catalogo
- 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>
2026-04-04 02:34:01 +00:00
8539720645 fix(pos): retry con backoff para rate limit 429 de OpenRouter
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>
2026-04-02 19:48:13 +00:00
fa6f713b7d fix(pos): corregir model ID — qwen/qwen3.6-plus-preview:free
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 08:25:12 +00:00
0f979b7912 feat(pos): parsear nombres de modelos — solo nombre primario visible
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>
2026-04-02 08:23:31 +00:00
97704fd804 feat(pos): filtrar modelos a solo Norteamerica — elimina modelos de otros mercados
Lista de modelos por marca para Mexico/USA/Canada (36 marcas).
Toyota: 625 → 236, Nissan: 499 → 138, Ford: 288 → 114,
Chevrolet: 470 → 207, VW: 283 → 143, Honda: 223 → 117.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 08:12:02 +00:00
10e318bfd7 feat: dropdown filtra marcas y modelos por ano seleccionado
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>
2026-04-02 08:06:34 +00:00
67e214db15 fix(pos): bloquear modelos de pago — solo modelos :free permitidos
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>
2026-04-02 08:02:10 +00:00
f30a782feb feat(pos): cambiar modelo de chatbot a Qwen 3.6 Plus Preview (free)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 08:00:43 +00:00
b5d62c2812 fix(pos): chatbot busca partes automaticamente con traduccion ES→EN
- 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>
2026-04-02 07:39:47 +00:00
0a44fb5304 feat(pos): chatbot IA con OpenRouter — busqueda de partes por lenguaje natural
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 07:18:55 +00:00
6628f2deef feat: subdomain routing por tenant — refac-xxx.nexusautoparts.com
- Nginx wildcard config: *.nexusautoparts.com routes to POS app with X-Tenant-Subdomain header
- middleware_tenant.py: resolves subdomain -> tenant_id via nexus_master.tenants.subdomain
- auth_bp: login and employee list endpoints accept tenant from subdomain, URL param, or body
- login.html: auto-detects tenant from subdomain, shows business name, falls back to ?tenant=ID
- tenant_manager: generates subdomain slug from business name on provision_tenant()
- Migration v1.2: adds subdomain column + unique index to tenants table
- setup-nginx.sh: one-command install script for the nginx config

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 07:16:49 +00:00
a74fe94187 feat(pos): filtrar marcas a solo Mexico/USA/Canada (36 marcas)
Eliminadas marcas de otros mercados (China, Australia, etc.)
Solo se muestran las relevantes para Norteamerica.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 22:21:52 +00:00
d5569d0cb6 perf(pos): eliminar JOIN vehicle_parts de queries de navegacion
vehicle_parts tiene 14B+ rows. Las queries de brands, models, years,
engines ahora solo usan model_year_engine (mucho mas rapido).
vehicle_parts solo se consulta para categories/groups/parts donde
se filtra por un mye_id especifico.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 22:16:31 +00:00
a3abb6d3a8 fix(pos): restaurar catalog_service.py real (sobreescrito por stub)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 22:10:55 +00:00
33cb053519 feat(pos): rewrite catalog blueprint — 9 endpoints for vehicle hierarchy navigation
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 21:42:58 +00:00