# FASE 3: Plan de Correcciones Basado en Analisis Odoo vs ERP-Core

**Fecha:** 2026-01-04
**Objetivo:** Plan priorizado de correcciones para alinear ERP-Core con definiciones Odoo
**Estado:** En Progreso
**Basado en:** FASE-1 (Planeacion), FASE-2 (Analisis Detallado)

---

## 1. Resumen Ejecutivo de Brechas

### 1.1 Cobertura por Modulo

| Modulo | Cobertura | Gaps Criticos | Gaps Altos | Gaps Medios |
|--------|-----------|---------------|------------|-------------|
| BASE/AUTH | 75% | 3 | 4 | 5 |
| PRODUCT/STOCK | 65% | 4 | 5 | 6 |
| SALE | 70% | 2 | 4 | 3 |
| PURCHASE | 70% | 2 | 3 | 4 |
| ACCOUNT/FINANCIAL | 65% | 4 | 5 | 4 |
| CRM | 75% | 2 | 3 | 3 |
| ANALYTIC | 65% | 2 | 2 | 2 |
| PROJECT | 80% | 2 | 2 | 3 |
| HR | 70% | 1 | 3 | 4 |

### 1.2 Total de Correcciones Identificadas

| Severidad | Cantidad | % del Total |
|-----------|----------|-------------|
| CRITICO | 22 | 18% |
| ALTO | 31 | 26% |
| MEDIO | 34 | 28% |
| BAJO | 34 | 28% |
| **TOTAL** | **121** | 100% |

---

## 2. Plan de Correcciones por Prioridad

### 2.1 PRIORIDAD CRITICA (P0) - Bloqueantes

#### COR-001: Agregar estado 'to_approve' a Purchase Orders
- **Archivo DDL:** `database/ddl/06-purchase.sql`
- **Cambio:** Modificar ENUM `purchase.order_status`
- **De:** `('draft', 'sent', 'confirmed', 'received', 'billed', 'cancelled')`
- **A:** `('draft', 'sent', 'to_approve', 'purchase', 'received', 'billed', 'cancelled')`
- **Impacto:** Functions, Triggers, Domain Models
- **Dependencias:** None

#### COR-002: Agregar estados faltantes a Stock Moves
- **Archivo DDL:** `database/ddl/05-inventory.sql`
- **Cambio:** Modificar ENUM `inventory.move_status`
- **De:** `('draft', 'confirmed', 'assigned', 'done', 'cancelled')`
- **A:** `('draft', 'waiting', 'confirmed', 'partially_available', 'assigned', 'done', 'cancelled')`
- **Impacto:** stock_moves, pickings, Functions
- **Dependencias:** None

#### COR-003: Crear tabla stock_move_lines
- **Archivo DDL:** `database/ddl/05-inventory.sql`
- **Cambio:** Nueva tabla para granularidad a nivel de lote/serie
- **Estructura:**
```sql
CREATE TABLE inventory.stock_move_lines (
  id UUID PRIMARY KEY,
  tenant_id UUID NOT NULL,
  move_id UUID NOT NULL REFERENCES inventory.stock_moves(id),
  product_id UUID NOT NULL,
  product_uom_id UUID NOT NULL,
  lot_id UUID REFERENCES inventory.lots(id),
  package_id UUID,
  owner_id UUID REFERENCES core.partners(id),
  location_id UUID NOT NULL,
  location_dest_id UUID NOT NULL,
  quantity DECIMAL(12, 4) NOT NULL,
  quantity_done DECIMAL(12, 4) DEFAULT 0,
  state VARCHAR(20),
  -- Audit fields
);
```
- **Impacto:** stock_moves, reserve_quantity(), process_stock_move()
- **Dependencias:** COR-002

#### COR-004: Agregar payment_state a Facturas
- **Archivo DDL:** `database/ddl/04-financial.sql`
- **Cambio:** Nueva columna para separar estado contable de estado de pago
- **De:** Solo `status` (draft, open, paid, cancelled)
- **A:** `status` + `payment_state` (not_paid, in_payment, paid, partial, reversed)
- **Impacto:** invoices, payment_invoice, triggers
- **Dependencias:** None

#### COR-005: Implementar Tax Groups
- **Archivo DDL:** `database/ddl/04-financial.sql`
- **Cambio:** Nueva tabla para grupos de impuestos complejos
- **Estructura:**
```sql
CREATE TABLE financial.tax_groups (
  id UUID PRIMARY KEY,
  tenant_id UUID NOT NULL,
  name VARCHAR(100) NOT NULL,
  sequence INTEGER DEFAULT 10,
  country_id UUID
);

ALTER TABLE financial.taxes
ADD COLUMN tax_group_id UUID REFERENCES financial.tax_groups(id),
ADD COLUMN amount_type VARCHAR(20) DEFAULT 'percent', -- percent, fixed, group, division
ADD COLUMN include_base_amount BOOLEAN DEFAULT FALSE,
ADD COLUMN price_include BOOLEAN DEFAULT FALSE,
ADD COLUMN children_tax_ids UUID[];
```
- **Impacto:** Calculo de impuestos en invoice_lines, sales_order_lines, purchase_order_lines
- **Dependencias:** None

#### COR-006: Vincular Sale Orders con Invoices
- **Archivo DDL:** `database/ddl/07-sales.sql`
- **Cambio:** Agregar campos para vinculacion factura
- **Estructura:**
```sql
ALTER TABLE sales.sales_orders
ADD COLUMN invoice_ids UUID[] DEFAULT '{}',
ADD COLUMN invoice_count INTEGER GENERATED ALWAYS AS (array_length(invoice_ids, 1)) STORED;
```
- **Impacto:** sales_orders, invoices, workflows
- **Dependencias:** None

---

### 2.2 PRIORIDAD ALTA (P1) - Importantes

#### COR-007: Agregar picking_type_id a Pickings
- **Archivo DDL:** `database/ddl/05-inventory.sql`
- **Cambio:** Nueva tabla y campo para tipos de operacion
- **Estructura:**
```sql
CREATE TABLE inventory.picking_types (
  id UUID PRIMARY KEY,
  tenant_id UUID NOT NULL,
  warehouse_id UUID REFERENCES inventory.warehouses(id),
  name VARCHAR(100) NOT NULL,
  code VARCHAR(20) NOT NULL, -- incoming, outgoing, internal
  sequence_id UUID,
  default_location_src_id UUID,
  default_location_dest_id UUID,
  return_picking_type_id UUID,
  show_operations BOOLEAN DEFAULT FALSE,
  show_reserved BOOLEAN DEFAULT TRUE,
  active BOOLEAN DEFAULT TRUE
);

ALTER TABLE inventory.pickings
ADD COLUMN picking_type_id UUID REFERENCES inventory.picking_types(id);
```
- **Impacto:** pickings, workflows
- **Dependencias:** None

#### COR-008: Implementar Product Attributes System
- **Archivo DDL:** `database/ddl/05-inventory.sql`
- **Cambio:** Sistema completo de atributos y variantes
- **Estructura:**
```sql
CREATE TABLE inventory.product_attributes (
  id UUID PRIMARY KEY,
  tenant_id UUID NOT NULL,
  name VARCHAR(100) NOT NULL,
  create_variant VARCHAR(20) DEFAULT 'always', -- always, dynamic, no_variant
  display_type VARCHAR(20) DEFAULT 'radio' -- radio, select, color, multi
);

CREATE TABLE inventory.product_attribute_values (
  id UUID PRIMARY KEY,
  attribute_id UUID NOT NULL REFERENCES inventory.product_attributes(id),
  name VARCHAR(100) NOT NULL,
  html_color VARCHAR(10),
  sequence INTEGER DEFAULT 10
);

CREATE TABLE inventory.product_template_attribute_lines (
  id UUID PRIMARY KEY,
  product_tmpl_id UUID NOT NULL REFERENCES inventory.products(id),
  attribute_id UUID NOT NULL REFERENCES inventory.product_attributes(id),
  value_ids UUID[] NOT NULL
);
```
- **Impacto:** products, product_variants
- **Dependencias:** None

#### COR-009: Agregar Approval Workflow a Purchase
- **Archivo DDL:** `database/ddl/06-purchase.sql`
- **Cambio:** Campos y funciones para flujo de aprobacion
- **Estructura:**
```sql
ALTER TABLE purchase.purchase_orders
ADD COLUMN approved_at TIMESTAMP,
ADD COLUMN approved_by UUID REFERENCES auth.users(id),
ADD COLUMN approval_required BOOLEAN DEFAULT FALSE,
ADD COLUMN amount_threshold DECIMAL(15, 2);

CREATE OR REPLACE FUNCTION purchase.button_approve(p_order_id UUID)
RETURNS VOID AS $$...$$;
```
- **Impacto:** purchase_orders, rbac
- **Dependencias:** COR-001

#### COR-010: Implementar Address Management
- **Archivo DDL:** `database/ddl/02-core.sql`
- **Cambio:** Direcciones de facturacion y envio separadas
- **Estructura:**
```sql
ALTER TABLE sales.sales_orders
ADD COLUMN partner_invoice_id UUID REFERENCES core.partners(id),
ADD COLUMN partner_shipping_id UUID REFERENCES core.partners(id);

ALTER TABLE purchase.purchase_orders
ADD COLUMN dest_address_id UUID REFERENCES core.partners(id);
```
- **Impacto:** sales_orders, purchase_orders, partners
- **Dependencias:** None

#### COR-011: Agregar Locked State a Orders
- **Archivo DDL:** `database/ddl/06-purchase.sql`, `database/ddl/07-sales.sql`
- **Cambio:** Campo locked para bloquear modificaciones
- **Estructura:**
```sql
ALTER TABLE purchase.purchase_orders
ADD COLUMN locked BOOLEAN DEFAULT FALSE;

ALTER TABLE sales.sales_orders
ADD COLUMN locked BOOLEAN DEFAULT FALSE;
```
- **Impacto:** Triggers de validacion
- **Dependencias:** None

#### COR-012: Implementar Downpayments (Anticipos)
- **Archivo DDL:** `database/ddl/07-sales.sql`
- **Cambio:** Soporte para anticipos en ventas
- **Estructura:**
```sql
ALTER TABLE sales.sales_order_lines
ADD COLUMN is_downpayment BOOLEAN DEFAULT FALSE;

ALTER TABLE sales.sales_orders
ADD COLUMN require_payment BOOLEAN DEFAULT FALSE,
ADD COLUMN prepayment_percent DECIMAL(5, 2) DEFAULT 0;
```
- **Impacto:** sales_order_lines, invoice generation
- **Dependencias:** COR-006

#### COR-013: Agregar Reconciliation Engine
- **Archivo DDL:** `database/ddl/04-financial.sql`
- **Cambio:** Motor de conciliacion completo
- **Estructura:**
```sql
CREATE TABLE financial.account_partial_reconcile (
  id UUID PRIMARY KEY,
  tenant_id UUID NOT NULL,
  debit_move_id UUID NOT NULL REFERENCES financial.journal_entry_lines(id),
  credit_move_id UUID NOT NULL REFERENCES financial.journal_entry_lines(id),
  amount DECIMAL(15, 2) NOT NULL,
  amount_currency DECIMAL(15, 2),
  currency_id UUID,
  full_reconcile_id UUID,
  max_date DATE
);

CREATE TABLE financial.account_full_reconcile (
  id UUID PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  partial_reconcile_ids UUID[],
  reconciled_line_ids UUID[]
);
```
- **Impacto:** journal_entry_lines, invoices, payments
- **Dependencias:** COR-004

---

### 2.3 PRIORIDAD MEDIA (P2) - Mejoras

#### COR-014: Implementar Predictive Lead Scoring (PLS)
- **Archivo DDL:** `database/ddl/11-crm.sql`
- **Cambio:** Sistema de scoring predictivo
- **Impacto:** leads, opportunities
- **Dependencias:** ML pipeline

#### COR-015: Agregar Multi-Plan Hierarchy (Analytics)
- **Archivo DDL:** `database/ddl/03-analytics.sql`
- **Cambio:** Jerarquia de planes analiticos
- **Impacto:** analytic_accounts, analytic_lines
- **Dependencias:** None

#### COR-016: Implementar Recurring Tasks (Projects)
- **Archivo DDL:** `database/ddl/08-projects.sql`
- **Cambio:** Tareas recurrentes
- **Impacto:** project_tasks
- **Dependencias:** None

#### COR-017: Agregar Multi-User Assignment (Tasks)
- **Archivo DDL:** `database/ddl/08-projects.sql`
- **Cambio:** Multiples usuarios asignados
- **Impacto:** project_tasks
- **Dependencias:** None

#### COR-018: Implementar Backorder Management
- **Archivo DDL:** `database/ddl/05-inventory.sql`
- **Cambio:** Gestion de backorders
- **Impacto:** pickings, stock_moves
- **Dependencias:** COR-002, COR-003

#### COR-019: Agregar Auto-Assignment Rules (CRM)
- **Archivo DDL:** `database/ddl/11-crm.sql`
- **Cambio:** Reglas de asignacion automatica
- **Impacto:** leads, teams
- **Dependencias:** None

#### COR-020: Implementar Duplicate Detection (Partners)
- **Archivo DDL:** `database/ddl/02-core.sql`
- **Cambio:** Deteccion de duplicados
- **Impacto:** partners
- **Dependencias:** None

---

### 2.4 PRIORIDAD BAJA (P3) - Nice to Have

#### COR-021 a COR-034: Mejoras menores documentadas en archivo separado
- Ver: `FASE-3-CORRECCIONES-MENORES.md`

---

## 3. Archivos Afectados por Correccion

### 3.1 Matriz de Impacto DDL

| Archivo DDL | P0 | P1 | P2 | Total |
|-------------|----|----|----| ------|
| 02-core.sql | 0 | 1 | 1 | 2 |
| 03-analytics.sql | 0 | 0 | 1 | 1 |
| 04-financial.sql | 2 | 1 | 0 | 3 |
| 05-inventory.sql | 2 | 2 | 2 | 6 |
| 06-purchase.sql | 1 | 2 | 0 | 3 |
| 07-sales.sql | 1 | 2 | 0 | 3 |
| 08-projects.sql | 0 | 0 | 2 | 2 |
| 11-crm.sql | 0 | 0 | 2 | 2 |

### 3.2 Matriz de Impacto Domain Models

| Domain Model | Correcciones | Secciones |
|--------------|--------------|-----------|
| inventory-domain.md | COR-002, COR-003, COR-007, COR-008, COR-018 | States, Relations, Constraints |
| sales-domain.md | COR-006, COR-010, COR-011, COR-012 | Relations, Fields |
| financial-domain.md | COR-004, COR-005, COR-013 | States, Tax Logic, Reconciliation |
| crm-domain.md | COR-014, COR-019 | Scoring, Assignment |
| analytics-domain.md | COR-015 | Plans, Hierarchy |
| projects-domain.md | COR-016, COR-017 | Recurrence, Assignment |

### 3.3 Matriz de Impacto Workflows

| Workflow | Correcciones | Impacto |
|----------|--------------|---------|
| (nuevo) WORKFLOW-PURCHASE-APPROVAL.md | COR-001, COR-009 | Nuevo workflow |
| (nuevo) WORKFLOW-STOCK-MOVES.md | COR-002, COR-003, COR-018 | Nuevo workflow |
| WORKFLOW-CIERRE-PERIODO-CONTABLE.md | COR-004 | Actualizacion menor |

---

## 4. Dependencias entre Correcciones

```
COR-001 (PO states)
    └── COR-009 (Approval workflow)

COR-002 (Move states)
    └── COR-003 (Move lines)
        └── COR-018 (Backorders)

COR-004 (Payment state)
    └── COR-013 (Reconciliation engine)

COR-006 (SO-Invoice link)
    └── COR-012 (Downpayments)
```

---

## 5. Orden de Ejecucion Recomendado

### Fase 6.1: Foundation (Semana 1)
1. COR-001: PO states
2. COR-002: Move states
3. COR-004: Payment state
4. COR-005: Tax groups

### Fase 6.2: Inventory (Semana 2)
5. COR-003: Move lines
6. COR-007: Picking types
7. COR-008: Product attributes

### Fase 6.3: Sales/Purchase (Semana 3)
8. COR-006: SO-Invoice link
9. COR-009: Approval workflow
10. COR-010: Address management
11. COR-011: Locked states
12. COR-012: Downpayments

### Fase 6.4: Financial (Semana 4)
13. COR-013: Reconciliation engine

### Fase 6.5: Advanced Features (Semana 5)
14. COR-014 a COR-020: Prioridad Media

---

## 6. Riesgos Identificados

| Riesgo | Probabilidad | Impacto | Mitigacion |
|--------|--------------|---------|------------|
| Breaking changes en ENUM | Alta | Alto | Migracion incremental |
| Incompatibilidad de datos existentes | Media | Alto | Scripts de migracion |
| Regresiones en funciones existentes | Media | Medio | Tests unitarios |
| Performance en nuevas tablas | Baja | Medio | Indices optimizados |

---

## 7. Entregables FASE 3

- [x] Plan priorizado de correcciones (este documento)
- [ ] Lista de dependencias validada
- [ ] Estimacion de esfuerzo por correccion
- [ ] Scripts de migracion preliminares
- [ ] Tests de regresion identificados

---

## 8. Proximos Pasos (FASE 4)

1. Validar dependencias entre correcciones
2. Verificar impacto en archivos downstream (User Stories, Backend Specs)
3. Identificar tests de regresion necesarios
4. Aprobar plan con stakeholders

---

**Generado:** 2026-01-04
**Herramienta:** Claude Code
