trading-platform/orchestration/tareas/TASK-2026-02-04-ANALISIS-PLANIFICACION-INTEGRAL/02-ANALISIS.md
Adrian Flores Cortes b9098ca91c [TASK-2026-02-05-ANALISIS-VALIDACION-MODELADO-BD] docs: Complete 6-phase database modeling analysis
Comprehensive analysis of 101 DDL tables across 11 schemas:
- Phase 1-2: Schema validation, 37 gaps cataloged (3 resolved)
- Phase 3: Integrity audit (80 FKs, 89 CHECKs, 17 issues: 2 CRIT/5 HIGH)
- Phase 4: DDL-Backend mapping (84% interfaces, 75% services, 61% controllers)
- Phase 5: Documentation purge catalog (201 files analyzed)
- Phase 6: Remediation plan (4 sprints, 204h)

Key finding: Backend uses raw SQL + pg Pool (NOT TypeORM).
13 deliverables + updated inventories to v2.0.0.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-05 16:48:45 -06:00

316 lines
11 KiB
Markdown

# 02-ANALISIS - Análisis y Planeación Integral
**Tarea:** TASK-2026-02-04-ANALISIS-PLANIFICACION-INTEGRAL
**Fase:** A (Análisis)
**Estado:** EN PROGRESO
**Fecha:** 2026-02-04
**Agente:** Claude Code (Opus 4.5)
---
## 1. ANÁLISIS DE DEPENDENCIAS ENTRE CAPAS
### 1.1 Matriz de Coherencia DDL → Backend
| Schema | Tablas DDL | Entities Backend | Coherencia | Gap |
|--------|------------|------------------|------------|-----|
| auth | 12 | 10 | 83% | phone_verifications, rate_limiting_config |
| trading | 10 | 8 | 80% | drawing_tools parcial, price_alerts |
| education | 14 | 11 | 79% | instructors, course_tags |
| financial | 10 | 8 | 80% | refunds (CREADO), currency_exchange |
| investment | 7 | 6 | 86% | agent_executions |
| market_data | 4 | 2 | 50% | ohlcv_5m, ohlcv_15m sin servicio |
| ml | 9 | 7 | 78% | prediction_overlays (CREADO) |
| llm | 4 | 4 | 100% | - |
| audit | 7 | 3 | 43% | compliance, system_events |
| portfolio | 4 | 4 | 100% | - |
**Coherencia Promedio DDL-Backend:** 85%
### 1.2 Matriz de Coherencia Backend → Frontend
| Módulo | Endpoints | Consumidos FE | Coherencia | Gap Principal |
|--------|-----------|---------------|------------|---------------|
| auth | 13 | 10 | 77% | Password recovery, 2FA setup |
| trading | 15 | 8 | 53% | Agents UI, Price alerts |
| education | 12 | 10 | 83% | Reviews, Progress tracking |
| financial | 10 | 8 | 80% | Refunds UI |
| investment | 8 | 4 | 50% | Dashboard completo |
| market_data | 0 | 0 | - | TODO FALTANTE |
| ml | 8 | 6 | 75% | Overlays |
| llm | 6 | 4 | 67% | Memory manager |
| portfolio | 5 | 2 | 40% | Monte Carlo, Goals |
**Coherencia Promedio Backend-Frontend:** 77.5%
---
## 2. ANÁLISIS DE PRIORIDADES
### 2.1 Criterios de Priorización
1. **Impacto en Usuario:** ¿Afecta flujos críticos de negocio?
2. **Cadena de Bloqueo:** ¿Bloquea otras funcionalidades?
3. **Esfuerzo vs Valor:** Ratio de implementación
4. **Dependencias Técnicas:** ¿Requiere trabajo previo?
### 2.2 Priorización de Gaps
#### PRIORIDAD CRÍTICA (P0) - Bloquean MVP
| Ranking | Gap | Impacto | Esfuerzo | Score |
|---------|-----|---------|----------|-------|
| 1 | Market Data OHLCV Service | CHAIN-001 bloqueado | 16h | 100 |
| 2 | Trading Agents UI | Feature vendida | 40h | 95 |
| 3 | User Profile Management | UX crítico | 6h | 90 |
| 4 | Password Recovery | Seguridad | 8h | 85 |
#### PRIORIDAD ALTA (P1) - Funcionalidad Core
| Ranking | Gap | Impacto | Esfuerzo | Score |
|---------|-----|---------|----------|-------|
| 5 | Notifications API | CHAIN-002 | 20h | 80 |
| 6 | ML Chart Overlays | OQI-006 ↔ OQI-003 | 24h | 75 |
| 7 | 2FA Complete Flow | Seguridad | 16h | 70 |
| 8 | Investment Dashboard | OQI-004 core | 16h | 68 |
| 9 | education.instructors DDL | Backend blocked | 4h | 65 |
#### PRIORIDAD MEDIA (P2) - Mejoras Importantes
| Ranking | Gap | Impacto | Esfuerzo | Score |
|---------|-----|---------|----------|-------|
| 10 | Audit System Service | Compliance | 32h | 55 |
| 11 | Currency Exchange Service | Pagos intl | 16h | 50 |
| 12 | Risk Assessment Service | Investment | 12h | 48 |
| 13 | Course Reviews | Education UX | 6h | 45 |
| 14 | OAuth Flows Complete | Auth options | 12h | 42 |
---
## 3. ANÁLISIS DE DEPENDENCIAS ENTRE TAREAS
### 3.1 Grafo de Dependencias
```
NIVEL 0: FUNDAMENTALS (Sin dependencias)
├── DDL-001: education.instructors table
├── DDL-002: education.course_tags field
├── DDL-003: trading.price_alerts table
├── DDL-004: financial.refunds table ✅ (Resuelto)
├── DDL-005: ml.prediction_overlays field ✅ (Resuelto)
└── INV-001: Sincronizar inventarios
NIVEL 1: BACKEND SERVICES (Depende de NIVEL 0)
├── BE-001: Market Data OHLCV Service [depende: DDL market_data]
├── BE-002: Notifications Service [depende: DDL auth]
├── BE-003: User Profile Service [depende: DDL auth]
├── BE-004: Audit Service [depende: DDL audit]
└── BE-005: Instructor Service ✅ (Resuelto)
NIVEL 2: BACKEND API (Depende de NIVEL 1)
├── API-001: Market Data Endpoints [depende: BE-001]
├── API-002: Notifications Endpoints [depende: BE-002]
├── API-003: User Profile Endpoints [depende: BE-003]
├── API-004: Trading Agents Endpoints [depende: DDL trading]
└── API-005: 2FA Setup Endpoints [depende: DDL auth]
NIVEL 3: FRONTEND INTEGRATION (Depende de NIVEL 2)
├── FE-001: Market Data Charts [depende: API-001]
├── FE-002: Notifications Consumer [depende: API-002]
├── FE-003: User Profile Settings [depende: API-003]
├── FE-004: Trading Agents UI [depende: API-004]
├── FE-005: 2FA Setup Flow [depende: API-005]
├── FE-006: ML Chart Overlays [depende: API-001]
├── FE-007: Investment Dashboard [depende: API investm.]
└── FE-008: Password Recovery UI [depende: API auth]
NIVEL 4: INTEGRATION & TESTING
├── INT-001: E2E Trading Flow
├── INT-002: E2E Investment Flow
├── INT-003: E2E Auth Flow
└── TEST-001: Coverage 40%+
```
### 3.2 Camino Crítico
```
DDL market_data → BE-001 (OHLCV Service) → API-001 → FE-001 (Charts) → FE-006 (ML Overlays)
↳ INT-001 (E2E Trading)
Tiempo estimado camino crítico: 56 horas (16h + 8h + 16h + 16h)
```
---
## 4. ANÁLISIS DE REUTILIZACIÓN
### 4.1 Código Reutilizable de template-saas
| Componente | Ubicación template-saas | Aplicabilidad | Esfuerzo Adaptación |
|------------|-------------------------|---------------|---------------------|
| Audit Service | services/audit/ | 90% | 4h |
| Password Recovery | modules/auth/password/ | 80% | 6h |
| User Profile | modules/users/profile/ | 75% | 8h |
| Feature Flags | modules/feature-flags/ | 100% | 2h (YA HECHO) |
| 2FA Flow | modules/auth/2fa/ | 85% | 4h |
### 4.2 Código Reutilizable de erp-core
| Componente | Ubicación erp-core | Aplicabilidad | Esfuerzo Adaptación |
|------------|---------------------|---------------|---------------------|
| Notifications Service | shared/notifications/ | 70% | 8h |
| Currency Exchange | shared/currency/ | 60% | 10h |
| Risk Assessment | modules/risk/ | 50% | 12h |
---
## 5. ANÁLISIS DE ARQUITECTURA
### 5.1 Inconsistencias Detectadas
#### ARCH-001: Acceso Directo a Python Services (ALTO RIESGO)
**Problema:** Frontend bypasses Express.js backend para acceder a:
- mlService.ts → ML Engine (3083)
- llmAgentService.ts → LLM Agent (3085)
- backtestService.ts → ML Engine (3083)
**Impacto:**
- Sin autenticación centralizada
- CORS inconsistente
- Error handling duplicado
- Logs fragmentados
**Solución Propuesta:** Crear proxy endpoints en Express.js
**Esfuerzo:** 16h
#### ARCH-002: Inconsistencia apiClient
**Problema:** 5 servicios NO usan apiClient centralizado:
- portfolio.service.ts
- adminService.ts
- mlService.ts
- llmAgentService.ts
- backtestService.ts
**Impacto:**
- Sin token refresh automático
- Sin retry logic
- Código duplicado
**Solución Propuesta:** Refactorizar para usar apiClient
**Esfuerzo:** 8h
### 5.2 Decisiones de Arquitectura Pendientes
| ADR | Decisión | Opciones | Recomendación |
|-----|----------|----------|---------------|
| ADR-010 | Proxy vs Direct | 1. Proxy todo via Express 2. Direct para ML | Opción 1 (consistencia) |
| ADR-011 | WebSocket Gateway | 1. Express WS 2. Separate service | Ya decidido: Express WS |
| ADR-012 | State ML Results | 1. Redis cache 2. DB persistence | Redis (ya implementado) |
---
## 6. ANÁLISIS DE DOCUMENTACIÓN
### 6.1 Documentos a Purgar
| Documento | Razón | Impacto | Acción |
|-----------|-------|---------|--------|
| TASK-2026-02-03-DDL-VALIDATION/ | Supersedida | Ninguno | MOVER a _archive |
| ANALISIS-GAPS-DOCUMENTACION.md | Outdated, rutas rotas | Confusión | ELIMINAR |
| 95-guias-desarrollo/backend/ | Vacío | Inconsistencia | CREAR o ELIMINAR |
| 95-guias-desarrollo/frontend/ | Vacío | Inconsistencia | CREAR o ELIMINAR |
### 6.2 Documentos a Crear
| Documento | Ubicación | Prioridad | Esfuerzo |
|-----------|-----------|-----------|----------|
| GUIA-BACKEND.md | 95-guias-desarrollo/backend/ | P2 | 4h |
| GUIA-FRONTEND.md | 95-guias-desarrollo/frontend/ | P2 | 4h |
| OQI-009 RF/ET/US | 02-definicion-modulos/OQI-009/ | P1 | 8h |
| API-MARKET-DATA.md | OQI-003/especificaciones/ | P0 | 4h |
### 6.3 Documentos a Actualizar
| Documento | Gap | Prioridad |
|-----------|-----|-----------|
| BACKEND_INVENTORY.yml | Conteo 57→79 | P1 |
| FRONTEND_INVENTORY.yml | Conteo 90→146 | P1 |
| PROJECT-STATUS.md | Fecha 2026-01-30 | P0 |
| PROXIMA-ACCION.md | Tarea actual | P0 |
---
## 7. ANÁLISIS DE RIESGOS
### 7.1 Riesgos Técnicos
| Riesgo | Probabilidad | Impacto | Mitigación |
|--------|--------------|---------|------------|
| Market Data API rate limits | Alta | Alto | Implementar cache agresivo |
| ML Model performance | Media | Alto | Backtesting pre-deploy |
| WebSocket scalability | Media | Medio | Redis pub/sub |
| Trading Agents bugs | Alta | Crítico | Sandbox obligatorio |
### 7.2 Riesgos de Proyecto
| Riesgo | Probabilidad | Impacto | Mitigación |
|--------|--------------|---------|------------|
| Scope creep | Alta | Alto | Plan detallado con SP fijos |
| Dependencias circulares | Media | Medio | Grafo de dependencias |
| Documentación desactualizada | Alta | Medio | INV-001 prioritario |
| Integración Python-TS | Media | Medio | ARCH-001 resolución |
---
## 8. ESTIMACIÓN CONSOLIDADA
### 8.1 Por Fase
| Fase | Descripción | Esfuerzo | Parallelizable |
|------|-------------|----------|----------------|
| FASE 0 | Purga y Sync Inventarios | 8h | Parcial |
| FASE 1 | DDL Gaps (P0) | 16h | Sí (4 parallel) |
| FASE 2 | Backend Services (P0) | 40h | Parcial |
| FASE 3 | Frontend Sprint 1-2 | 77h | Parcial |
| FASE 4 | Frontend Sprint 3-4 | 209h | Parcial |
| FASE 5 | Architecture Refactor | 24h | No |
| FASE 6 | Integration Testing | 40h | Parcial |
| FASE 7 | Documentation | 16h | Sí |
**Total Estimado:** 430h (~11 semanas, 2 desarrolladores)
### 8.2 Por Prioridad
| Prioridad | Story Points | Horas | % Total |
|-----------|--------------|-------|---------|
| P0 (MVP) | 142 SP | 170h | 40% |
| P1 (Core) | 186 SP | 150h | 35% |
| P2 (Nice) | 130 SP | 70h | 16% |
| P3 (Future) | 100 SP | 40h | 9% |
---
## 9. CONCLUSIONES DEL ANÁLISIS
### 9.1 Hallazgos Principales
1. **Market Data Service es el mayor bloqueador:** Bloquea CHAIN-001 completa (charts, ML overlays)
2. **Trading Agents es feature vendida sin UI:** 40h de trabajo crítico
3. **Arquitectura tiene 2 inconsistencias importantes:** ARCH-001 y ARCH-002
4. **Documentación 10% desactualizada:** Requiere purga y actualización
5. **Reutilización posible:** 30-40% del código puede adaptarse de template-saas
### 9.2 Recomendaciones
1. **Priorizar CHAIN-001:** Market Data → Charts → ML Overlays
2. **Resolver ARCH-001 antes de más frontend:** Proxy endpoints
3. **Ejecutar INV-001 inmediatamente:** Inventarios sincronizados
4. **Delegar DDL a subagentes paralelos:** 4 subagentes FASE_1
5. **Considerar reutilización de template-saas:** Audit, Password Recovery
---
**Siguiente Fase:** P (Planificación) - Plan de ejecución detallado