--- id: ET-ARQ-MCH-001 title: Arquitectura Tecnica MiChangarrito type: Specification subtype: Architecture status: Published priority: P0 module: core version: 2.1.0 created_date: 2026-01-04 updated_date: 2026-01-10 owner: Tech Lead tags: - arquitectura - tecnico - infraestructura --- # MiChangarrito - Arquitectura Tecnica | Campo | Valor | |-------|-------| | **ID** | ET-ARQ-MCH-001 | | **Tipo** | Especificacion Tecnica | | **Estado** | Published | | **Version** | 2.1.0 | | **Ultima Actualizacion** | 2026-01-10 | ## 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 │ │ Invoices │ │ │ │ │ │ Module │ │ Module │ │ Module │ │ Module │ │ │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │ │ │ │ │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ │ │ Subscript. │ │ Tokens │ │ Tenants │ │ Widgets │ │ │ │ │ │ Module │ │ 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 19.2.0 - Vite 7.2.4 - TailwindCSS 4.0.x - React Query - React Router 7.11.0 - Axios (HTTP client) - Lucide React (iconos) - clsx (utilidad CSS) ### 3. Backend API (NestJS) ``` apps/backend/ ├── src/ │ ├── modules/ │ │ ├── auth/ # Autenticación │ │ ├── tenants/ # Multi-tenancy │ │ ├── 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 │ │ ├── invoices/ # Facturación CFDI │ │ └── widgets/ # Widgets y atajos │ ├── 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 ```sql -- 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 (12 schemas) ``` ┌─────────────────────────────────────────────────────────────────────────┐ │ DATABASE SCHEMAS (12 total) │ ├─────────────────────────────────────────────────────────────────────────┤ │ │ │ public (4 tablas) │ │ ├── tenants # Negocios/comercios │ │ ├── tenant_configs # Configuracion por tenant │ │ ├── tenant_integration_credentials # Credenciales integraciones │ │ └── tenant_whatsapp_numbers # Numeros WhatsApp por tenant │ │ │ │ auth (3 tablas) │ │ ├── users # Usuarios (duenos, empleados) │ │ ├── sessions # Sesiones activas │ │ └── otp_codes # Codigos de verificacion │ │ │ │ catalog (3 tablas) │ │ ├── categories # Categorias │ │ ├── products # Productos │ │ └── product_templates # Templates predefinidos │ │ │ │ sales (8 tablas) │ │ ├── sales # Ventas │ │ ├── sale_items # Items de venta │ │ ├── payments # Pagos recibidos │ │ ├── daily_closures # Cortes de caja │ │ ├── virtual_accounts # Cuentas virtuales CoDi/SPEI │ │ ├── codi_transactions # Transacciones CoDi │ │ ├── spei_transactions # Transacciones SPEI │ │ └── payment_config # Configuracion de pagos │ │ │ │ inventory (2 tablas) │ │ ├── inventory_movements # Movimientos de inventario │ │ └── stock_alerts # Alertas de stock bajo │ │ │ │ customers (3 tablas) │ │ ├── customers # Clientes │ │ ├── fiados # Fiados/creditos │ │ └── fiado_payments # Pagos de fiados │ │ │ │ orders (2 tablas) │ │ ├── orders # Pedidos (WhatsApp, app, web) │ │ └── order_items # Items de pedido │ │ │ │ subscriptions (8 tablas) │ │ ├── plans # Planes disponibles │ │ ├── subscriptions # Suscripciones activas │ │ ├── token_packages # Paquetes de tokens │ │ ├── tenant_token_balance # Balance de tokens por tenant │ │ ├── token_usage # Consumo de tokens │ │ ├── referral_codes # Codigos de referidos │ │ ├── referrals # Referidos registrados │ │ └── referral_rewards # Recompensas por referidos │ │ │ │ messaging (3 tablas) │ │ ├── conversations # Sesiones de chat │ │ ├── messages # Historial de mensajes │ │ └── notifications # Notificaciones enviadas │ │ │ │ billing (5 tablas) │ │ ├── tax_configs # Configuraciones fiscales │ │ ├── invoices # Facturas CFDI │ │ ├── invoice_items # Items de factura │ │ ├── invoice_item_taxes # Impuestos por item │ │ └── invoice_history # Historial de facturas │ │ │ │ marketplace (6 tablas) │ │ ├── suppliers # Proveedores │ │ ├── supplier_products # Productos de proveedores │ │ ├── supplier_orders # Pedidos a proveedores │ │ ├── supplier_order_items # Items de pedido │ │ ├── supplier_reviews # Resenas de proveedores │ │ └── supplier_favorites # Favoritos │ │ │ │ integrations (2 tablas) │ │ ├── integration_configs # Configuracion por integracion │ │ └── integration_logs # Logs de integraciones │ │ │ └─────────────────────────────────────────────────────────────────────────┘ ``` **Total: 12 schemas, ~49 tablas** > **Referencia completa**: [ARQUITECTURA-DATABASE.md](../02-especificaciones/ARQUITECTURA-DATABASE.md) > **Inventario**: [DATABASE_INVENTORY.yml](../../orchestration/inventarios/DATABASE_INVENTORY.yml) ## 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 imagenes | Vision API | > **Documentacion detallada de integraciones**: > - [INT-001: WhatsApp Meta](../02-integraciones/INT-001-whatsapp-meta.md) > - [INT-002: Stripe](../02-integraciones/INT-002-stripe.md) > - [INT-003: OpenRouter](../02-integraciones/INT-003-openrouter.md) > - [INT-004: Mercado Pago](../02-integraciones/INT-004-mercadopago.md) ### 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 | ## ADRs Relacionados | ADR | Titulo | Estado | |-----|--------|--------| | [ADR-0001](../97-adr/ADR-0001-multi-tenant-architecture.md) | Multi-tenant Architecture | Accepted | | [ADR-0002](../97-adr/ADR-0002-whatsapp-first-approach.md) | WhatsApp-First Approach | Accepted | | [ADR-0003](../97-adr/ADR-0003-llm-agnostic-strategy.md) | LLM Agnostic Strategy | Accepted | ## Referencias ### Documentos Internos | Documento | Relacion | |-----------|----------| | [VISION-PROYECTO.md](./VISION-PROYECTO.md) | Contexto de negocio | | [REQUERIMIENTOS-FUNCIONALES.md](./REQUERIMIENTOS-FUNCIONALES.md) | Requisitos | | [ARQUITECTURA-DATABASE.md](../02-especificaciones/ARQUITECTURA-DATABASE.md) | Detalle BD | ### Inventarios | Inventario | Path | |------------|------| | MASTER_INVENTORY | [orchestration/inventarios/MASTER_INVENTORY.yml](../../orchestration/inventarios/MASTER_INVENTORY.yml) | | BACKEND_INVENTORY | [orchestration/inventarios/BACKEND_INVENTORY.yml](../../orchestration/inventarios/BACKEND_INVENTORY.yml) | | DATABASE_INVENTORY | [orchestration/inventarios/DATABASE_INVENTORY.yml](../../orchestration/inventarios/DATABASE_INVENTORY.yml) | --- **Sistema**: SIMCO v3.7.0 **Documento**: ET-ARQ-MCH-001 v2.1.0