# API Endpoints para Nuevas Tablas - FASE 8

**Fecha:** 2026-01-04
**Version:** 1.0
**Cobertura:** 61 nuevas tablas, 25 funciones

---

## 1. Resumen de Endpoints Requeridos

| Modulo | Tablas | Endpoints Estimados | Prioridad |
|--------|--------|---------------------|-----------|
| Financial | 5 | 17 | Alta |
| Inventory | 5 | 15 | Alta |
| Purchase | 1 | 4 | Alta |
| Sales | 0 (solo campos) | 2 (funciones) | Media |
| CRM | 3 | 10 | Alta |
| Projects | 3 | 9 | Media |
| HR | 11 | 30 | Alta |
| **Total** | **28 core** | **87** | |

---

## 2. Financial Module

### 2.1 PaymentTermLines

**Tabla:** `financial.payment_term_lines`

```
GET    /api/v1/financial/payment-terms/:termId/lines
POST   /api/v1/financial/payment-terms/:termId/lines
GET    /api/v1/financial/payment-terms/:termId/lines/:id
PATCH  /api/v1/financial/payment-terms/:termId/lines/:id
DELETE /api/v1/financial/payment-terms/:termId/lines/:id
```

**Campos clave:**
- `sequence` - Orden de aplicacion
- `value` - Tipo: percent, fixed, balance
- `value_amount` - Porcentaje o monto
- `days` - Dias para vencimiento
- `end_month` - Si vence fin de mes

### 2.2 Incoterms

**Tabla:** `financial.incoterms`

```
GET    /api/v1/financial/incoterms
GET    /api/v1/financial/incoterms/:id
```

**Nota:** Solo lectura, datos pre-cargados (11 incoterms estandar)

### 2.3 PaymentMethods

**Tabla:** `financial.payment_methods`

```
GET    /api/v1/financial/payment-methods
POST   /api/v1/financial/payment-methods
GET    /api/v1/financial/payment-methods/:id
PATCH  /api/v1/financial/payment-methods/:id
DELETE /api/v1/financial/payment-methods/:id
```

**Campos clave:**
- `payment_type` - ENUM: inbound, outbound
- `code` - Codigo unico por tenant

### 2.4 ReconcileModels

**Tabla:** `financial.reconcile_models`

```
GET    /api/v1/financial/reconcile-models
POST   /api/v1/financial/reconcile-models
GET    /api/v1/financial/reconcile-models/:id
PATCH  /api/v1/financial/reconcile-models/:id
DELETE /api/v1/financial/reconcile-models/:id
```

**Campos clave:**
- `rule_type` - ENUM: writeoff_button, writeoff_suggestion, invoice_matching
- `auto_reconcile` - Automatizar conciliacion
- `match_amount` - percentage, fixed, any

### 2.5 ReconcileModelLines

**Tabla:** `financial.reconcile_model_lines`

```
GET    /api/v1/financial/reconcile-models/:modelId/lines
POST   /api/v1/financial/reconcile-models/:modelId/lines
GET    /api/v1/financial/reconcile-models/:modelId/lines/:id
PATCH  /api/v1/financial/reconcile-models/:modelId/lines/:id
DELETE /api/v1/financial/reconcile-models/:modelId/lines/:id
```

**Campos clave:**
- `account_id` - Cuenta contable destino (requerido)
- `amount_type` - percentage, fixed, regex
- `amount_value` - Valor/porcentaje a aplicar

---

## 3. Inventory Module

### 3.1 PackageTypes

**Tabla:** `inventory.package_types`

```
GET    /api/v1/inventory/package-types
POST   /api/v1/inventory/package-types
GET    /api/v1/inventory/package-types/:id
PATCH  /api/v1/inventory/package-types/:id
DELETE /api/v1/inventory/package-types/:id
```

**Campos clave:**
- Dimensiones: height, width, length
- Pesos: base_weight, max_weight

### 3.2 Packages

**Tabla:** `inventory.packages`

```
GET    /api/v1/inventory/packages
POST   /api/v1/inventory/packages
GET    /api/v1/inventory/packages/:id
PATCH  /api/v1/inventory/packages/:id
DELETE /api/v1/inventory/packages/:id
GET    /api/v1/inventory/locations/:locationId/packages
```

### 3.3 PutawayRules

**Tabla:** `inventory.putaway_rules`

```
GET    /api/v1/inventory/putaway-rules
POST   /api/v1/inventory/putaway-rules
GET    /api/v1/inventory/putaway-rules/:id
PATCH  /api/v1/inventory/putaway-rules/:id
DELETE /api/v1/inventory/putaway-rules/:id
```

**Logica:**
- Ordenar por sequence
- Buscar por producto o categoria
- Aplicar location_out como destino

### 3.4 StorageCategories

**Tabla:** `inventory.storage_categories`

```
GET    /api/v1/inventory/storage-categories
POST   /api/v1/inventory/storage-categories
GET    /api/v1/inventory/storage-categories/:id
PATCH  /api/v1/inventory/storage-categories/:id
DELETE /api/v1/inventory/storage-categories/:id
```

### 3.5 RemovalStrategies

**Tabla:** `inventory.removal_strategies`

```
GET    /api/v1/inventory/removal-strategies
```

**Nota:** Solo lectura, datos pre-cargados (FIFO, LIFO, FEFO, Closest)

---

## 4. Purchase Module

### 4.1 ProductSupplierinfo

**Tabla:** `purchase.product_supplierinfo`

```
GET    /api/v1/purchase/suppliers/:partnerId/products
POST   /api/v1/purchase/suppliers/:partnerId/products
GET    /api/v1/purchase/suppliers/:partnerId/products/:id
PATCH  /api/v1/purchase/suppliers/:partnerId/products/:id
DELETE /api/v1/purchase/suppliers/:partnerId/products/:id

# Alternativa por producto
GET    /api/v1/inventory/products/:productId/suppliers
```

**Campos clave:**
- `min_qty` - Cantidad minima
- `price` - Precio del proveedor
- `delay` - Lead time en dias
- `date_start/date_end` - Vigencia

### 4.2 Funciones

```
POST   /api/v1/purchase/orders/:id/create-stock-moves
```

**Funcion:** `purchase.action_create_stock_moves(order_id)`
- Crea picking de recepcion
- Genera stock_moves por cada linea

---

## 5. Sales Module

### 5.1 Funciones

```
POST   /api/v1/sales/orders/:id/confirm
```

**Funcion:** `sales.action_confirm(order_id)`
- Cambia status a 'sale'
- Genera nombre de secuencia
- Actualiza qty_to_deliver, qty_to_invoice

```
GET    /api/v1/sales/pricelists/:id/price
```

**Query params:**
- `product_id` - UUID del producto
- `quantity` - Cantidad (default 1)
- `date` - Fecha (default hoy)

**Funcion:** `sales.get_pricelist_price(pricelist_id, product_id, quantity, date)`

---

## 6. CRM Module

### 6.1 Tags

**Tabla:** `crm.tags`

```
GET    /api/v1/crm/tags
POST   /api/v1/crm/tags
GET    /api/v1/crm/tags/:id
PATCH  /api/v1/crm/tags/:id
DELETE /api/v1/crm/tags/:id
```

### 6.2 Lead-Tag Relations

```
POST   /api/v1/crm/leads/:id/tags
DELETE /api/v1/crm/leads/:id/tags/:tagId
GET    /api/v1/crm/leads/:id/tags
```

### 6.3 Opportunity-Tag Relations

```
POST   /api/v1/crm/opportunities/:id/tags
DELETE /api/v1/crm/opportunities/:id/tags/:tagId
GET    /api/v1/crm/opportunities/:id/tags
```

### 6.4 Funciones CRM

```
POST   /api/v1/crm/leads/:id/convert-to-opportunity
```

**Body:**
```json
{
  "partner_id": "uuid (opcional)",
  "create_partner": true
}
```

**Funcion:** `crm.convert_lead_to_opportunity(lead_id, partner_id, create_partner)`

```
POST   /api/v1/crm/leads/:id/set-lost
POST   /api/v1/crm/opportunities/:id/set-lost
```

**Body:**
```json
{
  "lost_reason_id": "uuid",
  "lost_notes": "string (opcional)"
}
```

```
POST   /api/v1/crm/opportunities/:id/set-won
```

---

## 7. Projects Module

### 7.1 Collaborators

**Tabla:** `projects.collaborators`

```
GET    /api/v1/projects/:projectId/collaborators
POST   /api/v1/projects/:projectId/collaborators
GET    /api/v1/projects/:projectId/collaborators/:id
PATCH  /api/v1/projects/:projectId/collaborators/:id
DELETE /api/v1/projects/:projectId/collaborators/:id
```

**Constraint:** Debe tener partner_id OR user_id (no ambos)

### 7.2 Ratings

**Tabla:** `projects.ratings`

```
GET    /api/v1/projects/:projectId/ratings
POST   /api/v1/projects/:projectId/ratings
GET    /api/v1/projects/tasks/:taskId/ratings
POST   /api/v1/projects/tasks/:taskId/ratings
```

### 7.3 Burndown Chart

**Tabla:** `projects.burndown_chart_data`

```
GET    /api/v1/projects/:projectId/burndown
POST   /api/v1/projects/:projectId/burndown/snapshot
```

**Funcion:** `projects.generate_burndown_snapshot(project_id)`

**Response GET:**
```json
{
  "data": [
    {
      "date": "2026-01-04",
      "total_tasks": 50,
      "completed_tasks": 20,
      "remaining_tasks": 30,
      "total_hours": 400,
      "completed_hours": 150,
      "remaining_hours": 250
    }
  ]
}
```

---

## 8. HR Module

### 8.1 Work Locations

**Tabla:** `hr.work_locations`

```
GET    /api/v1/hr/work-locations
POST   /api/v1/hr/work-locations
GET    /api/v1/hr/work-locations/:id
PATCH  /api/v1/hr/work-locations/:id
DELETE /api/v1/hr/work-locations/:id
```

### 8.2 Skills System

**Tablas:** `hr.skill_types`, `hr.skills`, `hr.skill_levels`, `hr.employee_skills`

```
# Skill Types
GET    /api/v1/hr/skill-types
POST   /api/v1/hr/skill-types
GET    /api/v1/hr/skill-types/:id
PATCH  /api/v1/hr/skill-types/:id
DELETE /api/v1/hr/skill-types/:id

# Skills (por tipo)
GET    /api/v1/hr/skill-types/:typeId/skills
POST   /api/v1/hr/skill-types/:typeId/skills

# Skill Levels (por tipo)
GET    /api/v1/hr/skill-types/:typeId/levels
POST   /api/v1/hr/skill-types/:typeId/levels

# Employee Skills
GET    /api/v1/hr/employees/:employeeId/skills
POST   /api/v1/hr/employees/:employeeId/skills
DELETE /api/v1/hr/employees/:employeeId/skills/:skillId
```

### 8.3 Expenses

**Tablas:** `hr.expense_sheets`, `hr.expenses`

```
# Expense Sheets
GET    /api/v1/hr/expense-sheets
POST   /api/v1/hr/expense-sheets
GET    /api/v1/hr/expense-sheets/:id
PATCH  /api/v1/hr/expense-sheets/:id
DELETE /api/v1/hr/expense-sheets/:id
POST   /api/v1/hr/expense-sheets/:id/submit
POST   /api/v1/hr/expense-sheets/:id/approve
POST   /api/v1/hr/expense-sheets/:id/reject

# Expenses (lineas)
GET    /api/v1/hr/expense-sheets/:sheetId/expenses
POST   /api/v1/hr/expense-sheets/:sheetId/expenses
GET    /api/v1/hr/expenses/:id
PATCH  /api/v1/hr/expenses/:id
DELETE /api/v1/hr/expenses/:id

# Expenses sin sheet (draft individuales)
GET    /api/v1/hr/employees/:employeeId/expenses
POST   /api/v1/hr/employees/:employeeId/expenses
```

### 8.4 Resume Lines

**Tabla:** `hr.employee_resume_lines`

```
GET    /api/v1/hr/employees/:employeeId/resume
POST   /api/v1/hr/employees/:employeeId/resume
GET    /api/v1/hr/employees/:employeeId/resume/:id
PATCH  /api/v1/hr/employees/:employeeId/resume/:id
DELETE /api/v1/hr/employees/:employeeId/resume/:id
```

**Tipos:** experience, education, certification, internal

### 8.5 Payslips

**Tablas:** `hr.payslip_structures`, `hr.payslips`, `hr.payslip_lines`

```
# Structures
GET    /api/v1/hr/payslip-structures
POST   /api/v1/hr/payslip-structures
GET    /api/v1/hr/payslip-structures/:id
PATCH  /api/v1/hr/payslip-structures/:id
DELETE /api/v1/hr/payslip-structures/:id

# Payslips
GET    /api/v1/hr/payslips
POST   /api/v1/hr/payslips
GET    /api/v1/hr/payslips/:id
PATCH  /api/v1/hr/payslips/:id
DELETE /api/v1/hr/payslips/:id
POST   /api/v1/hr/payslips/:id/verify
POST   /api/v1/hr/payslips/:id/done
POST   /api/v1/hr/payslips/:id/cancel

# Payslip Lines
GET    /api/v1/hr/payslips/:payslipId/lines
```

---

## 9. Campos Adicionales (Existentes)

Las siguientes tablas existentes tienen nuevos campos que requieren actualizar los DTOs:

### 9.1 financial.journal_entries

Nuevos campos:
- `payment_state`
- `amount_residual`
- `invoice_date_due`
- `fiscal_position_id`
- `incoterm_id`
- `auto_post`

### 9.2 financial.payments

Nuevos campos:
- `is_matched`
- `partner_bank_id`
- `destination_journal_id`

### 9.3 inventory.products

Nuevos campos:
- `tracking` (none, serial, lot)
- `sale_delay`
- `purchase_ok`
- `sale_ok`
- `invoice_policy`
- `volume`, `weight`
- `hs_code`
- `origin_country_id`

### 9.4 inventory.stock_pickings

Nuevos campos:
- `scheduled_date`
- `date_deadline`
- `weight`
- `shipping_weight`

### 9.5 purchase.orders

Nuevos campos:
- `incoterm_id`
- `fiscal_position_id`
- `origin`
- `receipt_status`

### 9.6 sales.orders

Nuevos campos:
- `incoterm_id`
- `campaign_id`
- `require_signature`
- `signed_by`

### 9.7 crm.leads / crm.opportunities

Nuevos campos:
- `color`
- `referred`
- `day_open`, `day_close`
- `is_won` (opportunities)
- `date_action`, `title_action`

### 9.8 projects.projects / projects.tasks

Nuevos campos:
- `sequence`
- `is_favorite`
- `task_count`, `open_task_count`, `closed_task_count`
- `kanban_state` (tasks)
- `color` (tasks)

### 9.9 hr.employees

30+ nuevos campos:
- Datos privados: private_street, private_city, etc.
- Documentos: visa_no, work_permit_no, etc.
- Personal: children, vehicle, etc.
- Identificacion: badge_id, pin, barcode

---

## 10. Notas de Implementacion

### 10.1 RLS (Row Level Security)

Todas las nuevas tablas tienen RLS habilitado. Los endpoints deben:
1. Establecer `app.current_tenant_id` antes de queries
2. Verificar permisos de company cuando aplique

### 10.2 Transacciones

Las funciones que modifican multiples tablas (ej. convert_lead_to_opportunity)
ya manejan transacciones internamente.

### 10.3 Triggers

- `projects.tasks` - Trigger automatico para actualizar conteos en proyecto
- No requiere accion del API, los conteos se actualizan solos

### 10.4 ENUMs

Nuevos ENUMs a mapear en DTOs:
- `financial.payment_method_type`: inbound, outbound
- `financial.reconcile_model_type`: writeoff_button, writeoff_suggestion, invoice_matching
- `hr.expense_status`: draft, submitted, approved, posted, paid, rejected
- `hr.resume_line_type`: experience, education, certification, internal
- `hr.payslip_status`: draft, verify, done, cancel

---

**Generado:** 2026-01-04
**Para:** Equipo Backend
**Referencia:** FASE-8 Cobertura Maxima
