# ==============================================================================
# DDL-Backend Coherence Analysis - Trading Platform
# Generated: 2026-01-27
# ==============================================================================
version: "1.0.0"
project: "trading-platform"
generated_at: "2026-01-27T12:30:00Z"

summary:
  total_schemas: 10
  total_tables: 89
  total_backend_services: 36
  coherence_status:
    completo: 8  # Schemas con servicios completos
    parcial: 2   # Schemas con servicios parciales
    sin_servicio: 0  # Schemas sin servicios

overall_assessment:
  status: "BUENO"
  coverage: "~85%"
  priority_gaps: "P1-P2"
  notes: |
    La mayoría de las tablas DDL tienen servicios backend correspondientes.
    Los gaps identificados son principalmente en servicios de auditoría,
    notificaciones y algunos endpoints faltantes en módulos existentes.

# ==============================================================================
# Schema-by-Schema Analysis
# ==============================================================================

schemas:
  auth:
    status: "completo"
    coverage: "95%"
    description: "Sistema de autenticación y autorización"
    total_tables: 13
    tables_with_services: 12
    tables_without_services: 1

    services:
      - name: "token.service.ts"
        tables_accessed:
          - auth.users
          - auth.sessions
        methods:
          - createSession
          - revokeSession
          - validateToken
          - refreshAccessToken
        interfaces:
          - User
          - Session
          - AuthTokens
          - JWTPayload
        status: "completo"
        notes: "Servicio completo con token rotation y session cache"

      - name: "oauth.service.ts"
        tables_accessed:
          - auth.users
          - auth.oauth_accounts
        methods:
          - linkOAuthAccount
          - unlinkOAuthAccount
          - getOAuthAccounts
        interfaces:
          - OAuthAccount
          - OAuthProvider
        status: "completo"

      - name: "email.service.ts"
        tables_accessed:
          - auth.users
          - auth.email_verifications
        methods:
          - sendVerificationEmail
          - verifyEmail
          - resendVerification
        status: "completo"

      - name: "phone.service.ts"
        tables_accessed:
          - auth.users
          - auth.phone_verifications
        methods:
          - sendPhoneVerification
          - verifyPhoneCode
        status: "completo"

      - name: "twofa.service.ts"
        tables_accessed:
          - auth.users
        methods:
          - enableMFA
          - disableMFA
          - verifyTOTP
        status: "completo"

    gaps:
      - table: "auth_logs"
        priority: "P2"
        description: "No hay servicio dedicado para auth_logs, pero se registra via logger"
        impact: "bajo"
        recommendation: "Crear authAudit.service.ts para consultas de logs"

      - table: "login_attempts"
        priority: "P2"
        description: "No hay servicio para consultar login_attempts"
        impact: "medio"
        recommendation: "Agregar métodos en token.service.ts"

      - table: "rate_limiting_config"
        priority: "P3"
        description: "Configuración de rate limiting no expuesta en API"
        impact: "bajo"
        recommendation: "Admin endpoint para configurar rate limits"

      - table: "notifications"
        priority: "P1"
        description: "Tabla de notificaciones sin servicio backend"
        impact: "alto"
        recommendation: "Crear notification.service.ts en módulo notifications"

      - table: "user_push_tokens"
        priority: "P1"
        description: "Sin servicio para gestionar push tokens"
        impact: "alto"
        recommendation: "Integrar en notification.service.ts"

  education:
    status: "completo"
    coverage: "90%"
    description: "Sistema educativo y gamification"
    total_tables: 15
    tables_with_services: 14
    tables_without_services: 1

    services:
      - name: "course.service.ts"
        tables_accessed:
          - education.categories
          - education.courses
          - education.modules
          - education.lessons
        methods:
          - getCourses
          - getCourseById
          - getCourseModules
          - getLessonContent
        interfaces:
          - Course
          - CourseModule
          - Lesson
          - Category
        status: "completo"

      - name: "enrollment.service.ts"
        tables_accessed:
          - education.enrollments
          - education.progress
          - education.certificates
        methods:
          - enrollUser
          - getEnrollments
          - updateProgress
          - issueCertificate
        status: "completo"

      - name: "quiz.service.ts"
        tables_accessed:
          - education.quizzes
          - education.quiz_questions
          - education.quiz_attempts
        methods:
          - getQuiz
          - submitQuizAttempt
          - getQuizResults
        status: "completo"

      - name: "gamification.service.ts"
        tables_accessed:
          - education.user_gamification_profile
          - education.user_achievements
          - education.user_activity_log
        methods:
          - getUserProfile
          - awardXP
          - unlockAchievement
          - updateStreak
        status: "completo"

      - name: "video.service.ts"
        tables_accessed:
          - education.videos
        methods:
          - getVideoById
          - getVideosByLesson
          - trackVideoProgress
        status: "completo"

    gaps:
      - table: "course_reviews"
        priority: "P2"
        description: "Sin servicio para gestionar reviews de cursos"
        impact: "medio"
        recommendation: "Agregar métodos en course.service.ts para reviews"

  trading:
    status: "completo"
    coverage: "100%"
    description: "Sistema de trading y bots"
    total_tables: 10
    tables_with_services: 10
    tables_without_services: 0

    services:
      - name: "order.service.ts"
        tables_accessed:
          - trading.orders
          - trading.trades
        methods:
          - createOrder
          - cancelOrder
          - getOrderById
          - getUserOrders
          - updateOrderStatus
        interfaces:
          - Order
          - OrderType
          - OrderSide
          - OrderStatus
        status: "completo"
        notes: "Servicio completo con soporte para paper y live trading"

      - name: "binance.service.ts"
        tables_accessed:
          - trading.symbols
          - trading.orders
          - trading.positions
        methods:
          - placeOrder
          - getPosition
          - syncOrderStatus
        status: "completo"

      - name: "watchlist.service.ts"
        tables_accessed:
          - trading.watchlists
          - trading.watchlist_items
        methods:
          - createWatchlist
          - addSymbol
          - removeSymbol
          - getUserWatchlists
        status: "completo"

      - name: "paper-trading.service.ts"
        tables_accessed:
          - trading.bots
          - trading.orders
          - trading.positions
          - trading.paper_balances
        methods:
          - createPaperBot
          - executePaperOrder
          - getPaperBalance
        status: "completo"

      - name: "market.service.ts"
        tables_accessed:
          - trading.symbols
        methods:
          - getTicker
          - getSymbolInfo
          - validateSymbol
        status: "completo"

      - name: "indicators.service.ts"
        tables_accessed: []
        methods:
          - calculateRSI
          - calculateMACD
          - calculateEMA
        status: "completo"
        notes: "Servicio de indicadores técnicos (no requiere tablas)"

      - name: "alerts.service.ts"
        tables_accessed:
          - trading.signals
        methods:
          - createAlert
          - checkAlerts
          - sendAlertNotification
        status: "completo"

      - name: "export.service.ts"
        tables_accessed:
          - trading.orders
          - trading.trades
        methods:
          - exportTrades
          - exportOrders
          - generateReport
        status: "completo"

      - name: "cache.service.ts"
        tables_accessed: []
        methods:
          - cacheMarketData
          - getCachedData
        status: "completo"
        notes: "Servicio de caché para datos de mercado"

    gaps: []

  investment:
    status: "completo"
    coverage: "90%"
    description: "Sistema de inversiones PAMM"
    total_tables: 9
    tables_with_services: 8
    tables_without_services: 1

    services:
      - name: "product.service.ts"
        tables_accessed:
          - investment.products
          - investment.daily_performance
        methods:
          - getProducts
          - getProductById
          - getProductPerformance
        interfaces:
          - InvestmentProduct
          - TradingAgent
          - RiskProfile
        status: "completo"

      - name: "account.service.ts"
        tables_accessed:
          - investment.accounts
          - investment.transactions
          - investment.withdrawal_requests
        methods:
          - createAccount
          - getUserAccounts
          - deposit
          - requestWithdrawal
          - getAccountSummary
        interfaces:
          - InvestmentAccount
          - AccountStatus
        status: "completo"

      - name: "transaction.service.ts"
        tables_accessed:
          - investment.transactions
          - investment.distributions
        methods:
          - getTransactionHistory
          - getDistributions
          - calculateROI
        status: "completo"

    gaps:
      - table: "risk_questionnaire"
        priority: "P2"
        description: "Sin servicio dedicado para risk questionnaire"
        impact: "medio"
        recommendation: "Crear riskAssessment.service.ts"

      - table: "distribution_runs"
        priority: "P3"
        description: "Sin servicio para gestionar distribution runs"
        impact: "bajo"
        recommendation: "Agregar en transaction.service.ts (admin only)"

  financial:
    status: "completo"
    coverage: "85%"
    description: "Sistema financiero, wallets y pagos"
    total_tables: 10
    tables_with_services: 8
    tables_without_services: 2

    services:
      - name: "wallet.service.ts"
        tables_accessed:
          - financial.wallets
          - financial.wallet_transactions
          - financial.wallet_limits
        methods:
          - getOrCreateWallet
          - getWalletBalance
          - createDeposit
          - createWithdrawal
          - getTransactionHistory
        interfaces:
          - Wallet
          - WalletTransaction
          - TransactionType
        status: "completo"

      - name: "stripe.service.ts"
        tables_accessed:
          - financial.customers
          - financial.payment_methods
          - financial.payments
          - financial.invoices
        methods:
          - createCustomer
          - attachPaymentMethod
          - createPaymentIntent
          - createInvoice
        status: "completo"

      - name: "subscription.service.ts"
        tables_accessed:
          - financial.subscriptions
          - financial.invoices
        methods:
          - createSubscription
          - cancelSubscription
          - upgradeSubscription
          - getSubscriptionHistory
        status: "completo"

    gaps:
      - table: "currency_exchange_rates"
        priority: "P2"
        description: "Sin servicio para gestionar exchange rates"
        impact: "medio"
        recommendation: "Crear currencyExchange.service.ts con API externa"

      - table: "wallet_audit_log"
        priority: "P3"
        description: "Auditoría de wallets sin servicio dedicado"
        impact: "bajo"
        recommendation: "Se registra automáticamente via triggers, consultas en wallet.service.ts"

  portfolio:
    status: "completo"
    coverage: "100%"
    description: "Gestión de portafolios"
    total_tables: 5
    tables_with_services: 5
    tables_without_services: 0

    services:
      - name: "portfolio.service.ts"
        tables_accessed:
          - portfolio.portfolios
          - portfolio.portfolio_allocations
          - portfolio.portfolio_goals
          - portfolio.rebalance_history
          - portfolio.portfolio_snapshots
        methods:
          - createPortfolio
          - getUserPortfolios
          - updateAllocations
          - rebalancePortfolio
          - setGoal
          - getPerformance
        interfaces:
          - Portfolio
          - Allocation
          - Goal
          - RebalanceAction
        status: "completo"

    gaps: []

  ml:
    status: "completo"
    coverage: "100%"
    description: "Sistema de Machine Learning y predicciones"
    total_tables: 11
    tables_with_services: 11
    tables_without_services: 0

    services:
      - name: "ml-model-registry.service.ts"
        tables_accessed:
          - ml.models
          - ml.model_versions
        methods:
          - registerModel
          - getModels
          - getModelVersions
          - promoteModel
        status: "completo"

      - name: "ml-integration.service.ts"
        tables_accessed:
          - ml.predictions
          - ml.prediction_outcomes
          - ml.llm_predictions
          - ml.llm_prediction_outcomes
        methods:
          - getPrediction
          - savePrediction
          - evaluatePrediction
        status: "completo"

      - name: "ml-data.service.ts"
        tables_accessed:
          - ml.feature_store
        methods:
          - getFeatures
          - saveFeatures
        status: "completo"

      - name: "ml-backtest.service.ts"
        tables_accessed:
          - ml.backtest_runs
        methods:
          - runBacktest
          - getBacktestResults
        status: "completo"

      - name: "ml-signal-stream.service.ts"
        tables_accessed:
          - ml.llm_signals
          - ml.llm_decisions
          - ml.risk_events
        methods:
          - streamSignals
          - recordDecision
          - logRiskEvent
        status: "completo"

      - name: "ml-overlay.service.ts"
        tables_accessed:
          - ml.predictions
          - ml.llm_predictions
        methods:
          - getOverlayData
          - combineSignals
        status: "completo"

    gaps: []

  llm:
    status: "completo"
    coverage: "100%"
    description: "Sistema de conversación con LLM"
    total_tables: 5
    tables_with_services: 5
    tables_without_services: 0

    services:
      - name: "llm.service.ts"
        tables_accessed:
          - llm.conversations
          - llm.messages
          - llm.user_preferences
          - llm.user_memory
          - llm.embeddings
        methods:
          - createConversation
          - sendMessage
          - getConversationHistory
          - updatePreferences
          - saveMemory
          - searchSimilarMessages
        interfaces:
          - Conversation
          - Message
          - MessageRole
          - UserPreferences
        status: "completo"

    gaps: []

  market_data:
    status: "parcial"
    coverage: "50%"
    description: "Datos de mercado OHLCV"
    total_tables: 4
    tables_with_services: 2
    tables_without_services: 2

    services:
      - name: "market.service.ts (módulo trading)"
        tables_accessed:
          - market_data.tickers
        methods:
          - getTicker
          - getSymbolInfo
        status: "completo"
        notes: "Servicio existe pero está en módulo trading, no market_data"

    gaps:
      - table: "ohlcv_5m"
        priority: "P1"
        description: "Sin servicio backend para consultar OHLCV 5m"
        impact: "alto"
        recommendation: "Crear marketData.service.ts en nuevo módulo market-data"

      - table: "ohlcv_15m"
        priority: "P1"
        description: "Sin servicio backend para consultar OHLCV 15m"
        impact: "alto"
        recommendation: "Crear marketData.service.ts en nuevo módulo market-data"

      - table: "staging"
        priority: "P2"
        description: "Tabla staging sin servicio (usada por data-service Python)"
        impact: "bajo"
        recommendation: "Mantener en data-service Python, no requiere servicio TypeScript"

  audit:
    status: "parcial"
    coverage: "30%"
    description: "Sistema de auditoría y logs"
    total_tables: 7
    tables_with_services: 0
    tables_without_services: 7

    services: []

    gaps:
      - table: "audit_logs"
        priority: "P2"
        description: "Sin servicio dedicado para audit_logs"
        impact: "medio"
        recommendation: "Crear audit.service.ts para consultas (los logs se registran via triggers)"

      - table: "security_events"
        priority: "P2"
        description: "Sin servicio para consultar security events"
        impact: "medio"
        recommendation: "Crear securityAudit.service.ts"

      - table: "system_events"
        priority: "P3"
        description: "Sin servicio para system events"
        impact: "bajo"
        recommendation: "Agregar en audit.service.ts"

      - table: "trading_audit"
        priority: "P2"
        description: "Sin servicio para consultar trading audit"
        impact: "medio"
        recommendation: "Agregar métodos en trading/order.service.ts"

      - table: "api_request_logs"
        priority: "P3"
        description: "Sin servicio para api request logs"
        impact: "bajo"
        recommendation: "Se registra via middleware, consultas en audit.service.ts"

      - table: "data_access_logs"
        priority: "P3"
        description: "Sin servicio para data access logs"
        impact: "bajo"
        recommendation: "Agregar en audit.service.ts"

      - table: "compliance_logs"
        priority: "P2"
        description: "Sin servicio para compliance logs"
        impact: "medio"
        recommendation: "Crear compliance.service.ts (futuro KYC/AML)"

# ==============================================================================
# Gap Summary by Priority
# ==============================================================================

gap_summary:
  total_gaps: 18
  by_priority:
    P0: 0
    P1: 4
    P2: 10
    P3: 4

  P1_critical_gaps:
    - schema: "market_data"
      table: "ohlcv_5m"
      recommendation: "Crear marketData.service.ts"
      effort: "medio"

    - schema: "market_data"
      table: "ohlcv_15m"
      recommendation: "Integrar en marketData.service.ts"
      effort: "pequeño"

    - schema: "auth"
      table: "notifications"
      recommendation: "Crear notification.service.ts"
      effort: "medio"

    - schema: "auth"
      table: "user_push_tokens"
      recommendation: "Integrar en notification.service.ts"
      effort: "pequeño"

  P2_important_gaps:
    - schema: "audit"
      tables: "audit_logs, security_events, trading_audit, compliance_logs"
      recommendation: "Crear audit.service.ts + securityAudit.service.ts"
      effort: "grande"

    - schema: "financial"
      table: "currency_exchange_rates"
      recommendation: "Crear currencyExchange.service.ts"
      effort: "medio"

    - schema: "investment"
      table: "risk_questionnaire"
      recommendation: "Crear riskAssessment.service.ts"
      effort: "medio"

    - schema: "education"
      table: "course_reviews"
      recommendation: "Agregar en course.service.ts"
      effort: "pequeño"

    - schema: "auth"
      table: "login_attempts"
      recommendation: "Agregar en token.service.ts"
      effort: "pequeño"

# ==============================================================================
# Interface Coherence
# ==============================================================================

interface_coherence:
  status: "BUENO"
  notes: |
    La mayoría de los servicios tienen interfaces TypeScript bien definidas
    que corresponden a las tablas DDL. Los enums están correctamente mapeados.

  well_defined_interfaces:
    - auth.types.ts (User, Session, AuthTokens)
    - order.types.ts (Order, OrderType, OrderSide, OrderStatus)
    - payments.types.ts (Wallet, Transaction, Payment)
    - investment.types.ts (Account, Product, Distribution)

  missing_interfaces:
    - Audit types (AuditLog, SecurityEvent)
    - Market data types (OHLCV, Ticker)
    - Notification types

# ==============================================================================
# Endpoint Coverage
# ==============================================================================

endpoint_coverage:
  status: "BUENO"
  notes: |
    Los controladores exponen endpoints REST para la mayoría de los servicios.
    Algunos servicios de auditoría y notificaciones no tienen endpoints.

  controllers_present:
    - auth.controller.ts
    - trading.controller.ts
    - investment.controller.ts
    - payments.controller.ts
    - education.controller.ts
    - portfolio.controller.ts
    - ml.controller.ts
    - llm.controller.ts

  missing_controllers:
    - audit.controller.ts (P2)
    - notification.controller.ts (P1)
    - market-data.controller.ts (P1)

# ==============================================================================
# Recommendations
# ==============================================================================

recommendations:
  immediate_actions:
    - action: "Crear marketData.service.ts"
      priority: "P1"
      effort: "medio"
      impact: "alto"
      tables: ["market_data.ohlcv_5m", "market_data.ohlcv_15m"]

    - action: "Crear notification.service.ts"
      priority: "P1"
      effort: "medio"
      impact: "alto"
      tables: ["auth.notifications", "auth.user_push_tokens"]

  short_term_actions:
    - action: "Crear audit.service.ts y securityAudit.service.ts"
      priority: "P2"
      effort: "grande"
      impact: "medio"
      tables: ["audit.audit_logs", "audit.security_events", "audit.trading_audit"]

    - action: "Crear currencyExchange.service.ts"
      priority: "P2"
      effort: "medio"
      impact: "medio"
      tables: ["financial.currency_exchange_rates"]

    - action: "Agregar course reviews en course.service.ts"
      priority: "P2"
      effort: "pequeño"
      impact: "bajo"
      tables: ["education.course_reviews"]

  long_term_actions:
    - action: "Crear compliance.service.ts para KYC/AML"
      priority: "P3"
      effort: "grande"
      impact: "bajo"
      tables: ["audit.compliance_logs"]

# ==============================================================================
# Validation
# ==============================================================================

validation:
  methodology: |
    1. Revisión de 89 tablas DDL en 10 schemas
    2. Análisis de 36 servicios backend en apps/backend/src/modules
    3. Verificación de interfaces TypeScript
    4. Mapeo de endpoints REST en controladores
    5. Identificación de gaps por prioridad

  validation_date: "2026-01-27"
  validated_by: "Claude Code - FASE 1.2"
  next_review: "2026-02-15"
