# ANALISIS DE IMPACTO DE CAMBIOS

**Fecha:** 2025-12-18
**Fase:** 4 - Validacion
**Objetivo:** Identificar todos los objetos impactados por los cambios planificados

---

## 1. RESUMEN DE IMPACTOS

### 1.1 Metricas Generales

| Categoria | Cantidad |
|-----------|----------|
| Tablas nuevas | 26 |
| Vistas/Views | 1 |
| Vistas materializadas | 3 |
| Entidades TypeORM | 26 |
| Servicios nuevos | 28 |
| Servicios extendidos | 8 |
| Controllers | 15 |
| Paginas frontend | ~65 |
| Componentes UI | ~80 |
| Integraciones externas | 7 |

### 1.2 Impacto por Capa

```
┌─────────────────────────────────────────────────────────────┐
│                    MATRIZ DE IMPACTO                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  DATABASE        [████████████████████████████] 100%        │
│  26 tablas, 3 mat views, 1 view                            │
│                                                             │
│  BACKEND         [████████████████████████████] 100%        │
│  36 services, 15 controllers, 5 middlewares                │
│                                                             │
│  FRONTEND        [████████████████████████████] 100%        │
│  3 apps, ~65 pages, ~80 components                         │
│                                                             │
│  INTEGRACIONES   [████████████░░░░░░░░░░░░░░░░] 35%         │
│  PAC, Pagos, Envios (parcialmente nuevos)                  │
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

---

## 2. IMPACTO EN BASE DE DATOS

### 2.1 Schemas Afectados

| Schema | Accion | Objetos |
|--------|--------|---------|
| auth | MODIFICAR | Agregar permissions, user_roles |
| core | MODIFICAR | Agregar countries, currencies, uom, sequences |
| financial | MODIFICAR | Agregar tax_groups, payment_methods |
| inventory | VERIFICAR | Ya existe, solo verificar stock_quants |
| sales | MODIFICAR | Agregar pricelists, pricelist_items |
| **retail** | **CREAR** | **26 tablas nuevas** |

### 2.2 Tablas por Schema

#### Schema: retail (NUEVO)

| Tabla | Modulo | FK Entrantes | FK Salientes |
|-------|--------|--------------|--------------|
| branches | RT-001 | cash_registers, branch_users, pos_sessions, stock_transfers(x2), stock_adjustments, supplier_orders, goods_receipts, ecommerce_orders | auth.tenants, inventory.warehouses |
| cash_registers | RT-001 | pos_sessions | auth.tenants, retail.branches |
| branch_users | RT-001 | - | auth.tenants, retail.branches, auth.users |
| pos_sessions | RT-002 | pos_orders, cash_movements, cash_closings, cash_counts | auth.tenants, retail.branches, retail.cash_registers, auth.users |
| pos_orders | RT-002 | pos_order_lines, pos_payments, loyalty_transactions, coupon_redemptions, cfdis | auth.tenants, retail.pos_sessions, core.partners |
| pos_order_lines | RT-002 | - | auth.tenants, retail.pos_orders, inventory.products |
| pos_payments | RT-002 | - | auth.tenants, retail.pos_orders |
| cash_movements | RT-007 | - | auth.tenants, retail.pos_sessions, auth.users |
| cash_closings | RT-007 | - | auth.tenants, retail.pos_sessions, auth.users |
| cash_counts | RT-007 | - | auth.tenants, retail.pos_sessions, auth.users |
| stock_transfers | RT-003 | stock_transfer_lines | auth.tenants, retail.branches(x2), auth.users(x3) |
| stock_transfer_lines | RT-003 | - | auth.tenants, retail.stock_transfers, inventory.products |
| stock_adjustments | RT-003 | stock_adjustment_lines | auth.tenants, retail.branches, auth.users(x2) |
| stock_adjustment_lines | RT-003 | - | auth.tenants, retail.stock_adjustments, inventory.products |
| loyalty_programs | RT-005 | membership_levels, loyalty_transactions, customer_memberships | auth.tenants |
| membership_levels | RT-005 | customer_memberships | auth.tenants, retail.loyalty_programs |
| loyalty_transactions | RT-005 | - | auth.tenants, core.partners, retail.loyalty_programs, retail.pos_orders |
| customer_memberships | RT-005 | - | auth.tenants, core.partners, retail.loyalty_programs, retail.membership_levels |
| promotions | RT-006 | promotion_products | auth.tenants |
| promotion_products | RT-006 | - | auth.tenants, retail.promotions, inventory.products, inventory.product_categories |
| coupons | RT-006 | coupon_redemptions | auth.tenants, core.partners |
| coupon_redemptions | RT-006 | - | auth.tenants, retail.coupons, retail.pos_orders |
| purchase_suggestions | RT-004 | - | auth.tenants, retail.branches, inventory.products, core.partners |
| supplier_orders | RT-004 | supplier_order_lines, goods_receipts | auth.tenants, core.partners, retail.branches, auth.users(x2) |
| supplier_order_lines | RT-004 | - | auth.tenants, retail.supplier_orders, inventory.products |
| goods_receipts | RT-004 | goods_receipt_lines | auth.tenants, retail.supplier_orders, retail.branches, core.partners, auth.users |
| goods_receipt_lines | RT-004 | - | auth.tenants, retail.goods_receipts, inventory.products |
| cfdi_config | RT-010 | - | auth.tenants |
| cfdis | RT-010 | - | auth.tenants |
| carts | RT-009 | cart_items | auth.tenants, core.partners |
| cart_items | RT-009 | - | auth.tenants, retail.carts, inventory.products |
| ecommerce_orders | RT-009 | ecommerce_order_lines, cfdis | auth.tenants, core.partners, retail.branches |
| ecommerce_order_lines | RT-009 | - | auth.tenants, retail.ecommerce_orders, inventory.products |
| shipping_rates | RT-009 | - | auth.tenants |

### 2.3 Impacto en Tablas Existentes

| Tabla Existente | Impacto | Descripcion |
|-----------------|---------|-------------|
| auth.tenants | Referenciada | FK desde todas las tablas retail |
| auth.users | Referenciada | FK desde pos_sessions, cash_*, branch_users, etc. |
| core.partners | Referenciada | FK desde pos_orders, customers, suppliers |
| inventory.products | Referenciada | FK desde pos_order_lines, cart_items, promotion_products |
| inventory.warehouses | Referenciada | FK desde branches |
| inventory.stock_quants | Lectura/Escritura | Para stock por sucursal |
| inventory.product_categories | Referenciada | FK desde promotion_products |

### 2.4 Vistas y Vistas Materializadas

| Objeto | Tipo | Tablas Fuente | Refresh |
|--------|------|---------------|---------|
| retail.branch_stock | VIEW | inventory.stock_quants, retail.branches, inventory.products | Real-time |
| retail.mv_daily_sales | MATERIALIZED VIEW | retail.pos_orders, retail.pos_sessions | Cada hora |
| retail.mv_product_sales | MATERIALIZED VIEW | retail.pos_order_lines, retail.pos_orders, retail.pos_sessions | Cada hora |
| retail.mv_branch_stock_summary | MATERIALIZED VIEW | retail.branches, inventory.stock_quants, inventory.products | Cada hora |

---

## 3. IMPACTO EN BACKEND

### 3.1 Modulos Afectados

| Modulo | Tipo | Servicios | Controllers |
|--------|------|-----------|-------------|
| auth | MODIFICAR | AuthService (actualizar) | - |
| branches | NUEVO | BranchesService, CashRegistersService, BranchUsersService | BranchesController |
| pos | NUEVO | POSSessionService, POSOrderService, POSPaymentService, POSSyncService | POSController |
| cash | NUEVO | CashSessionService, CashMovementService, CashClosingService | CashController |
| inventory | EXTENDER | RetailStockService, TransfersService, AdjustmentsService | InventoryController |
| customers | EXTENDER | RetailCustomersService, LoyaltyService | CustomersController |
| pricing | NUEVO | PriceEngineService, PromotionsService, CouponsService | PricingController |
| purchases | EXTENDER | RetailPurchaseService, PurchaseSuggestionsService, GoodsReceiptService | PurchaseController |
| invoicing | NUEVO | CFDIService, CFDIBuilderService, PACService, XMLService, PDFService, AutofacturaService | CFDIController, AutofacturaController |
| ecommerce | NUEVO | CatalogService, CartService, CheckoutService, PaymentGatewayService, ShippingService, EcommerceOrderService | StorefrontController, EcommerceAdminController |
| reports | EXTENDER | DashboardService, SalesReportService, ProductReportService, CashReportService, ExportService | ReportsController |

### 3.2 Middleware Nuevo

| Middleware | Proposito | Ruta |
|------------|-----------|------|
| TenantMiddleware | Establecer tenant_id en sesion | Global |
| BranchMiddleware | Establecer branch_id en header | /pos/*, /inventory/* |
| AuthMiddleware | Validar JWT | Rutas protegidas |
| PermissionsMiddleware | Validar permisos | Rutas admin |
| OfflineAuthMiddleware | Auth para sync offline | /pos/sync |

### 3.3 Gateways (WebSocket)

| Gateway | Namespace | Eventos |
|---------|-----------|---------|
| POSGateway | /pos | sync:orders, order:created, session:updated |

### 3.4 Integraciones Externas

| Integracion | Provider | Servicios Afectados |
|-------------|----------|---------------------|
| Finkok PAC | PACService | FinkokPAC.timbrar(), FinkokPAC.cancelar() |
| Facturama PAC | PACService | FacturamaPAC.timbrar(), FacturamaPAC.cancelar() |
| Stripe | PaymentGatewayService | StripeGateway.createPayment(), StripeGateway.capture() |
| Conekta | PaymentGatewayService | ConektaGateway.createPayment() |
| MercadoPago | PaymentGatewayService | MercadoPagoGateway.createPayment() |
| Fedex | ShippingService | FedexProvider.calculateRate(), FedexProvider.createShipment() |
| DHL | ShippingService | DHLProvider.calculateRate() |

---

## 4. IMPACTO EN FRONTEND

### 4.1 Aplicaciones

| App | Tipo | Paginas | Componentes |
|-----|------|---------|-------------|
| Backoffice | React SPA | ~35 | ~50 |
| POS | React PWA | ~15 | ~20 |
| Storefront | React SPA | ~15 | ~30 |

### 4.2 Packages Compartidos

| Package | Tipo | Contenido |
|---------|------|-----------|
| @retail/ui-components | Library | Button, Input, Table, Modal, etc. |
| @retail/api-client | Library | Cliente API tipado |
| @retail/hooks | Library | useAuth, useTenant, useBranch, etc. |

### 4.3 Paginas por App

#### Backoffice

| Pagina | Ruta | Modulo |
|--------|------|--------|
| Dashboard | / | RT-008 |
| Stock por Sucursal | /inventory | RT-003 |
| Transferencias | /inventory/transfers | RT-003 |
| Ajustes | /inventory/adjustments | RT-003 |
| Productos | /products | Core |
| Categorias | /products/categories | Core |
| Clientes | /customers | RT-005 |
| Programa Lealtad | /customers/loyalty | RT-005 |
| Listas de Precios | /pricing/pricelists | RT-006 |
| Promociones | /pricing/promotions | RT-006 |
| Cupones | /pricing/coupons | RT-006 |
| Sugerencias Compra | /purchases/suggestions | RT-004 |
| Ordenes Proveedor | /purchases/orders | RT-004 |
| Recepciones | /purchases/receipts | RT-004 |
| Pedidos Online | /ecommerce/orders | RT-009 |
| Tarifas Envio | /ecommerce/shipping | RT-009 |
| Facturas | /invoicing | RT-010 |
| Config CFDI | /invoicing/config | RT-010 |
| Reporte Ventas | /reports/sales | RT-008 |
| Reporte Productos | /reports/products | RT-008 |
| Reporte Inventario | /reports/inventory | RT-008 |
| Reporte Clientes | /reports/customers | RT-008 |
| Reporte Caja | /reports/cash | RT-008 |
| Sucursales | /settings/branches | RT-001 |
| Cajas | /settings/registers | RT-001 |
| Usuarios | /settings/users | Core |

#### POS

| Pagina | Ruta | Modulo |
|--------|------|--------|
| Login | /login | Core |
| Seleccion Caja | /select-register | RT-001 |
| Apertura | /open-session | RT-007 |
| Ventas | /sales | RT-002 |
| Cobro | /sales/checkout | RT-002 |
| Movimientos Caja | /cash/movements | RT-007 |
| Arqueo | /cash/count | RT-007 |
| Cierre | /cash/close | RT-007 |
| Historial | /history | RT-002 |
| Facturar | /invoice/:orderId | RT-010 |
| Cola Offline | /offline | RT-002 |

#### Storefront

| Pagina | Ruta | Modulo |
|--------|------|--------|
| Home | / | RT-009 |
| Catalogo | /products | RT-009 |
| Producto | /products/:id | RT-009 |
| Categoria | /category/:slug | RT-009 |
| Busqueda | /search | RT-009 |
| Carrito | /cart | RT-009 |
| Checkout | /checkout | RT-009 |
| Login | /login | Core |
| Registro | /register | Core |
| Mi Cuenta | /account | RT-009 |
| Mis Pedidos | /account/orders | RT-009 |
| Mis Puntos | /account/loyalty | RT-005 |

### 4.4 PWA Features (POS)

| Feature | Componente |
|---------|------------|
| Service Worker | sw.ts |
| IndexedDB | offline/db.ts (Dexie) |
| Sync Queue | offline/queue.ts |
| Background Sync | offline/sync.ts |
| Push Notifications | Opcional |

### 4.5 Hardware Integration (POS)

| Hardware | Archivo | API |
|----------|---------|-----|
| Impresora ESC/POS | hardware/printer.ts | Web USB, Web Bluetooth, Network |
| Lector Codigo Barras | hardware/scanner.ts | Keyboard Events |
| Cajon Dinero | hardware/drawer.ts | Via Impresora ESC/POS |

---

## 5. ANALISIS DE RIESGOS POR IMPACTO

### 5.1 Riesgos de Base de Datos

| Riesgo | Probabilidad | Impacto | Mitigacion |
|--------|--------------|---------|------------|
| Migraciones fallidas | Media | Alto | Backups antes de cada migracion |
| RLS mal configurado | Baja | Critico | Tests exhaustivos de aislamiento |
| Performance en joins | Media | Medio | Indices optimizados, vistas materializadas |
| Datos inconsistentes offline | Media | Alto | Validacion robusta en sync |

### 5.2 Riesgos de Backend

| Riesgo | Probabilidad | Impacto | Mitigacion |
|--------|--------------|---------|------------|
| Integracion PAC falla | Media | Alto | PAC backup, reintentos |
| Motor precios lento | Baja | Medio | Cache de promociones |
| Sync conflictos | Media | Medio | Estrategia last-write-wins |
| Pasarelas pago | Media | Alto | SDK oficiales, logs detallados |

### 5.3 Riesgos de Frontend

| Riesgo | Probabilidad | Impacto | Mitigacion |
|--------|--------------|---------|------------|
| PWA no funciona offline | Media | Alto | Tests de offline exhaustivos |
| Hardware no compatible | Media | Medio | Fallbacks, documentacion clara |
| Performance en catalogos | Baja | Medio | Paginacion, lazy loading |
| UX confusa en POS | Baja | Medio | Tests de usabilidad |

---

## 6. MATRIZ DE TRAZABILIDAD

### 6.1 Requisitos -> Componentes

| Requisito | Entidad | Servicio | Controller | UI |
|-----------|---------|----------|------------|-----|
| Venta en POS | pos_orders, pos_order_lines | POSOrderService | POSController | Sales.tsx |
| Cobro mixto | pos_payments | POSPaymentService | POSController | Checkout.tsx |
| Puntos lealtad | loyalty_transactions | LoyaltyService | CustomersController | PointsRedemption.tsx |
| Promociones | promotions | PromotionsService, PriceEngineService | PricingController | - |
| Cupones | coupons | CouponsService | PricingController | CouponInput.tsx |
| Transferencias | stock_transfers | TransfersService | InventoryController | TransferForm.tsx |
| Corte caja | cash_closings | CashClosingService | CashController | CashClosing.tsx |
| Facturacion | cfdis | CFDIService | CFDIController | InvoiceModal.tsx |
| Autofactura | cfdis | AutofacturaService | AutofacturaController | AutofacturaPortal.tsx |
| E-commerce | ecommerce_orders | CheckoutService | StorefrontController | Checkout.tsx |

### 6.2 Entidades -> Servicios

| Entidad | Servicios que la usan |
|---------|----------------------|
| branches | BranchesService, POSSessionService, TransfersService, RetailStockService |
| pos_orders | POSOrderService, LoyaltyService, CFDIService, CashClosingService |
| products | POSOrderService, CatalogService, CartService, RetailStockService |
| partners | RetailCustomersService, LoyaltyService, CFDIService |
| promotions | PromotionsService, PriceEngineService |
| coupons | CouponsService, PriceEngineService |
| cfdis | CFDIService, AutofacturaService |

---

## 7. CHECKLIST DE VALIDACION DE IMPACTO

### Database
- [x] Todas las tablas tienen tenant_id
- [x] Todas las tablas tienen RLS policy
- [x] FKs correctamente definidas
- [x] Indices necesarios identificados
- [x] Migraciones en orden correcto
- [x] Columnas generadas (STORED) definidas
- [x] Vistas materializadas planificadas

### Backend
- [x] Servicios identificados para cada entidad
- [x] Herencias de core mapeadas
- [x] Integraciones externas documentadas
- [x] Middleware necesario identificado
- [x] WebSocket gateway planificado
- [x] DTOs definidos implicitamente

### Frontend
- [x] Paginas por app identificadas
- [x] Componentes compartidos definidos
- [x] PWA features planificadas
- [x] Hardware integration documentada
- [x] Store management (Zustand) planificado

### Seguridad
- [x] RLS en todas las tablas
- [x] JWT authentication
- [x] Middleware de tenant
- [x] Middleware de branch
- [x] RBAC pendiente (depende core)

---

## 8. CONCLUSION

### 8.1 Resumen de Impacto

El proyecto Retail impacta:
- **100%** de la capa de datos con schema nuevo
- **100%** del backend con servicios nuevos/extendidos
- **100%** del frontend con 3 aplicaciones nuevas
- **35%** de integraciones (PAC, pagos, envios)

### 8.2 Dependencias Criticas

1. **MGN-005 Catalogs** - Bloqueante para todo retail
2. **MGN-001 Auth** - Bloqueante para autenticacion
3. **MGN-013 Sales** - Bloqueante para precios
4. **MGN-010 Financial** - Bloqueante para POS y facturacion

### 8.3 Recomendaciones

1. **Priorizar core** - No iniciar retail hasta completar prerrequisitos
2. **Tests RLS** - Validar aislamiento de datos antes de produccion
3. **Ambiente sandbox PAC** - Probar facturacion temprano
4. **Hardware testing** - Validar impresoras/scanners en hardware real
5. **PWA testing** - Probar offline en condiciones reales

---

**Estado:** ANALISIS COMPLETO
**Impacto Total:** Alto
**Riesgo Global:** Medio (con mitigaciones)
