# Features Batch 2 — Design Specs

**Date:** 2026-04-04
**Author:** Consultoria AS + Claude
**Status:** Draft

---

## Feature 6: WhatsApp Business API

### Overview

Allow refaccionarias to receive customer inquiries, send quotes, and notifications via WhatsApp. Customers message the store's WhatsApp number; messages are routed to an AI chatbot or a human employee. Outbound messages include quotes, order confirmations, and stock alerts.

### Architecture

- Use **WhatsApp Cloud API (Meta)** or **Twilio WhatsApp Business API** as the messaging transport.
- A webhook endpoint receives inbound messages and routes them to the existing AI chatbot (`ai_chat.py`) or to an employee conversation queue.
- Outbound flow: the system sends quotes, order confirmations, and stock alerts to customers via the API.
- Each tenant can configure their own WhatsApp Business number, or share a central number with routing logic based on tenant context.

```
Customer (WhatsApp) --> Meta Cloud API --> Webhook --> whatsapp_service.py
                                                        |
                                           +------------+------------+
                                           |                         |
                                     AI Chatbot               Employee Queue
                                     (ai_chat.py)           (whatsapp.html)
                                           |                         |
                                           +------------+------------+
                                                        |
                                                  Outbound reply
                                              (quote / confirmation)
```

### Endpoints and Components

| Component | Path | Purpose |
|-----------|------|---------|
| WhatsApp service | `/home/Autopartes/pos/services/whatsapp_service.py` | Send/receive messages, template management, media handling |
| Blueprint | `/home/Autopartes/pos/blueprints/whatsapp_bp.py` | Webhook verification (GET), inbound messages (POST), admin API |
| Template | `/home/Autopartes/pos/templates/whatsapp.html` | Conversation view, message history, manual reply UI |
| Config | Tenant settings table | API token, phone number ID, business account ID per tenant |

**API Endpoints:**

- `GET /pos/api/whatsapp/webhook` — Meta webhook verification (hub.challenge)
- `POST /pos/api/whatsapp/webhook` — Receive inbound messages
- `POST /pos/api/whatsapp/send` — Send message to customer (text, template, or media)
- `GET /pos/api/whatsapp/conversations` — List active conversations
- `GET /pos/api/whatsapp/conversations/<id>/messages` — Message history
- `POST /pos/api/whatsapp/templates` — Manage message templates

### Key Decisions

- **Meta Cloud API** recommended: free for first 1,000 service conversations per month, no per-message cost for business-initiated within 24h window. Twilio adds $0.005/msg overhead.
- Webhook URL must be HTTPS; Cloudflare already handles TLS termination.
- Each tenant needs their own WhatsApp Business number (Meta requirement for verified businesses) or a shared number with keyword-based routing.
- Message templates must be pre-approved by Meta for outbound notifications outside the 24h window.

### Dependencies

- Meta Business account verification (takes 1-2 weeks)
- Existing AI chatbot (`ai_chat.py`) for auto-responses
- Existing quotation system for generating and sending quotes
- Cloudflare for HTTPS webhook endpoint

### Effort Estimate

**2-3 weeks**

- Week 1: Webhook setup, message send/receive, service layer
- Week 2: Conversation UI, AI chatbot integration, quote sending
- Week 3: Template management, multi-tenant routing, testing

---

## Feature 9: Imagenes de Partes

### Overview

Add images to the parts catalog so customers and counter staff can visually identify parts. Images are stored on the local filesystem and served statically. Staff can upload images manually, import from URLs, or bulk-import via CSV.

### Architecture

- Images stored at `/home/Autopartes/data/images/parts/<tenant_id>/<item_id>.<ext>`
- The `image_url` field already exists in the inventory schema; populate it on upload.
- Thumbnails (300x300) are generated on upload for use in catalog cards and search results.
- Original images are preserved for detail views.

```
Upload (file/URL) --> resize + thumbnail --> filesystem
                                              |
                                     /pos/static/images/parts/<file>
                                              |
                                     image_url column updated in DB
```

### Endpoints and Components

| Component | Path | Purpose |
|-----------|------|---------|
| Upload endpoint | `POST /pos/api/inventory/items/<id>/image` | Upload image file or provide URL |
| Image serving | `/pos/static/images/parts/<filename>` | Static file serving via Flask/nginx |
| Bulk import | `POST /pos/api/inventory/images/bulk` | CSV with item IDs and image URLs |
| UI update | Inventory detail modal | Upload button, image preview, delete |

**API Endpoints:**

- `POST /pos/api/inventory/items/<id>/image` — Upload image (multipart/form-data or JSON with URL)
- `DELETE /pos/api/inventory/items/<id>/image` — Remove image
- `POST /pos/api/inventory/images/bulk` — Bulk import from CSV (columns: item_id, image_url)
- `GET /pos/api/inventory/items/<id>/image` — Redirect to static image URL

### Implementation Approach

1. Add Pillow dependency for image processing.
2. On upload: validate file type (JPEG, PNG, WebP), resize original to max 1200px wide, generate 300x300 thumbnail.
3. Save to filesystem with naming convention: `{item_id}_full.webp` and `{item_id}_thumb.webp` (convert all to WebP for size savings).
4. Update `image_url` in the inventory item record.
5. Update catalog card template to show thumbnail; detail modal shows full image.
6. Bulk import: download each URL, process, store, update DB in a background task.

### Dependencies

- **Pillow** (`pip install Pillow`) for image resizing and format conversion
- Filesystem storage (no cloud storage needed initially)

### Effort Estimate

**1 week**

- Days 1-2: Upload endpoint, image processing, filesystem storage
- Days 3-4: UI integration (catalog cards, detail modal, upload button)
- Day 5: Bulk import, testing, edge cases

---

## Feature 13: Gestion de Flotillas

### Overview

Module for fleet operators (transport companies, car rental agencies, corporate fleets) to manage vehicle maintenance schedules, track service history, and receive alerts when maintenance is due. Links to the parts catalog for automatic part suggestions per maintenance type.

### Architecture

New tables in the tenant database:

```sql
-- v1.3_fleet.sql

CREATE TABLE fleet_vehicles (
    id SERIAL PRIMARY KEY,
    tenant_id INTEGER NOT NULL REFERENCES tenants(id),
    plate VARCHAR(20) NOT NULL,
    vin VARCHAR(17),
    make VARCHAR(100),
    model VARCHAR(100),
    year INTEGER,
    current_mileage INTEGER DEFAULT 0,
    status VARCHAR(20) DEFAULT 'active',  -- active, inactive, sold
    notes TEXT,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE fleet_maintenance_schedules (
    id SERIAL PRIMARY KEY,
    tenant_id INTEGER NOT NULL REFERENCES tenants(id),
    vehicle_id INTEGER REFERENCES fleet_vehicles(id),
    maintenance_type VARCHAR(100) NOT NULL,  -- 'oil_change', 'brake_pads', 'tire_rotation', etc.
    interval_km INTEGER,          -- every N kilometers
    interval_days INTEGER,        -- every N days
    last_done_km INTEGER,
    last_done_date DATE,
    next_due_km INTEGER,
    next_due_date DATE,
    parts_list JSONB,             -- suggested parts from catalog
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE fleet_maintenance_logs (
    id SERIAL PRIMARY KEY,
    tenant_id INTEGER NOT NULL REFERENCES tenants(id),
    vehicle_id INTEGER NOT NULL REFERENCES fleet_vehicles(id),
    schedule_id INTEGER REFERENCES fleet_maintenance_schedules(id),
    maintenance_type VARCHAR(100) NOT NULL,
    mileage_at_service INTEGER,
    service_date DATE NOT NULL DEFAULT CURRENT_DATE,
    parts_used JSONB,             -- [{item_id, qty, cost}]
    labor_cost NUMERIC(12,2) DEFAULT 0,
    total_cost NUMERIC(12,2) DEFAULT 0,
    notes TEXT,
    performed_by VARCHAR(100),
    created_at TIMESTAMPTZ DEFAULT NOW()
);
```

### Endpoints and Components

| Component | Path | Purpose |
|-----------|------|---------|
| Blueprint | `/home/Autopartes/pos/blueprints/fleet_bp.py` | CRUD for vehicles, schedules, logs |
| Template | `/home/Autopartes/pos/templates/fleet.html` | Fleet dashboard with tabs |
| JS | `/home/Autopartes/pos/static/js/fleet.js` | Client-side logic, charts |
| Migration | `/home/Autopartes/pos/migrations/v1.3_fleet.sql` | Schema creation |

**API Endpoints:**

- `GET/POST /pos/api/fleet/vehicles` — List/create fleet vehicles
- `GET/PUT/DELETE /pos/api/fleet/vehicles/<id>` — Vehicle CRUD
- `PUT /pos/api/fleet/vehicles/<id>/mileage` — Update current mileage
- `GET/POST /pos/api/fleet/vehicles/<id>/schedules` — Maintenance schedules for a vehicle
- `GET/POST /pos/api/fleet/vehicles/<id>/logs` — Maintenance log entries
- `GET /pos/api/fleet/alerts` — Vehicles with overdue or upcoming maintenance
- `GET /pos/api/fleet/reports` — Fleet cost reports (by vehicle, by period, by type)

### Implementation Approach

1. Run migration to create tables.
2. Build blueprint with standard CRUD endpoints.
3. Fleet dashboard UI: vehicle list with status indicators (green/yellow/red based on maintenance status).
4. Alert logic: compare `current_mileage` vs `next_due_km` and `CURRENT_DATE` vs `next_due_date`; flag vehicles within 10% of threshold.
5. When logging a service, auto-update the schedule's `last_done` and `next_due` fields.
6. Part suggestion: given a maintenance type and vehicle (make/model/year), query the parts catalog for matching parts.
7. Reports: cost per vehicle, cost per km, maintenance frequency charts.

### Dependencies

- Existing parts catalog for part suggestions
- Tenant system for multi-tenant isolation
- Optional: WhatsApp integration (Feature 6) for sending maintenance alerts to fleet managers

### Effort Estimate

**2 weeks**

- Week 1: Migration, vehicle CRUD, schedule management, alert logic
- Week 2: Dashboard UI, maintenance logging, reports, catalog integration

---

## Feature 15: IA por Voz

### Overview

Voice-activated part search: a mechanic speaks into their phone or computer microphone, the browser transcribes the speech, and the existing AI chatbot processes the query to find matching parts. No server-side speech processing required.

### Architecture

- Use the **Web Speech API** (`SpeechRecognition` / `webkitSpeechRecognition`), which is built into Chrome, Edge, and Safari. Free, no API keys needed.
- Transcribed text is sent to the existing chatbot endpoint (`POST /pos/api/chat`).
- Results display in the existing chat widget.
- Optional: use `SpeechSynthesis` API to read back AI responses.

```
Mechanic speaks --> Browser Web Speech API (es-MX) --> Transcribed text
                                                            |
                                                   POST /pos/api/chat
                                                            |
                                                      AI response
                                                            |
                                                  Chat widget + (optional TTS)
```

### Endpoints and Components

| Component | Path | Purpose |
|-----------|------|---------|
| Chat JS (update) | `/home/Autopartes/pos/static/js/chat.js` | Add microphone button, speech recognition logic |
| CSS (update) | Existing chat styles | Mic button styling, pulsing animation while listening |

No new backend endpoints required. The existing `POST /pos/api/chat` handles the transcribed text identically to typed text.

### Implementation Approach

1. Add a microphone icon button next to the chat input field.
2. On click: initialize `SpeechRecognition` with `lang: 'es-MX'`, `continuous: false`, `interimResults: true`.
3. Show interim results as greyed-out text in the input field (live preview).
4. On `onresult` (final): populate the chat input and auto-send to the chatbot.
5. Visual feedback: pulsing red mic icon while actively listening; stop on silence or manual tap.
6. Feature detection: if `SpeechRecognition` is not available, hide the mic button entirely (graceful degradation).
7. Optional Phase 2: add a speaker icon on AI responses to read them aloud via `SpeechSynthesis`.

### Dependencies

- None for the core feature (Web Speech API is browser-native)
- Existing AI chatbot (`POST /pos/api/chat`) must be functional
- Chrome/Edge recommended for best `es-MX` speech recognition accuracy

### Effort Estimate

**1 week**

- Days 1-2: Speech recognition integration, mic button UI, interim results
- Days 3-4: Auto-send flow, error handling, visual feedback animations
- Day 5: Testing across browsers, fallback behavior, optional TTS

---

## Feature 20: App Movil Nativa

### Overview

Native mobile app for iOS and Android, enabling store owners and employees to use the POS system from their phones with access to native device capabilities (camera, push notifications, biometrics).

### Architecture Options

| Option | Approach | Pros | Cons |
|--------|----------|------|------|
| A: PWA | Enhance existing PWA | Already done, zero cost | Limited native API access |
| B: React Native | Rewrite UI in React Native | Full native performance | Major rewrite, two codebases to maintain |
| C: Capacitor | Wrap existing web app in native container | Minimal code changes, native API access | Slightly less native feel |

### Recommendation: Option C (Capacitor)

The POS is already a web app with PWA support. Capacitor wraps it as a native app with full access to device APIs while reusing 95%+ of existing code.

### Components

| Component | Path | Purpose |
|-----------|------|---------|
| Config | `/home/Autopartes/capacitor.config.ts` | Capacitor project configuration |
| iOS project | `/home/Autopartes/ios/` | Xcode project (auto-generated) |
| Android project | `/home/Autopartes/android/` | Android Studio project (auto-generated) |
| Native bridge | `/home/Autopartes/pos/static/js/native.js` | Abstraction layer for native vs web APIs |

**Native Plugins:**

- `@capacitor/camera` — Barcode scanning (replace current JS-only scanner)
- `@capacitor/push-notifications` — Push alerts to store owner (low stock, large sales, etc.)
- `@capacitor/biometrics` — Fingerprint/Face ID for login
- `@capacitor/filesystem` — Export ticket PDFs to device storage
- `@capacitor/share` — Share quotes/invoices via native share sheet
- `@capacitor/splash-screen` — Branded launch screen

### Implementation Approach

1. **Setup (Day 1-2):** Initialize Capacitor in the project, configure `capacitor.config.ts` with the POS server URL, add iOS and Android platforms.
2. **Native bridge (Day 3-5):** Create `native.js` that detects Capacitor environment and provides unified API for camera, push notifications, biometrics. Falls back to web APIs when running in browser.
3. **Camera integration (Day 6-7):** Replace current barcode scanner with Capacitor camera plugin for faster, more reliable scanning.
4. **Push notifications (Day 8-10):** Set up Firebase Cloud Messaging (Android) and APNs (iOS). Backend sends push via Firebase Admin SDK when stock is low or a large sale occurs.
5. **Biometric auth (Day 11-12):** Add fingerprint/Face ID option on login screen as alternative to password.
6. **UI polish (Day 13-15):** Safe area insets, status bar styling, haptic feedback on key actions, splash screen.
7. **Store submission (Week 4):** App Store and Play Store listings, screenshots, review process.

### Dependencies

- Node.js and npm (for Capacitor CLI)
- Xcode (for iOS builds) — requires macOS
- Android Studio (for Android builds)
- Apple Developer Account ($99/year) for App Store
- Google Play Developer Account ($25 one-time) for Play Store
- Firebase project for push notifications

### Effort Estimate

**3-4 weeks**

- Weeks 1-2: Capacitor setup, native plugins, camera and push notifications
- Week 3: Biometrics, UI polish, testing on physical devices
- Week 4: Store submission, review process, launch

---

## Summary

| Feature | Effort | Priority Dependencies |
|---------|--------|-----------------------|
| 6. WhatsApp Business API | 2-3 weeks | Meta Business verification, AI chatbot |
| 9. Imagenes de partes | 1 week | Pillow library |
| 13. Gestion de flotillas | 2 weeks | Parts catalog, tenant system |
| 15. IA por voz | 1 week | AI chatbot (already exists) |
| 20. App movil nativa | 3-4 weeks | Capacitor, developer accounts |

**Total estimated effort: 9-11 weeks** (can be parallelized across developers)

**Recommended implementation order:**
1. Feature 9 (Images) — quick win, high visual impact
2. Feature 15 (Voice AI) — quick win, leverages existing chatbot
3. Feature 13 (Fleet management) — new revenue stream
4. Feature 6 (WhatsApp) — requires Meta verification lead time (start verification now)
5. Feature 20 (Mobile app) — wraps everything else, do last
