- Backend NestJS con módulos de autenticación, inventario, créditos - Frontend React con dashboard y componentes UI - Base de datos PostgreSQL con migraciones - Tests E2E configurados - Configuración de Docker y deployment Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
504 lines
28 KiB
Markdown
504 lines
28 KiB
Markdown
# MiInventario - Arquitectura Tecnica
|
|
|
|
---
|
|
id: ARQ-MII-001
|
|
type: Architecture
|
|
status: Published
|
|
version: "1.0.0"
|
|
created_date: 2026-01-10
|
|
updated_date: 2026-01-10
|
|
simco_version: "4.0.0"
|
|
---
|
|
|
|
## Metadata
|
|
|
|
| Campo | Valor |
|
|
|-------|-------|
|
|
| **ID** | ARQ-MII-001 |
|
|
| **Tipo** | Architecture |
|
|
| **Estado** | Published |
|
|
| **Version** | 1.0.0 |
|
|
|
|
---
|
|
|
|
## 1. Vision General de Arquitectura
|
|
|
|
### 1.1 Tipo de Sistema
|
|
|
|
```
|
|
Tipo: SaaS Mobile-First
|
|
Nivel SIMCO: L2-A (Standalone)
|
|
Patron: Monorepo con Microservicios Ligeros
|
|
```
|
|
|
|
### 1.2 Diagrama de Alto Nivel
|
|
|
|
```
|
|
┌─────────────────────────────────────────────────────────────────────────────┐
|
|
│ ARQUITECTURA MIINVENTARIO │
|
|
├─────────────────────────────────────────────────────────────────────────────┤
|
|
│ │
|
|
│ ┌──────────────────┐ │
|
|
│ │ MOBILE APP │ │
|
|
│ │ React Native │ │
|
|
│ │ (Expo SDK 50) │ │
|
|
│ └────────┬─────────┘ │
|
|
│ │ HTTPS/REST │
|
|
│ ▼ │
|
|
│ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │
|
|
│ │ API GATEWAY │────▶│ AUTH SERVICE │────▶│ PostgreSQL │ │
|
|
│ │ (NestJS) │ │ (JWT/OTP) │ │ (Database) │ │
|
|
│ └────────┬─────────┘ └──────────────────┘ └──────────────────┘ │
|
|
│ │ │
|
|
│ ┌─────┴─────┬─────────────┬─────────────┬─────────────┐ │
|
|
│ ▼ ▼ ▼ ▼ ▼ │
|
|
│ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ │
|
|
│ │ Stores │ │ Videos │ │ Credits│ │Payments│ │Referral│ │
|
|
│ │ Module │ │ Module │ │ Module │ │ Module │ │ Module │ │
|
|
│ └────────┘ └───┬────┘ └────────┘ └───┬────┘ └────────┘ │
|
|
│ │ │ │
|
|
│ ┌────▼────┐ ┌────▼────┐ │
|
|
│ │ Bull │ │ Stripe │ │
|
|
│ │ (Queue) │ │ API │ │
|
|
│ └────┬────┘ └─────────┘ │
|
|
│ │ │
|
|
│ ┌─────────┼─────────┐ │
|
|
│ ▼ ▼ ▼ │
|
|
│ ┌────────┐ ┌────────┐ ┌────────┐ │
|
|
│ │ S3 │ │ IA │ │ Redis │ │
|
|
│ │(MinIO) │ │Provider│ │ Cache │ │
|
|
│ └────────┘ └────────┘ └────────┘ │
|
|
│ │
|
|
└─────────────────────────────────────────────────────────────────────────────┘
|
|
```
|
|
|
|
---
|
|
|
|
## 2. Stack Tecnologico
|
|
|
|
### 2.1 Frontend (Mobile)
|
|
|
|
| Componente | Tecnologia | Version | Justificacion |
|
|
|------------|------------|---------|---------------|
|
|
| Framework | React Native | 0.73+ | Cross-platform, comunidad grande |
|
|
| Build Tool | Expo | SDK 50+ | Simplifica desarrollo y deployment |
|
|
| Navigation | React Navigation | 6.x | Estandar de la industria |
|
|
| State | Zustand | 4.x | Ligero, simple, TypeScript nativo |
|
|
| Forms | React Hook Form | 7.x | Performance, validacion |
|
|
| HTTP | Axios | 1.x | Interceptors, reintentos |
|
|
| Storage | AsyncStorage | - | Persistencia local |
|
|
| Camera | expo-camera | - | Captura de video |
|
|
| Video | expo-av | - | Reproduccion y procesamiento |
|
|
|
|
### 2.2 Backend
|
|
|
|
| Componente | Tecnologia | Version | Justificacion |
|
|
|------------|------------|---------|---------------|
|
|
| Framework | NestJS | 10.x | Modular, TypeScript, escalable |
|
|
| Language | TypeScript | 5.x | Tipado estatico, DX |
|
|
| ORM | TypeORM | 0.3.x | Migraciones, decorators |
|
|
| Validation | class-validator | - | Decorators, DTOs |
|
|
| Auth | Passport | - | Estrategias JWT, OTP |
|
|
| Queue | Bull | 4.x | Jobs asincronos, Redis |
|
|
| Cache | Redis | 7.x | Cache, sessions, rate limit |
|
|
| Docs | Swagger | - | OpenAPI automatico |
|
|
|
|
### 2.3 Database
|
|
|
|
| Componente | Tecnologia | Version | Justificacion |
|
|
|------------|------------|---------|---------------|
|
|
| Primary | PostgreSQL | 15+ | ACID, JSON, RLS |
|
|
| Cache | Redis | 7.x | In-memory, pub/sub |
|
|
| Storage | MinIO (S3) | - | Videos, artefactos |
|
|
|
|
### 2.4 Infraestructura
|
|
|
|
| Componente | Tecnologia | Notas |
|
|
|------------|------------|-------|
|
|
| Containers | Docker | docker-compose local |
|
|
| CI/CD | GitHub Actions | Build, test, deploy |
|
|
| Hosting | TBD | DigitalOcean/AWS |
|
|
| CDN | Cloudflare | Cache, SSL |
|
|
|
|
---
|
|
|
|
## 3. Arquitectura de Capas
|
|
|
|
### 3.1 Diagrama de Capas
|
|
|
|
```
|
|
┌─────────────────────────────────────────────────────────────────┐
|
|
│ PRESENTATION LAYER │
|
|
│ ┌─────────────────────────────────────────────────────────────┐│
|
|
│ │ React Native App ││
|
|
│ │ - Screens (16) ││
|
|
│ │ - Components ││
|
|
│ │ - Hooks ││
|
|
│ │ - Stores (Zustand) ││
|
|
│ └─────────────────────────────────────────────────────────────┘│
|
|
├─────────────────────────────────────────────────────────────────┤
|
|
│ API LAYER │
|
|
│ ┌─────────────────────────────────────────────────────────────┐│
|
|
│ │ NestJS Controllers ││
|
|
│ │ - REST Endpoints (~60) ││
|
|
│ │ - DTOs & Validation ││
|
|
│ │ - Guards (Auth, Roles) ││
|
|
│ │ - Interceptors (Transform, Logging) ││
|
|
│ └─────────────────────────────────────────────────────────────┘│
|
|
├─────────────────────────────────────────────────────────────────┤
|
|
│ SERVICE LAYER │
|
|
│ ┌─────────────────────────────────────────────────────────────┐│
|
|
│ │ Business Logic ││
|
|
│ │ - AuthService - PaymentService ││
|
|
│ │ - StoreService - ReferralService ││
|
|
│ │ - VideoService - CreditService ││
|
|
│ │ - InventoryService - NotificationService ││
|
|
│ │ - IAProviderService - AdminService ││
|
|
│ └─────────────────────────────────────────────────────────────┘│
|
|
├─────────────────────────────────────────────────────────────────┤
|
|
│ INFRASTRUCTURE LAYER │
|
|
│ ┌─────────────────────────────────────────────────────────────┐│
|
|
│ │ - Repositories (TypeORM) ││
|
|
│ │ - Queue Processors (Bull) ││
|
|
│ │ - External Integrations (Stripe, IA, S3) ││
|
|
│ │ - Cache (Redis) ││
|
|
│ └─────────────────────────────────────────────────────────────┘│
|
|
├─────────────────────────────────────────────────────────────────┤
|
|
│ DATA LAYER │
|
|
│ ┌─────────────────────────────────────────────────────────────┐│
|
|
│ │ PostgreSQL (9 schemas, 30+ tables) ││
|
|
│ │ Redis (sessions, cache, queues) ││
|
|
│ │ S3/MinIO (videos, artefactos) ││
|
|
│ └─────────────────────────────────────────────────────────────┘│
|
|
└─────────────────────────────────────────────────────────────────┘
|
|
```
|
|
|
|
---
|
|
|
|
## 4. Modulos del Sistema
|
|
|
|
### 4.1 Modulos Backend
|
|
|
|
| Modulo | Responsabilidad | Dependencias |
|
|
|--------|-----------------|--------------|
|
|
| **auth** | Registro, login, OTP, JWT | users, notifications |
|
|
| **users** | Gestion de usuarios y perfiles | - |
|
|
| **stores** | Multi-tienda, roles | users |
|
|
| **videos** | Upload, procesamiento, storage | stores, queue |
|
|
| **inventory** | Sesiones, resultados, items | stores, videos |
|
|
| **ia-provider** | Abstraccion proveedores IA | - |
|
|
| **credits** | Wallet, transacciones, COGS | users, stores |
|
|
| **payments** | Stripe, OXXO, webhooks | credits |
|
|
| **referrals** | Codigos, arbol, rewards | users, credits |
|
|
| **notifications** | Push, in-app | users |
|
|
| **admin** | Panel SaaS, metricas | all |
|
|
|
|
### 4.2 Diagrama de Dependencias
|
|
|
|
```
|
|
┌─────────┐
|
|
│ admin │
|
|
└────┬────┘
|
|
│ depends on all
|
|
┌────────────────────┼────────────────────┐
|
|
│ │ │
|
|
▼ ▼ ▼
|
|
┌────────┐ ┌─────────┐ ┌──────────┐
|
|
│referral│ │payments │ │ stores │
|
|
└───┬────┘ └────┬────┘ └────┬─────┘
|
|
│ │ │
|
|
│ ┌────▼────┐ │
|
|
└─────────────▶│ credits │◀─────────────┘
|
|
└────┬────┘
|
|
│
|
|
┌────▼────┐
|
|
│ users │
|
|
└────┬────┘
|
|
│
|
|
┌────▼────┐
|
|
│ auth │
|
|
└─────────┘
|
|
```
|
|
|
|
---
|
|
|
|
## 5. Modelo de Datos
|
|
|
|
### 5.1 Schemas de Base de Datos
|
|
|
|
| Schema | Descripcion | Tablas Principales |
|
|
|--------|-------------|-------------------|
|
|
| auth | Autenticacion | users, sessions, otp_codes |
|
|
| tenancy | Multi-tienda | stores, store_users |
|
|
| inventory | Core negocio | inventory_sessions, inventory_items, products |
|
|
| media | Videos | videos, video_artifacts, frames |
|
|
| billing | Monetizacion | credit_wallets, credit_transactions, cogs_records |
|
|
| payments | Pagos | payment_orders, payment_methods |
|
|
| referrals | Referidos | referral_codes, referral_tree, referral_rewards |
|
|
| feedback | Retroalimentacion | corrections, ground_truth |
|
|
| admin | Administracion | settings, audit_logs |
|
|
|
|
### 5.2 Entidades Principales
|
|
|
|
```
|
|
┌─────────────────────────────────────────────────────────────────────────────┐
|
|
│ MODELO DE DATOS SIMPLIFICADO │
|
|
├─────────────────────────────────────────────────────────────────────────────┤
|
|
│ │
|
|
│ ┌─────────┐ 1 N ┌─────────┐ 1 N ┌──────────────────┐ │
|
|
│ │ User │───────▶│ Store │───────▶│ InventorySession │ │
|
|
│ └────┬────┘ └─────────┘ └────────┬─────────┘ │
|
|
│ │ │ │
|
|
│ │ 1 │ 1 │
|
|
│ ▼ ▼ │
|
|
│ ┌─────────┐ ┌─────────────┐ │
|
|
│ │ Wallet │ │InventoryItem│ │
|
|
│ └────┬────┘ └──────┬──────┘ │
|
|
│ │ │ │
|
|
│ │ N │ N │
|
|
│ ▼ ▼ │
|
|
│ ┌───────────┐ ┌─────────┐ │
|
|
│ │Transaction│ │ Product │ │
|
|
│ └───────────┘ └─────────┘ │
|
|
│ │
|
|
│ ┌─────────┐ 1 N ┌─────────────┐ │
|
|
│ │ Video │───────▶│VideoArtifact│ │
|
|
│ └─────────┘ └─────────────┘ │
|
|
│ │
|
|
│ ┌────────────┐ 1 N ┌──────────────┐ │
|
|
│ │ReferralCode│──────▶│ ReferralTree │ │
|
|
│ └────────────┘ └──────────────┘ │
|
|
│ │
|
|
└─────────────────────────────────────────────────────────────────────────────┘
|
|
```
|
|
|
|
### 5.3 Tabla de Entidades
|
|
|
|
| Entidad | Atributos Clave | Relaciones |
|
|
|---------|-----------------|------------|
|
|
| User | id, phone, email, role | 1:1 Wallet, 1:N Stores, 1:1 ReferralCode |
|
|
| Store | id, name, owner_id, giro | N:1 User, 1:N Sessions |
|
|
| InventorySession | id, store_id, status, video_id | N:1 Store, 1:1 Video, 1:N Items |
|
|
| InventoryItem | id, session_id, product_id, qty, confidence | N:1 Session, N:1 Product |
|
|
| Product | id, name, brand, barcode, category | 1:N Items |
|
|
| Video | id, session_id, s3_key, status | 1:1 Session, 1:N Artifacts |
|
|
| CreditWallet | id, user_id, balance | 1:1 User, 1:N Transactions |
|
|
| CreditTransaction | id, wallet_id, amount, type | N:1 Wallet |
|
|
| PaymentOrder | id, user_id, amount, status, provider | N:1 User |
|
|
| ReferralCode | id, user_id, code | 1:1 User, 1:N Tree |
|
|
| ReferralTree | id, referrer_id, referred_id, level | N:1 Code |
|
|
|
|
---
|
|
|
|
## 6. Flujos Principales
|
|
|
|
### 6.1 Flujo de Inventario
|
|
|
|
```
|
|
┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
|
|
│ Captura │──▶│ Upload │──▶│ Queue │──▶│ IA │──▶│ Reporte │
|
|
│ Video │ │ S3 │ │ Job │ │ Process │ │ Ready │
|
|
└─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘
|
|
│ │ │ │ │
|
|
▼ ▼ ▼ ▼ ▼
|
|
30-60s ~10s Async ~30-120s Push/Poll
|
|
guiado resiliente Bull job multi-frame notificacion
|
|
```
|
|
|
|
### 6.2 Flujo de Pago OXXO
|
|
|
|
```
|
|
┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
|
|
│ Selec- │──▶│ Crear │──▶│ Generar │──▶│ Pago │──▶│ Webhook │
|
|
│ Paquete │ │ Order │ │ Voucher │ │ en OXXO │ │ Confirm │
|
|
└─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘
|
|
│ │ │ │ │
|
|
▼ ▼ ▼ ▼ ▼
|
|
Usuario PENDING Stripe 24-72h PAID →
|
|
elige en DB OXXO ref expira acreditar
|
|
```
|
|
|
|
### 6.3 Flujo de Referidos
|
|
|
|
```
|
|
┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
|
|
│ Invita │──▶│ Registro│──▶│ Primera │──▶│ Primera │──▶│ Reward │
|
|
│ Amigo │ │ c/codigo│ │ Compra │ │ Sesion │ │ Unlock │
|
|
└─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘
|
|
│ │ │ │ │
|
|
▼ ▼ ▼ ▼ ▼
|
|
Comparte Tree Condicion Condicion +1 credito
|
|
codigo creado #1 ✓ #2 ✓ al referrer
|
|
```
|
|
|
|
---
|
|
|
|
## 7. Integraciones Externas
|
|
|
|
### 7.1 Mapa de Integraciones
|
|
|
|
| ID | Servicio | Proposito | Protocolo | Criticidad |
|
|
|----|----------|-----------|-----------|------------|
|
|
| INT-001 | Stripe | Pagos tarjeta | REST/Webhooks | P0 |
|
|
| INT-002 | Stripe OXXO | Pagos efectivo | REST/Webhooks | P0 |
|
|
| INT-003 | 7-Eleven | Pagos efectivo | Agregador | P1 |
|
|
| INT-004 | Firebase FCM | Push notifications | REST | P1 |
|
|
| INT-005 | S3/MinIO | Video storage | S3 API | P0 |
|
|
| INT-006 | IA Provider | Vision/Detection | REST | P0 |
|
|
|
|
### 7.2 Abstraccion de IA
|
|
|
|
```
|
|
┌─────────────────────────────────────────────────────────────────┐
|
|
│ IA PROVIDER ABSTRACTION │
|
|
├─────────────────────────────────────────────────────────────────┤
|
|
│ │
|
|
│ ┌─────────────────────────────────────────────────────────┐ │
|
|
│ │ IAProviderService │ │
|
|
│ │ - detectProducts(frames: Buffer[]): DetectionResult[] │ │
|
|
│ │ - getCost(): number │ │
|
|
│ │ - getProvider(): string │ │
|
|
│ └────────────────────────┬────────────────────────────────┘ │
|
|
│ │ │
|
|
│ ┌────────────┼────────────────┐ │
|
|
│ ▼ ▼ ▼ │
|
|
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
|
|
│ │ OpenAI │ │ Claude │ │ Custom │ │
|
|
│ │ Adapter │ │ Adapter │ │ Model │ │
|
|
│ └──────────┘ └──────────┘ └──────────┘ │
|
|
│ │
|
|
└─────────────────────────────────────────────────────────────────┘
|
|
```
|
|
|
|
---
|
|
|
|
## 8. Seguridad
|
|
|
|
### 8.1 Autenticacion
|
|
|
|
| Mecanismo | Uso |
|
|
|-----------|-----|
|
|
| JWT Access Token | Autenticacion API (15min TTL) |
|
|
| JWT Refresh Token | Renovacion (7d TTL) |
|
|
| OTP (SMS/Email) | Verificacion registro |
|
|
| API Keys | Webhooks, servicios internos |
|
|
|
|
### 8.2 Autorizacion
|
|
|
|
| Nivel | Implementacion |
|
|
|-------|----------------|
|
|
| Roles | USER, OWNER, OPERATOR, ADMIN |
|
|
| RLS | Row-Level Security en PostgreSQL |
|
|
| Guards | NestJS Guards por endpoint |
|
|
| Scopes | Permisos granulares por tienda |
|
|
|
|
### 8.3 Protecciones
|
|
|
|
| Amenaza | Mitigacion |
|
|
|---------|------------|
|
|
| SQL Injection | TypeORM parameterized queries |
|
|
| XSS | Sanitizacion, CSP headers |
|
|
| CSRF | Token validation |
|
|
| Rate Limiting | Redis + express-rate-limit |
|
|
| Brute Force | Account lockout, OTP cooldown |
|
|
|
|
---
|
|
|
|
## 9. Escalabilidad
|
|
|
|
### 9.1 Estrategias
|
|
|
|
| Componente | Estrategia |
|
|
|------------|------------|
|
|
| API | Horizontal scaling (containers) |
|
|
| Database | Connection pooling, read replicas |
|
|
| Queue | Redis cluster, worker pools |
|
|
| Storage | S3 con lifecycle policies |
|
|
| Cache | Redis cluster |
|
|
|
|
### 9.2 Metricas de Capacidad
|
|
|
|
| Metrica | Objetivo Inicial | Escalado |
|
|
|---------|------------------|----------|
|
|
| RPS | 100 | 1000+ |
|
|
| Usuarios concurrentes | 500 | 5000+ |
|
|
| Videos/hora | 100 | 1000+ |
|
|
| Storage | 100GB | 10TB+ |
|
|
|
|
---
|
|
|
|
## 10. Monitoreo y Observabilidad
|
|
|
|
### 10.1 Logging
|
|
|
|
| Nivel | Destino | Contenido |
|
|
|-------|---------|-----------|
|
|
| Application | stdout/file | Requests, errors, events |
|
|
| Database | PostgreSQL logs | Queries lentas |
|
|
| Queue | Bull dashboard | Jobs, failures |
|
|
|
|
### 10.2 Metricas
|
|
|
|
| Tipo | Herramienta | Metricas |
|
|
|------|-------------|----------|
|
|
| APM | TBD | Latency, throughput, errors |
|
|
| Business | Custom | Sessions, conversiones, COGS |
|
|
| Infrastructure | Docker stats | CPU, memory, disk |
|
|
|
|
### 10.3 Alertas
|
|
|
|
| Condicion | Severidad | Accion |
|
|
|-----------|-----------|--------|
|
|
| Error rate > 5% | Critical | PagerDuty |
|
|
| Latency P95 > 3s | Warning | Slack |
|
|
| Queue backlog > 100 | Warning | Slack |
|
|
| Disk > 80% | Warning | Email |
|
|
|
|
---
|
|
|
|
## 11. Ambientes
|
|
|
|
| Ambiente | Proposito | Infraestructura |
|
|
|----------|-----------|-----------------|
|
|
| Local | Desarrollo | Docker Compose |
|
|
| Staging | QA, demos | Single server |
|
|
| Production | Usuarios reales | HA cluster |
|
|
|
|
### 11.1 Puertos por Ambiente (Local)
|
|
|
|
| Servicio | Puerto |
|
|
|----------|--------|
|
|
| PostgreSQL | 5433 |
|
|
| Redis | 6380 |
|
|
| MinIO API | 9002 |
|
|
| MinIO Console | 9003 |
|
|
| Backend API | 3142 |
|
|
| Mobile (Expo) | 8082 |
|
|
|
|
---
|
|
|
|
## 12. ADRs Relacionados
|
|
|
|
| ADR | Titulo | Estado |
|
|
|-----|--------|--------|
|
|
| [ADR-0001](../97-adr/ADR-0001-modelo-creditos-tokens.md) | Modelo de Creditos | Aceptado |
|
|
| [ADR-0002](../97-adr/ADR-0002-procesamiento-asincrono.md) | Procesamiento Asincrono | Aceptado |
|
|
| [ADR-0003](../97-adr/ADR-0003-abstraccion-proveedores-ia.md) | Abstraccion IA | Aceptado |
|
|
| [ADR-0004](../97-adr/ADR-0004-pagos-efectivo-mexico.md) | Pagos en Efectivo | Aceptado |
|
|
|
|
---
|
|
|
|
## 13. Referencias
|
|
|
|
| Documento | Relacion |
|
|
|-----------|----------|
|
|
| [VISION-PROYECTO.md](./VISION-PROYECTO.md) | Contexto de negocio |
|
|
| [REQUERIMIENTOS-FUNCIONALES.md](./REQUERIMIENTOS-FUNCIONALES.md) | Funcionalidades |
|
|
| [MASTER_INVENTORY.yml](../../orchestration/inventarios/MASTER_INVENTORY.yml) | Inventario completo |
|
|
| [DATABASE_INVENTORY.yml](../../orchestration/inventarios/DATABASE_INVENTORY.yml) | Detalle DB |
|
|
|
|
---
|
|
|
|
**Ultima Actualizacion:** 2026-01-10
|
|
**Autor:** Tech Lead
|