# ANALISIS DE DEPENDENCIAS - FASE 4 (CAPVED)

**Fecha:** 2026-01-06
**Fase:** A (Analisis de Dependencias)
**Proyecto:** ERP-Core
**Orquestador:** Claude Code - Opus 4.5

---

## 1. ESTRUCTURA ACTUAL DEL PROYECTO

### 1.1 Backend - Estructura de Modulos

```
backend/src/
├── config/
│   ├── database.ts          # Configuracion TypeORM
│   ├── redis.ts             # Configuracion Redis (existe!)
│   ├── swagger.config.ts    # OpenAPI config
│   ├── typeorm.ts           # DataSource config
│   └── index.ts
│
├── shared/
│   ├── utils/logger.ts      # Winston logger
│   ├── types/index.ts       # Tipos compartidos
│   ├── services/base.service.ts  # Servicio base
│   ├── errors/index.ts      # Error handlers
│   └── middleware/
│       ├── auth.middleware.ts
│       ├── apiKeyAuth.middleware.ts
│       └── fieldPermissions.middleware.ts
│
├── modules/
│   ├── auth/                # MGN-001 ✅
│   │   ├── entities/        # 15 entidades
│   │   ├── services/        # auth, token, apiKeys
│   │   ├── *.controller.ts
│   │   └── *.routes.ts
│   │
│   ├── users/               # MGN-002 ✅
│   │   ├── users.service.ts
│   │   ├── users.controller.ts
│   │   └── users.routes.ts
│   │
│   ├── roles/               # MGN-003 ✅
│   ├── tenants/             # MGN-004 ✅
│   ├── companies/           # Parte de MGN-002 ✅
│   ├── partners/            # Parte de MGN-005 ✅
│   │
│   ├── financial/           # MGN-010 ⚠️ Parcial
│   ├── inventory/           # MGN-011 ⚠️ Parcial
│   ├── purchase/            # MGN-012 ⚠️ Scaffold
│   ├── sales/               # MGN-013 ⚠️ Scaffold
│   ├── projects/            # MGN-015 ⚠️ Scaffold
│   ├── crm/                 # MGN-014 ⚠️ Scaffold
│   ├── hr/                  # HR ⚠️ Scaffold
│   ├── reports/             # MGN-009 ⚠️ Scaffold
│   └── system/              # Notifications, etc ⚠️ Scaffold
│
└── app.ts, index.ts         # Entry points
```

### 1.2 Frontend - Estructura FSD

```
frontend/src/
├── app/
│   ├── layouts/             # DashboardLayout, AuthLayout
│   ├── providers/           # Context providers
│   └── router/              # React Router config
│
├── features/                # Features implementadas
│   ├── users/              # ✅ Completo
│   │   ├── api/
│   │   ├── components/
│   │   ├── hooks/
│   │   └── types/
│   ├── companies/          # ✅ Completo
│   ├── partners/           # ✅ Completo
│   └── tenants/            # ✅ Completo
│
├── pages/                  # 21 paginas
│   ├── auth/               # Login, Register, ForgotPassword
│   ├── dashboard/          # DashboardPage
│   ├── users/              # CRUD pages
│   ├── companies/          # CRUD pages
│   ├── partners/           # CRUD pages
│   └── tenants/            # CRUD pages
│
├── services/
│   └── api/                # Axios instance, interceptors
│
└── shared/
    ├── components/         # 23 componentes (atoms, molecules, organisms)
    ├── hooks/              # useDebounce, useLocalStorage, useMediaQuery
    ├── stores/             # 4 Zustand stores
    ├── types/              # Tipos compartidos
    └── utils/              # Formatters, cn()
```

### 1.3 Database - DDL Files

```
database/ddl/
├── 00-prerequisites.sql     # Extensions, functions base
├── 01-auth.sql              # Schema auth (tenants, users, roles)
├── 01-auth-extensions.sql   # OAuth, MFA, API Keys
├── 02-core.sql              # Schema core (partners, catalogs)
├── 03-analytics.sql         # Schema analytics (analytic accounts)
├── 04-financial.sql         # Schema financial (accounts, invoices)
├── 05-inventory.sql         # Schema inventory (products, stock)
├── 05-inventory-extensions.sql
├── 06-purchase.sql          # Schema purchase
├── 07-sales.sql             # Schema sales
├── 08-projects.sql          # Schema projects
├── 09-system.sql            # Schema system (notifications, activities)
├── 10-billing.sql           # Schema billing (SaaS)
├── 11-crm.sql               # Schema crm (leads, opportunities)
└── 12-hr.sql                # Schema hr (employees, contracts) ✅ EXISTE
```

**NOTA IMPORTANTE:** El HR Schema (12-hr.sql) YA EXISTE. El gap GAP-002 puede no ser valido.

---

## 2. DEPENDENCIAS ENTRE MODULOS

### 2.1 Backend - Grafo de Dependencias

```
                    ┌─────────────┐
                    │   config/   │
                    │  database   │
                    │   redis     │
                    └──────┬──────┘
                           │
                    ┌──────▼──────┐
                    │   shared/   │
                    │  services   │
                    │ middleware  │
                    └──────┬──────┘
                           │
        ┌──────────────────┼──────────────────┐
        │                  │                  │
        ▼                  ▼                  ▼
   ┌─────────┐        ┌─────────┐        ┌─────────┐
   │  auth   │◄───────│  users  │        │ tenants │
   │ MGN-001 │        │ MGN-002 │        │ MGN-004 │
   └────┬────┘        └────┬────┘        └────┬────┘
        │                  │                  │
        │                  │                  │
        └──────────────────┼──────────────────┘
                           │
                    ┌──────▼──────┐
                    │   roles     │
                    │   MGN-003   │
                    └──────┬──────┘
                           │
        ┌──────────────────┼──────────────────┐
        │                  │                  │
        ▼                  ▼                  ▼
   ┌─────────┐        ┌─────────┐        ┌─────────┐
   │partners │        │ core/   │        │catalogs │
   │ (core)  │        │countries│        │ MGN-005 │
   └────┬────┘        └─────────┘        └────┬────┘
        │                                     │
        └──────────────────┬──────────────────┘
                           │
                    ┌──────▼──────┐
                    │ financial   │
                    │  MGN-010    │
                    └──────┬──────┘
                           │
        ┌──────────────────┼──────────────────┐
        │                  │                  │
        ▼                  ▼                  ▼
   ┌─────────┐        ┌─────────┐        ┌─────────┐
   │inventory│        │ purchase│        │  sales  │
   │ MGN-011 │        │ MGN-012 │        │ MGN-013 │
   └─────────┘        └─────────┘        └─────────┘
```

### 2.2 Dependencias Criticas por Modulo

| Modulo | Depende de | Usado por |
|--------|------------|-----------|
| **config/** | - | Todos los modulos |
| **shared/** | config/ | Todos los modulos |
| **auth** | shared/, config/ | users, roles, tenants, todos |
| **users** | auth, shared/ | roles, tenants |
| **roles** | auth, users | Todos (permisos) |
| **tenants** | auth | Todos (multi-tenancy) |
| **partners** | auth, tenants | financial, sales, purchase |
| **catalogs** | auth, tenants | inventory, financial, sales, purchase |
| **financial** | auth, tenants, partners, catalogs | sales, purchase |
| **inventory** | auth, tenants, catalogs | sales, purchase |
| **sales** | auth, tenants, partners, catalogs, financial, inventory | - |
| **purchase** | auth, tenants, partners, catalogs, financial, inventory | - |

---

## 3. DEPENDENCIAS FRONTEND

### 3.1 Features Existentes vs Nuevas

```
EXISTENTES (reutilizables):
├── features/users/       → Base para features/catalogs/
├── features/companies/   → Patron similar
├── features/partners/    → Reutilizar estructura
└── features/tenants/     → Reutilizar estructura

NUEVAS A CREAR:
├── features/catalogs/    → Copiar estructura de features/users/
└── features/settings/    → Copiar estructura de features/tenants/
```

### 3.2 Componentes Compartidos Reutilizables

| Componente | Usado por Features Existentes | Requerido por Features Nuevas |
|------------|------------------------------|-------------------------------|
| DataTable | users, companies, partners, tenants | catalogs, settings |
| Modal | users, companies | catalogs, settings |
| Form components | Todos | catalogs, settings |
| Badge | users, partners, tenants | catalogs |
| Select | Todos | catalogs (CurrencySelect, CountrySelect) |
| Pagination | Todos | catalogs, settings |

### 3.3 Stores Existentes vs Nuevos

```yaml
EXISTENTES:
  - useAuthStore        # Autenticacion
  - useCompanyStore     # Empresa actual
  - useNotificationStore # Notificaciones toast
  - useUIStore          # Tema, sidebar

NUEVOS A CREAR:
  - useCurrencyStore    # Moneda actual
  - useCatalogCacheStore # Cache de catalogos
  - useSettingsStore    # Configuraciones
  - useFeatureFlagsStore # Feature flags
```

---

## 4. DEPENDENCIAS DATABASE

### 4.1 Orden de Ejecucion DDL

El orden de archivos DDL es critico por las FK:

```
1. 00-prerequisites.sql  # Extensions, funciones base
         │
         ▼
2. 01-auth.sql           # Tenants, users, roles (base de todo)
         │
         ▼
3. 01-auth-extensions.sql # OAuth, MFA (extiende auth)
         │
         ▼
4. 02-core.sql           # Partners, countries, currencies
         │
         ▼
5. 03-analytics.sql      # Analytic accounts (referencia core)
         │
         ▼
6. 04-financial.sql      # Accounts, invoices (referencia core, auth)
         │
         ▼
7. 05-inventory.sql      # Products, stock (referencia core, auth)
         │
         ▼
8. 06-purchase.sql       # Purchase orders (ref: financial, inventory)
         │
         ▼
9. 07-sales.sql          # Sales orders (ref: financial, inventory)
         │
         ▼
10. 08-projects.sql      # Projects, tasks (ref: hr)
         │
         ▼
11. 09-system.sql        # Notifications, activities
         │
         ▼
12. 10-billing.sql       # SaaS billing
         │
         ▼
13. 11-crm.sql           # CRM (ref: partners, sales)
         │
         ▼
14. 12-hr.sql            # HR (ref: auth.users)
```

### 4.2 FK Cross-Schema

| Origen | FK a Schema | Tabla Destino |
|--------|-------------|---------------|
| core.partners | auth | auth.tenants |
| financial.invoices | auth | auth.users (created_by) |
| financial.invoices | core | core.partners |
| inventory.products | core | core.product_categories |
| purchase.orders | core | core.partners (vendor) |
| sales.orders | core | core.partners (customer) |
| hr.employees | auth | auth.users |
| projects.tasks | hr | hr.employees (assignee) |

---

## 5. ARCHIVOS A MODIFICAR/CREAR POR SPRINT

### 5.1 Sprint 1 - Database + Tests Setup

**Database:**
```
VERIFICAR (ya existe):
- database/ddl/12-hr.sql       # Verificar contenido

CREAR:
- database/tests/rls-validation.sql
- database/tests/tenant-isolation.sql
- database/seeds/01-countries.sql
- database/seeds/02-currencies.sql
- database/seeds/03-states.sql
- database/seeds/04-uom.sql

MODIFICAR:
- database/ddl/09-system.sql   # Agregar track_field_changes()
```

**Backend:**
```
CREAR:
- backend/jest.config.js
- backend/tests/setup.ts
- backend/tests/factories/user.factory.ts
- backend/tests/factories/tenant.factory.ts
- backend/src/modules/auth/__tests__/auth.service.spec.ts
- backend/src/modules/auth/__tests__/auth.controller.spec.ts
- backend/src/modules/auth/__tests__/auth.integration.spec.ts

MODIFICAR:
- backend/package.json  # Agregar jest, supertest
- backend/tsconfig.json # Agregar paths para tests
```

**Frontend:**
```
CREAR:
- frontend/src/features/catalogs/
  ├── api/catalogs.api.ts
  ├── components/
  ├── hooks/
  ├── types/
  └── index.ts
- frontend/src/pages/catalogs/countries/
```

### 5.2 Sprint 2 - Tests + Frontend Catalogs

**Backend:**
```
CREAR:
- backend/src/modules/users/__tests__/
- backend/src/modules/roles/__tests__/
- backend/src/modules/tenants/__tests__/
- backend/src/modules/auth/services/permission-cache.service.ts

MODIFICAR:
- backend/src/config/redis.ts  # Ya existe, verificar
- backend/src/modules/auth/index.ts  # Exportar permission-cache
```

**Frontend:**
```
CREAR:
- frontend/src/pages/catalogs/currencies/
- frontend/src/pages/catalogs/uom/
- frontend/src/pages/catalogs/categories/
- frontend/src/shared/stores/useCurrencyStore.ts
- frontend/src/shared/stores/useCatalogCacheStore.ts

MODIFICAR:
- frontend/src/app/router/routes.tsx  # Agregar rutas catalogs
```

### 5.3 Sprint 3 - OAuth + Settings

**Backend:**
```
CREAR:
- backend/src/modules/auth/providers/google.provider.ts
- backend/src/modules/auth/providers/microsoft.provider.ts
- backend/src/modules/financial/__tests__/
- backend/src/modules/inventory/__tests__/

MODIFICAR:
- backend/src/modules/auth/auth.routes.ts  # Agregar rutas OAuth
- backend/src/modules/auth/auth.controller.ts  # Agregar endpoints OAuth
```

**Frontend:**
```
CREAR:
- frontend/src/features/settings/
  ├── api/
  ├── components/
  ├── hooks/
  ├── types/
  └── index.ts
- frontend/src/pages/settings/SystemSettingsPage.tsx

MODIFICAR:
- frontend/src/app/router/routes.tsx  # Agregar rutas settings
```

### 5.4 Sprint 4 - 2FA + Settings Completion

**Backend:**
```
CREAR:
- backend/src/modules/auth/services/mfa.service.ts
- backend/src/modules/auth/services/email-verification.service.ts
- backend/src/shared/services/email.service.ts

MODIFICAR:
- backend/src/modules/auth/auth.routes.ts  # Agregar rutas MFA
- backend/src/modules/auth/auth.controller.ts  # Agregar endpoints MFA
```

**Frontend:**
```
CREAR:
- frontend/src/pages/settings/TenantSettingsPage.tsx
- frontend/src/pages/settings/UserPreferencesPage.tsx
- frontend/src/pages/settings/FeatureFlagsPage.tsx
- frontend/src/shared/stores/useSettingsStore.ts
- frontend/src/shared/stores/useFeatureFlagsStore.ts
- frontend/src/shared/components/organisms/ThemeSelector.tsx

MODIFICAR:
- frontend/src/shared/stores/useUIStore.ts  # Integrar ThemeSelector
```

---

## 6. IMPACTO DE CAMBIOS

### 6.1 Archivos de Alto Impacto (Modificar con cuidado)

| Archivo | Impacto | Razon |
|---------|---------|-------|
| backend/src/app.ts | ALTO | Entry point, routing |
| backend/src/modules/auth/entities/*.ts | ALTO | Entidades compartidas |
| frontend/src/app/router/routes.tsx | ALTO | Routing global |
| frontend/src/shared/stores/useAuthStore.ts | ALTO | Estado de autenticacion |
| database/ddl/01-auth.sql | ALTO | Schema base |

### 6.2 Archivos de Bajo Riesgo (Safe to modify)

| Archivo | Impacto | Razon |
|---------|---------|-------|
| backend/src/modules/*/__tests__/*.ts | BAJO | Solo tests |
| frontend/src/features/catalogs/* | BAJO | Nuevo feature |
| frontend/src/features/settings/* | BAJO | Nuevo feature |
| database/seeds/*.sql | BAJO | Datos iniciales |

---

## 7. RESUMEN DE DEPENDENCIAS

### 7.1 Dependencias Externas (npm packages)

**Backend - Ya instalados:**
- express, typescript, typeorm, pg
- jsonwebtoken, bcryptjs
- zod, class-validator
- winston

**Backend - A instalar:**
- jest, supertest, ts-jest (tests)
- ioredis (Redis client - verificar si ya existe)
- otplib (TOTP for 2FA)
- nodemailer (email)
- passport, passport-google-oauth20, passport-microsoft (OAuth)

**Frontend - Ya instalados:**
- react, react-dom, react-router-dom
- zustand, axios
- react-hook-form, zod
- tailwindcss, lucide-react

**Frontend - A instalar:**
- Ninguno adicional requerido

### 7.2 Variables de Entorno Requeridas

```env
# Existentes (verificar)
DATABASE_URL=
JWT_SECRET=
REDIS_URL=

# Nuevas a agregar
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
MICROSOFT_CLIENT_ID=
MICROSOFT_CLIENT_SECRET=
SMTP_HOST=
SMTP_PORT=
SMTP_USER=
SMTP_PASS=
```

---

## 8. CONCLUSIONES

### 8.1 Hallazgos Importantes

1. **HR Schema YA EXISTE** (12-hr.sql) - El gap GAP-002 puede no ser valido
2. **Redis config YA EXISTE** (config/redis.ts) - Facilita permission cache
3. **Estructura FSD consistente** - Facilita crear nuevos features
4. **Dependencias bien definidas** - Orden de implementacion claro

### 8.2 Recomendaciones para Ejecucion

1. **Verificar 12-hr.sql** antes de crear HR Schema
2. **Verificar redis.ts** antes de implementar permission cache
3. **Seguir estructura existente** para nuevos features
4. **Respetar orden de DDL** en cualquier cambio de base de datos

### 8.3 Siguiente Fase

Proceder con **FASE 5: Refinamiento del Plan** incorporando estos hallazgos.

---

**Documento generado por:** ORQUESTADOR (Claude Code Opus 4.5)
**Sistema:** SIMCO + CAPVED
**Fase actual:** A (Analisis de Dependencias) - COMPLETADA
**Proxima fase:** FASE 5 - Refinamiento del Plan
