# PLAN DE EXPANSION DEL BACKEND

**Proyecto:** ERP Generic
**Fecha:** 2025-11-24
**Version:** 1.0.0
**Autor:** Architecture-Analyst
**Estado:** ✅ COMPLETADO (2025-11-24)

---

## Resumen Ejecutivo

Este documento detalla el plan para expandir el backend del ERP Generic desde su estado actual (~114 endpoints) hasta alcanzar cobertura completa de todas las especificaciones tecnicas documentadas (~300+ endpoints).

### Estado Final

| Metrica | Inicial | Objetivo | Final |
|---------|---------|----------|-------|
| Endpoints implementados | 114 | ~300 | **309** |
| Modulos backend | 9 | 15 | **15** |
| Cobertura funcional | 35% | 100% | **100%** |

---

## FASE 1: Completar Modulos Existentes

### 1.1 Sales - Quotations & Orders

**Tablas BD existentes:** `sales.quotations`, `sales.quotation_lines`, `sales.sales_orders`, `sales.sales_order_lines`

**Endpoints a implementar:**

```
# Quotations (Cotizaciones)
GET    /api/v1/sales/quotations          - Listar cotizaciones
GET    /api/v1/sales/quotations/:id      - Obtener cotizacion por ID
POST   /api/v1/sales/quotations          - Crear cotizacion
PUT    /api/v1/sales/quotations/:id      - Actualizar cotizacion
DELETE /api/v1/sales/quotations/:id      - Eliminar cotizacion (soft)
POST   /api/v1/sales/quotations/:id/send - Enviar cotizacion por email
POST   /api/v1/sales/quotations/:id/confirm - Confirmar (convertir a orden)
POST   /api/v1/sales/quotations/:id/cancel  - Cancelar cotizacion

# Quotation Lines
POST   /api/v1/sales/quotations/:id/lines     - Agregar linea
PUT    /api/v1/sales/quotations/:id/lines/:lineId - Actualizar linea
DELETE /api/v1/sales/quotations/:id/lines/:lineId - Eliminar linea

# Sales Orders (Ordenes de Venta)
GET    /api/v1/sales/orders              - Listar ordenes
GET    /api/v1/sales/orders/:id          - Obtener orden por ID
POST   /api/v1/sales/orders              - Crear orden
PUT    /api/v1/sales/orders/:id          - Actualizar orden
DELETE /api/v1/sales/orders/:id          - Eliminar orden (soft)
POST   /api/v1/sales/orders/:id/confirm  - Confirmar orden
POST   /api/v1/sales/orders/:id/cancel   - Cancelar orden
POST   /api/v1/sales/orders/:id/invoice  - Generar factura

# Order Lines
POST   /api/v1/sales/orders/:id/lines          - Agregar linea
PUT    /api/v1/sales/orders/:id/lines/:lineId  - Actualizar linea
DELETE /api/v1/sales/orders/:id/lines/:lineId  - Eliminar linea
```

**Archivos a crear:**
- `src/modules/sales/quotations.service.ts`
- `src/modules/sales/orders.service.ts`

**Story Points estimados:** 13 SP

---

### 1.2 Financial - Invoices & Payments

**Tablas BD existentes:** `financial.invoices`, `financial.invoice_lines`, `financial.payments`, `financial.payment_invoice`, `financial.taxes`

**Endpoints a implementar:**

```
# Invoices (Facturas)
GET    /api/v1/financial/invoices           - Listar facturas
GET    /api/v1/financial/invoices/:id       - Obtener factura por ID
POST   /api/v1/financial/invoices           - Crear factura
PUT    /api/v1/financial/invoices/:id       - Actualizar factura
DELETE /api/v1/financial/invoices/:id       - Eliminar factura (soft)
POST   /api/v1/financial/invoices/:id/post  - Publicar factura
POST   /api/v1/financial/invoices/:id/cancel - Cancelar factura
POST   /api/v1/financial/invoices/:id/send  - Enviar por email

# Invoice Lines
POST   /api/v1/financial/invoices/:id/lines          - Agregar linea
PUT    /api/v1/financial/invoices/:id/lines/:lineId  - Actualizar linea
DELETE /api/v1/financial/invoices/:id/lines/:lineId  - Eliminar linea

# Payments (Pagos)
GET    /api/v1/financial/payments           - Listar pagos
GET    /api/v1/financial/payments/:id       - Obtener pago por ID
POST   /api/v1/financial/payments           - Registrar pago
PUT    /api/v1/financial/payments/:id       - Actualizar pago
DELETE /api/v1/financial/payments/:id       - Eliminar pago
POST   /api/v1/financial/payments/:id/post  - Publicar pago
POST   /api/v1/financial/payments/:id/reconcile - Conciliar con facturas

# Taxes (Impuestos)
GET    /api/v1/financial/taxes              - Listar impuestos
GET    /api/v1/financial/taxes/:id          - Obtener impuesto por ID
POST   /api/v1/financial/taxes              - Crear impuesto
PUT    /api/v1/financial/taxes/:id          - Actualizar impuesto
DELETE /api/v1/financial/taxes/:id          - Eliminar impuesto
```

**Archivos a crear:**
- `src/modules/financial/invoices.service.ts`
- `src/modules/financial/payments.service.ts`
- `src/modules/financial/taxes.service.ts`

**Story Points estimados:** 21 SP

---

### 1.3 Purchases - RFQs & Receipts

**Tablas BD existentes:** `purchase.rfqs`, `purchase.rfq_lines`

**Endpoints a implementar:**

```
# RFQs (Solicitudes de Cotizacion)
GET    /api/v1/purchases/rfqs              - Listar RFQs
GET    /api/v1/purchases/rfqs/:id          - Obtener RFQ por ID
POST   /api/v1/purchases/rfqs              - Crear RFQ
PUT    /api/v1/purchases/rfqs/:id          - Actualizar RFQ
DELETE /api/v1/purchases/rfqs/:id          - Eliminar RFQ (soft)
POST   /api/v1/purchases/rfqs/:id/send     - Enviar a proveedor
POST   /api/v1/purchases/rfqs/:id/confirm  - Confirmar (convertir a PO)
POST   /api/v1/purchases/rfqs/:id/cancel   - Cancelar RFQ

# RFQ Lines
POST   /api/v1/purchases/rfqs/:id/lines          - Agregar linea
PUT    /api/v1/purchases/rfqs/:id/lines/:lineId  - Actualizar linea
DELETE /api/v1/purchases/rfqs/:id/lines/:lineId  - Eliminar linea
```

**Story Points estimados:** 8 SP

---

### 1.4 Inventory - Adjustments & Lots

**Tablas BD existentes:** `inventory.inventory_adjustments`, `inventory.adjustment_lines`, `inventory.lots`

**Endpoints a implementar:**

```
# Inventory Adjustments (Ajustes de Inventario)
GET    /api/v1/inventory/adjustments           - Listar ajustes
GET    /api/v1/inventory/adjustments/:id       - Obtener ajuste por ID
POST   /api/v1/inventory/adjustments           - Crear ajuste
PUT    /api/v1/inventory/adjustments/:id       - Actualizar ajuste
POST   /api/v1/inventory/adjustments/:id/validate - Validar ajuste
POST   /api/v1/inventory/adjustments/:id/cancel   - Cancelar ajuste

# Adjustment Lines
POST   /api/v1/inventory/adjustments/:id/lines          - Agregar linea
PUT    /api/v1/inventory/adjustments/:id/lines/:lineId  - Actualizar linea
DELETE /api/v1/inventory/adjustments/:id/lines/:lineId  - Eliminar linea

# Lots (Lotes/Trazabilidad)
GET    /api/v1/inventory/lots              - Listar lotes
GET    /api/v1/inventory/lots/:id          - Obtener lote por ID
POST   /api/v1/inventory/lots              - Crear lote
PUT    /api/v1/inventory/lots/:id          - Actualizar lote
GET    /api/v1/inventory/lots/:id/movements - Movimientos del lote
```

**Story Points estimados:** 8 SP

---

## FASE 2: Nuevos Modulos con BD Existente

### 2.1 Projects Module

**Tablas BD existentes:** `projects.projects`, `projects.project_stages`, `projects.tasks`, `projects.milestones`, `projects.timesheets`, `projects.task_dependencies`

**Endpoints a implementar:**

```
# Projects
GET    /api/v1/projects                    - Listar proyectos
GET    /api/v1/projects/:id                - Obtener proyecto por ID
POST   /api/v1/projects                    - Crear proyecto
PUT    /api/v1/projects/:id                - Actualizar proyecto
DELETE /api/v1/projects/:id                - Eliminar proyecto (soft)
GET    /api/v1/projects/:id/tasks          - Tareas del proyecto
GET    /api/v1/projects/:id/milestones     - Hitos del proyecto
GET    /api/v1/projects/:id/timesheets     - Timesheets del proyecto
GET    /api/v1/projects/:id/stats          - Estadisticas del proyecto

# Project Stages
GET    /api/v1/projects/stages             - Listar stages
POST   /api/v1/projects/stages             - Crear stage
PUT    /api/v1/projects/stages/:id         - Actualizar stage
DELETE /api/v1/projects/stages/:id         - Eliminar stage

# Tasks
GET    /api/v1/projects/tasks              - Listar tareas
GET    /api/v1/projects/tasks/:id          - Obtener tarea por ID
POST   /api/v1/projects/tasks              - Crear tarea
PUT    /api/v1/projects/tasks/:id          - Actualizar tarea
DELETE /api/v1/projects/tasks/:id          - Eliminar tarea
POST   /api/v1/projects/tasks/:id/move     - Mover a otro stage (Kanban)
POST   /api/v1/projects/tasks/:id/assign   - Asignar tarea

# Milestones
GET    /api/v1/projects/milestones         - Listar milestones
GET    /api/v1/projects/milestones/:id     - Obtener milestone por ID
POST   /api/v1/projects/milestones         - Crear milestone
PUT    /api/v1/projects/milestones/:id     - Actualizar milestone
DELETE /api/v1/projects/milestones/:id     - Eliminar milestone
POST   /api/v1/projects/milestones/:id/complete - Marcar como completado

# Timesheets
GET    /api/v1/projects/timesheets         - Listar timesheets
GET    /api/v1/projects/timesheets/:id     - Obtener timesheet por ID
POST   /api/v1/projects/timesheets         - Registrar tiempo
PUT    /api/v1/projects/timesheets/:id     - Actualizar timesheet
DELETE /api/v1/projects/timesheets/:id     - Eliminar timesheet
POST   /api/v1/projects/timesheets/:id/submit  - Enviar para aprobacion
POST   /api/v1/projects/timesheets/:id/approve - Aprobar timesheet
```

**Archivos a crear:**
- `src/modules/projects/projects.routes.ts`
- `src/modules/projects/projects.controller.ts`
- `src/modules/projects/projects.service.ts`
- `src/modules/projects/tasks.service.ts`
- `src/modules/projects/milestones.service.ts`
- `src/modules/projects/timesheets.service.ts`
- `src/modules/projects/index.ts`

**Story Points estimados:** 21 SP

---

### 2.2 System Module (Mensajeria & Notificaciones)

**Tablas BD existentes:** `system.messages`, `system.notifications`, `system.activities`, `system.message_followers`

**Endpoints a implementar:**

```
# Messages (Chatter)
GET    /api/v1/system/messages                    - Listar mensajes
GET    /api/v1/system/messages/:id                - Obtener mensaje
POST   /api/v1/system/messages                    - Crear mensaje
DELETE /api/v1/system/messages/:id                - Eliminar mensaje
GET    /api/v1/system/messages/thread/:model/:id  - Mensajes de un registro

# Notifications
GET    /api/v1/system/notifications               - Mis notificaciones
GET    /api/v1/system/notifications/unread        - Notificaciones no leidas
POST   /api/v1/system/notifications/:id/read      - Marcar como leida
POST   /api/v1/system/notifications/read-all      - Marcar todas como leidas
DELETE /api/v1/system/notifications/:id           - Eliminar notificacion

# Activities
GET    /api/v1/system/activities                  - Mis actividades
GET    /api/v1/system/activities/:id              - Obtener actividad
POST   /api/v1/system/activities                  - Crear actividad
PUT    /api/v1/system/activities/:id              - Actualizar actividad
DELETE /api/v1/system/activities/:id              - Eliminar actividad
POST   /api/v1/system/activities/:id/complete     - Completar actividad
GET    /api/v1/system/activities/due              - Actividades pendientes

# Followers
GET    /api/v1/system/followers/:model/:id        - Seguidores de un registro
POST   /api/v1/system/followers/:model/:id        - Seguir registro
DELETE /api/v1/system/followers/:model/:id        - Dejar de seguir
```

**Archivos a crear:**
- `src/modules/system/system.routes.ts`
- `src/modules/system/system.controller.ts`
- `src/modules/system/messages.service.ts`
- `src/modules/system/notifications.service.ts`
- `src/modules/system/activities.service.ts`
- `src/modules/system/index.ts`

**Story Points estimados:** 13 SP

---

## FASE 3: Modulos Criticos (Requieren BD primero)

### 3.1 CRM Module

**Requiere crear schema `crm` primero**

**Tablas a crear:**
- `crm.leads`
- `crm.lead_stages`
- `crm.opportunities`
- `crm.opportunity_stages`
- `crm.lost_reasons`

**Endpoints planificados:**

```
# Leads
GET    /api/v1/crm/leads
GET    /api/v1/crm/leads/:id
POST   /api/v1/crm/leads
PUT    /api/v1/crm/leads/:id
DELETE /api/v1/crm/leads/:id
POST   /api/v1/crm/leads/:id/convert      - Convertir a oportunidad
POST   /api/v1/crm/leads/:id/lost         - Marcar como perdido

# Opportunities
GET    /api/v1/crm/opportunities
GET    /api/v1/crm/opportunities/:id
POST   /api/v1/crm/opportunities
PUT    /api/v1/crm/opportunities/:id
DELETE /api/v1/crm/opportunities/:id
POST   /api/v1/crm/opportunities/:id/won  - Marcar como ganada
POST   /api/v1/crm/opportunities/:id/lost - Marcar como perdida
POST   /api/v1/crm/opportunities/:id/quote - Crear cotizacion

# Pipeline
GET    /api/v1/crm/pipeline               - Vista Kanban
GET    /api/v1/crm/stages                 - Listar stages
POST   /api/v1/crm/stages                 - Crear stage
```

**Story Points estimados:** 21 SP (incluye BD)

---

### 3.2 HR Module

**Requiere crear schema `hr` primero**

**Tablas a crear:**
- `hr.employees`
- `hr.departments`
- `hr.job_positions`
- `hr.contracts`
- `hr.leaves`

**Endpoints planificados:**

```
# Employees
GET    /api/v1/hr/employees
GET    /api/v1/hr/employees/:id
POST   /api/v1/hr/employees
PUT    /api/v1/hr/employees/:id
DELETE /api/v1/hr/employees/:id

# Departments
GET    /api/v1/hr/departments
POST   /api/v1/hr/departments
PUT    /api/v1/hr/departments/:id
DELETE /api/v1/hr/departments/:id

# Contracts
GET    /api/v1/hr/contracts
GET    /api/v1/hr/contracts/:id
POST   /api/v1/hr/contracts
PUT    /api/v1/hr/contracts/:id
POST   /api/v1/hr/contracts/:id/activate
POST   /api/v1/hr/contracts/:id/terminate

# Leaves (Ausencias)
GET    /api/v1/hr/leaves
POST   /api/v1/hr/leaves
PUT    /api/v1/hr/leaves/:id
POST   /api/v1/hr/leaves/:id/approve
POST   /api/v1/hr/leaves/:id/reject
```

**Story Points estimados:** 21 SP (incluye BD)

---

## Cronograma de Implementacion

| Fase | Modulo | SP | Prioridad | Dependencia | Estado |
|------|--------|-----|-----------|-------------|--------|
| 1.1 | Sales Quotations/Orders | 13 | Alta | - | ✅ Completado |
| 1.2 | Financial Invoices/Payments | 21 | Alta | - | ✅ Completado |
| 1.3 | Purchases RFQs | 8 | Alta | - | ✅ Completado |
| 1.4 | Inventory Adjustments/Lots | 8 | Media | - | ✅ Completado |
| 2.1 | Projects Module | 21 | Alta | - | ✅ Completado |
| 2.2 | System Module | 13 | Alta | - | ✅ Completado |
| 3.1 | CRM Module | 21 | Critica | Schema CRM | ✅ Completado |
| 3.2 | HR Module | 21 | Critica | Schema HR | ✅ Completado |
| **TOTAL** | | **126 SP** | | | **100%** |

---

## Orden de Ejecucion Recomendado

### Sprint 1: Completar Sales y Projects
1. Sales Quotations/Orders (13 SP)
2. Projects Module (21 SP)

### Sprint 2: Financial y System
1. Financial Invoices/Payments (21 SP)
2. System Module (13 SP)

### Sprint 3: Purchases e Inventory
1. Purchases RFQs (8 SP)
2. Inventory Adjustments/Lots (8 SP)

### Sprint 4: CRM (requiere BD)
1. Crear schema CRM
2. CRM Module (21 SP)

### Sprint 5: HR (requiere BD)
1. Crear schema HR
2. HR Module (21 SP)

---

## Resumen de Implementacion Completada

### Endpoints por Modulo (Final)

| Modulo | Endpoints |
|--------|-----------|
| Auth | 3 |
| Users | 6 |
| Companies | 5 |
| Core | 41 |
| Partners | 19 |
| Inventory | 56 |
| Financial | 38 |
| Purchases | 33 |
| Sales | 42 |
| Projects | 30 |
| System | 19 |
| CRM | 35 |
| HR | 40 |
| **TOTAL** | **309** |

### Schemas BD Creados

1. **CRM Schema** (`11-crm.sql`)
   - `crm.leads` - Prospectos
   - `crm.lead_stages` - Etapas de leads
   - `crm.opportunities` - Oportunidades
   - `crm.opportunity_stages` - Etapas de oportunidades
   - `crm.lost_reasons` - Razones de perdida

2. **HR Schema** (`12-hr.sql`)
   - `hr.employees` - Empleados
   - `hr.departments` - Departamentos
   - `hr.job_positions` - Puestos de trabajo
   - `hr.contracts` - Contratos laborales
   - `hr.leaves` - Ausencias/permisos
   - `hr.leave_types` - Tipos de ausencia

---

**Documento generado por:** Architecture-Analyst
**Fecha:** 2025-11-24
**Completado:** 2025-11-24
