michangarrito/backups/docs-backup-2026-01-10/docs/00-vision-general/ARQUITECTURA-TECNICA.md
rckrdmrd 97f407c661 [MIGRATION-V2] feat: Migrar michangarrito a estructura v2
- Prefijo v2: MCH
- TRACEABILITY-MASTER.yml creado
- Listo para integracion como submodulo

Workspace: v2.0.0 | SIMCO: v4.0.0
2026-01-10 11:28:54 -06:00

28 KiB

MiChangarrito - Arquitectura Técnica

Diagrama General

┌─────────────────────────────────────────────────────────────────────────────────┐
│                              MICHANGARRITO PLATFORM                             │
├─────────────────────────────────────────────────────────────────────────────────┤
│                                                                                 │
│   CLIENTES                                                                      │
│   ────────                                                                      │
│                                                                                 │
│   ┌──────────────┐   ┌──────────────┐   ┌──────────────┐   ┌──────────────┐   │
│   │   iOS App    │   │ Android App  │   │   Web App    │   │  WhatsApp    │   │
│   │ React Native │   │ React Native │   │    React     │   │  (Meta API)  │   │
│   └──────┬───────┘   └──────┬───────┘   └──────┬───────┘   └──────┬───────┘   │
│          │                  │                  │                  │           │
│          └──────────────────┴──────────────────┴──────────────────┘           │
│                                       │                                        │
│   ┌───────────────────────────────────┴───────────────────────────────────┐   │
│   │                           API GATEWAY                                 │   │
│   │                         (Kong / Custom)                               │   │
│   │   - Rate Limiting    - Auth (JWT)    - Request Routing                │   │
│   └───────────────────────────────────┬───────────────────────────────────┘   │
│                                       │                                        │
│   SERVICIOS                           │                                        │
│   ─────────                           │                                        │
│                                       │                                        │
│   ┌───────────────────────────────────┴───────────────────────────────────┐   │
│   │                         BACKEND API (NestJS)                          │   │
│   │                                                                       │   │
│   │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  │   │
│   │  │   Auth      │  │   Sales     │  │  Products   │  │  Inventory  │  │   │
│   │  │   Module    │  │   Module    │  │   Module    │  │   Module    │  │   │
│   │  └─────────────┘  └─────────────┘  └─────────────┘  └─────────────┘  │   │
│   │                                                                       │   │
│   │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  │   │
│   │  │  Customers  │  │   Orders    │  │   Fiados    │  │  Reports    │  │   │
│   │  │   Module    │  │   Module    │  │   Module    │  │   Module    │  │   │
│   │  └─────────────┘  └─────────────┘  └─────────────┘  └─────────────┘  │   │
│   │                                                                       │   │
│   │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐                   │   │
│   │  │ Subscript.  │  │   Tokens    │  │  Tenants    │                   │   │
│   │  │   Module    │  │   Module    │  │   Module    │                   │   │
│   │  └─────────────┘  └─────────────┘  └─────────────┘                   │   │
│   │                                                                       │   │
│   └───────────────────────────────────────────────────────────────────────┘   │
│                                       │                                        │
│         ┌─────────────────────────────┼─────────────────────────────┐         │
│         │                             │                             │         │
│         ▼                             ▼                             ▼         │
│   ┌─────────────┐             ┌─────────────┐             ┌─────────────┐     │
│   │ MCP Server  │             │  WhatsApp   │             │  Payments   │     │
│   │  (LLM)      │             │  Service    │             │  Service    │     │
│   │             │             │             │             │             │     │
│   │ ┌─────────┐ │             │ - Webhooks  │             │ - Stripe    │     │
│   │ │OpenRouter│ │             │ - Send msg  │             │ - MP SDK    │     │
│   │ │ OpenAI  │ │             │ - Multi-num │             │ - Clip API  │     │
│   │ │ Claude  │ │             │ - OCR/Audio │             │ - CoDi      │     │
│   │ │ Ollama  │ │             │             │             │ - SPEI      │     │
│   │ └─────────┘ │             │             │             │             │     │
│   └─────────────┘             └─────────────┘             └─────────────┘     │
│                                                                               │
│   DATOS                                                                       │
│   ─────                                                                       │
│                                                                               │
│   ┌─────────────────────────────────────────────────────────────────────┐    │
│   │                                                                     │    │
│   │  ┌─────────────┐   ┌─────────────┐   ┌─────────────┐               │    │
│   │  │ PostgreSQL  │   │    Redis    │   │  S3/MinIO   │               │    │
│   │  │(Multi-tenant│   │   (Cache,   │   │  (Files,    │               │    │
│   │  │   + RLS)    │   │  Sessions)  │   │   Images)   │               │    │
│   │  └─────────────┘   └─────────────┘   └─────────────┘               │    │
│   │                                                                     │    │
│   └─────────────────────────────────────────────────────────────────────┘    │
│                                                                               │
└───────────────────────────────────────────────────────────────────────────────┘

Componentes Principales

1. App Móvil (React Native)

apps/mobile/
├── src/
│   ├── components/          # Componentes reutilizables
│   │   ├── ui/              # Botones, inputs, cards
│   │   ├── pos/             # Componentes de punto de venta
│   │   └── common/          # Header, navigation, etc.
│   ├── screens/             # Pantallas
│   │   ├── auth/            # Login, registro
│   │   ├── pos/             # Punto de venta
│   │   ├── products/        # Catálogo
│   │   ├── inventory/       # Inventario
│   │   ├── customers/       # Clientes y fiados
│   │   ├── orders/          # Pedidos
│   │   ├── reports/         # Reportes
│   │   └── settings/        # Configuración
│   ├── services/            # API calls, storage
│   ├── hooks/               # Custom hooks
│   ├── store/               # Estado global (Zustand/Redux)
│   ├── utils/               # Helpers
│   └── navigation/          # React Navigation config
├── android/
├── ios/
└── package.json

Tecnologías clave:

  • React Native 0.73+
  • Expo (managed workflow para simplificar)
  • React Navigation 6
  • Zustand (estado global)
  • React Query (cache de API)
  • react-native-camera (scanner)
  • react-native-bluetooth-classic (terminales)

2. Web Dashboard (React)

apps/web/
├── src/
│   ├── components/
│   ├── pages/
│   │   ├── dashboard/
│   │   ├── sales/
│   │   ├── products/
│   │   ├── inventory/
│   │   ├── customers/
│   │   ├── reports/
│   │   ├── settings/
│   │   └── subscription/
│   ├── services/
│   ├── hooks/
│   ├── store/
│   └── utils/
├── public/
└── package.json

Tecnologías clave:

  • React 18
  • Vite
  • TailwindCSS
  • shadcn/ui
  • React Query
  • Recharts (gráficas)
  • React Router 6

3. Backend API (NestJS)

apps/backend/
├── src/
│   ├── modules/
│   │   ├── auth/            # Autenticación
│   │   ├── tenants/         # Multi-tenancy
│   │   ├── users/           # Usuarios
│   │   ├── products/        # Productos
│   │   ├── categories/      # Categorías
│   │   ├── sales/           # Ventas
│   │   ├── inventory/       # Inventario
│   │   ├── customers/       # Clientes
│   │   ├── fiados/          # Sistema de fiados
│   │   ├── orders/          # Pedidos
│   │   ├── payments/        # Pagos (integraciones)
│   │   ├── subscriptions/   # Suscripciones
│   │   ├── tokens/          # Tokens IA
│   │   ├── reports/         # Reportes
│   │   └── notifications/   # Push y WhatsApp
│   ├── common/
│   │   ├── decorators/
│   │   ├── guards/
│   │   ├── interceptors/
│   │   ├── filters/
│   │   └── pipes/
│   ├── database/
│   │   ├── entities/
│   │   └── migrations/
│   └── config/
├── test/
└── package.json

Tecnologías clave:

  • NestJS 10
  • TypeORM
  • PostgreSQL
  • Redis (cache, sessions, bull queues)
  • Passport (auth)
  • Class-validator
  • Swagger/OpenAPI

4. MCP Server (LLM Gateway)

apps/mcp-server/
├── src/
│   ├── providers/           # Adaptadores de LLM
│   │   ├── openai.ts
│   │   ├── anthropic.ts
│   │   ├── openrouter.ts
│   │   └── ollama.ts
│   ├── tools/               # Herramientas MCP
│   │   ├── sales.tools.ts
│   │   ├── products.tools.ts
│   │   ├── inventory.tools.ts
│   │   ├── customers.tools.ts
│   │   ├── fiados.tools.ts
│   │   ├── orders.tools.ts
│   │   └── reports.tools.ts
│   ├── prompts/             # System prompts
│   │   ├── owner.prompt.ts
│   │   └── customer.prompt.ts
│   ├── handlers/
│   │   ├── message.handler.ts
│   │   └── tool-call.handler.ts
│   └── config/
└── package.json

Tecnologías clave:

  • TypeScript
  • MCP SDK (@anthropic/mcp-sdk o custom)
  • Axios (llamadas a LLM APIs)
  • Token counting (tiktoken)

5. WhatsApp Service

apps/whatsapp-service/
├── src/
│   ├── webhooks/            # Recepción de mensajes
│   ├── handlers/
│   │   ├── text.handler.ts
│   │   ├── audio.handler.ts
│   │   ├── image.handler.ts
│   │   └── document.handler.ts
│   ├── services/
│   │   ├── meta-api.service.ts
│   │   ├── transcription.service.ts
│   │   ├── ocr.service.ts
│   │   └── tenant-detection.service.ts
│   ├── templates/           # Plantillas de mensajes
│   └── config/
└── package.json

Tecnologías clave:

  • NestJS
  • Meta WhatsApp Business API
  • Whisper API (transcripción)
  • Google Vision / Tesseract (OCR)

Base de Datos

Schema Multi-tenant

-- Tenants (negocios)
CREATE TABLE tenants (
    id UUID PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    slug VARCHAR(50) UNIQUE,
    phone VARCHAR(20) NOT NULL,
    business_type VARCHAR(50),
    whatsapp_config JSONB,
    subscription_status VARCHAR(20),
    subscription_plan VARCHAR(20),
    token_balance INTEGER DEFAULT 0,
    settings JSONB,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Todas las tablas tienen tenant_id y RLS
CREATE TABLE products (
    id UUID PRIMARY KEY,
    tenant_id UUID REFERENCES tenants(id),
    name VARCHAR(200) NOT NULL,
    barcode VARCHAR(50),
    price NUMERIC(10,2) NOT NULL,
    cost NUMERIC(10,2),
    category_id UUID,
    stock INTEGER DEFAULT 0,
    min_stock INTEGER DEFAULT 5,
    image_url VARCHAR(500),
    active BOOLEAN DEFAULT true,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

-- RLS Policy
ALTER TABLE products ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON products
    USING (tenant_id = current_setting('app.current_tenant_id')::UUID);

Schemas Principales

┌─────────────────────────────────────────────────────────────────────────┐
│                           DATABASE SCHEMAS                              │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│  public                                                                 │
│  ├── tenants                 # Negocios/comercios                       │
│  ├── users                   # Usuarios (dueños)                        │
│  └── tenant_settings         # Configuración por tenant                 │
│                                                                         │
│  catalog                                                                │
│  ├── products                # Productos                                │
│  ├── categories              # Categorías                               │
│  ├── product_variants        # Variantes/presentaciones                 │
│  └── product_templates       # Templates predefinidos                   │
│                                                                         │
│  sales                                                                  │
│  ├── sales                   # Ventas                                   │
│  ├── sale_items              # Items de venta                           │
│  ├── payments                # Pagos recibidos                          │
│  └── cash_registers          # Cortes de caja                           │
│                                                                         │
│  inventory                                                              │
│  ├── stock_movements         # Movimientos de inventario                │
│  ├── stock_alerts            # Alertas de stock bajo                    │
│  └── purchase_entries        # Entradas de compra                       │
│                                                                         │
│  customers                                                              │
│  ├── customers               # Clientes                                 │
│  ├── fiados                  # Fiados/créditos                          │
│  ├── fiado_payments          # Pagos de fiados                          │
│  └── orders                  # Pedidos de clientes                      │
│                                                                         │
│  subscriptions                                                          │
│  ├── plans                   # Planes disponibles                       │
│  ├── subscriptions           # Suscripciones activas                    │
│  ├── token_packages          # Paquetes de tokens                       │
│  ├── token_purchases         # Compras de tokens                        │
│  └── token_usage             # Consumo de tokens                        │
│                                                                         │
│  messaging                                                              │
│  ├── whatsapp_sessions       # Sesiones de chat                         │
│  ├── messages                # Historial de mensajes                    │
│  └── notifications           # Notificaciones enviadas                  │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘

Integraciones Externas

Pagos

Servicio Uso SDK/API
Stripe Suscripciones, tokens, OXXO stripe-node
Mercado Pago Terminal Bluetooth mercadopago SDK
Clip Terminal Bluetooth Clip SDK
CoDi QR de cobro Banxico API
SPEI Transferencias STP/Banxico

Comunicación

Servicio Uso API
Meta WhatsApp Business Mensajería principal Cloud API
Firebase Cloud Messaging Push notifications Admin SDK
Twilio (backup) SMS OTP REST API

IA/ML

Servicio Uso API
OpenRouter LLM barato OpenAI-compatible
OpenAI LLM premium REST API
Anthropic LLM alternativo REST API
Whisper Transcripción audio OpenAI API
Google Vision OCR de imágenes Vision API

Storage

Servicio Uso
AWS S3 / MinIO Imágenes, documentos
Cloudflare R2 CDN de assets

Seguridad

Autenticación

┌─────────────────────────────────────────────────────────────────────────┐
│                         FLUJO DE AUTENTICACIÓN                          │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│  1. Login con teléfono                                                  │
│     ┌─────────┐        ┌─────────┐        ┌─────────┐                  │
│     │  User   │ ────── │   API   │ ────── │ Twilio/ │                  │
│     │ (phone) │        │  (OTP)  │        │WhatsApp │                  │
│     └─────────┘        └─────────┘        └─────────┘                  │
│                                                                         │
│  2. Verificación OTP                                                    │
│     ┌─────────┐        ┌─────────┐        ┌─────────┐                  │
│     │  User   │ ────── │   API   │ ────── │  JWT    │                  │
│     │ (code)  │        │(verify) │        │(access+ │                  │
│     └─────────┘        └─────────┘        │refresh) │                  │
│                                           └─────────┘                  │
│                                                                         │
│  3. Acceso rápido (después de login inicial)                           │
│     - PIN de 4-6 dígitos                                               │
│     - Biométrico (huella/face)                                         │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘

Multi-tenancy

  • Row Level Security (RLS) en PostgreSQL
  • tenant_id en todas las tablas
  • Context variable: app.current_tenant_id
  • Middleware que extrae tenant del JWT

Encriptación

  • TLS 1.3 para tráfico
  • AES-256 para datos sensibles en reposo
  • Bcrypt para PINs

Infraestructura (Producción)

┌─────────────────────────────────────────────────────────────────────────┐
│                         INFRAESTRUCTURA AWS                             │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│  ┌─────────────────────────────────────────────────────────────────┐   │
│  │                         CloudFront                              │   │
│  │                     (CDN + WAF + SSL)                           │   │
│  └─────────────────────────────┬───────────────────────────────────┘   │
│                                │                                        │
│  ┌─────────────────────────────┴───────────────────────────────────┐   │
│  │                    Application Load Balancer                    │   │
│  └─────────────────────────────┬───────────────────────────────────┘   │
│                                │                                        │
│  ┌─────────────────────────────┴───────────────────────────────────┐   │
│  │                         ECS Fargate                             │   │
│  │  ┌───────────┐  ┌───────────┐  ┌───────────┐  ┌───────────┐    │   │
│  │  │  Backend  │  │    MCP    │  │ WhatsApp  │  │    Web    │    │   │
│  │  │   API     │  │  Server   │  │  Service  │  │  (Static) │    │   │
│  │  └───────────┘  └───────────┘  └───────────┘  └───────────┘    │   │
│  └─────────────────────────────────────────────────────────────────┘   │
│                                                                         │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐                    │
│  │  RDS        │  │ ElastiCache │  │     S3      │                    │
│  │ PostgreSQL  │  │   Redis     │  │   Bucket    │                    │
│  └─────────────┘  └─────────────┘  └─────────────┘                    │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘

Performance y Escalabilidad

Estrategias

  1. Caching agresivo

    • Redis para sesiones y datos frecuentes
    • React Query en clientes
  2. Lazy loading

    • Cargar productos por páginas
    • Imágenes con placeholder
  3. Offline-first

    • SQLite local en app móvil
    • Sync queue con reintentos
  4. CDN

    • Assets estáticos en CloudFront
    • Imágenes optimizadas

Métricas objetivo

Métrica Objetivo
Tiempo de respuesta API (p95) <200ms
Tiempo de carga app <3s
Disponibilidad 99.9%
Sync offline <30s después de reconexión

Versión: 1.0.0 Última actualización: 2026-01-04