workspace/core/orchestration/procesos/ORDEN-IMPLEMENTACION.md
rckrdmrd 2781837d9e feat: Add SaaS products architecture and alignment analysis
Analysis and Documentation:
- Add ANALISIS-ALINEACION-WORKSPACE-2025-12-08.md with comprehensive gap analysis
- Document SIMCO v3.2 system with 20+ directives
- Identify alignment gaps between orchestration and projects

New SaaS Products Structure:
- Create apps/products/pos-micro/ - Ultra basic POS (~100 MXN/month)
  - Target: Mexican informal market (street vendors, small stores)
  - Features: Offline-first PWA, WhatsApp bot, minimal DB (~10 tables)
- Create apps/products/erp-basico/ - Austere ERP (~300-500 MXN/month)
  - Target: SMBs needing full ERP without complexity
  - Features: Inherits from erp-core, modular pricing

SaaS Layer:
- Create apps/saas/ structure (billing, portal, admin, onboarding)
- Add README.md and CONTEXTO-SAAS.md documentation

Vertical Alignment:
- Verify HERENCIA-ERP-CORE.md exists in all verticals
- Add HERENCIA-SPECS-CORE.md to verticals
- Update orchestration inventories

Updates:
- Update WORKSPACE-STATUS.md with new products and analysis
- Update suite inventories with new structure

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-08 11:34:35 -06:00

17 KiB

ORDEN DE IMPLEMENTACIÓN

Versión: 1.0.0 Fecha: 2025-12-08 Prioridad: OBLIGATORIA - DDL-First Sistema: SIMCO + CAPVED


PROPÓSITO

Definir el orden correcto de implementación cuando una tarea toca múltiples capas.


PRINCIPIO FUNDAMENTAL

╔══════════════════════════════════════════════════════════════════════╗
║  DDL-FIRST: La Base de Datos es la Fuente de Verdad                  ║
║                                                                       ║
║  ORDEN OBLIGATORIO:                                                  ║
║                                                                       ║
║  1. DATABASE  → Tablas existen                                       ║
║  2. BACKEND   → Entity refleja DDL                                   ║
║  3. FRONTEND  → Types reflejan DTOs                                  ║
║                                                                       ║
║  ⚠️  NUNCA invertir este orden                                       ║
╚══════════════════════════════════════════════════════════════════════╝

1. FLUJO COMPLETO DE IMPLEMENTACIÓN

┌─────────────────────────────────────────────────────────────────────┐
│                    FASE 1: BASE DE DATOS                            │
│                    (Database-Agent)                                  │
├─────────────────────────────────────────────────────────────────────┤
│ [ ] 1.1 Crear/modificar archivo DDL                                 │
│ [ ] 1.2 Definir columnas con tipos correctos                        │
│ [ ] 1.3 Definir PK, FK, constraints                                 │
│ [ ] 1.4 Crear índices necesarios                                    │
│ [ ] 1.5 Ejecutar carga limpia (recreate-database.sh)                │
│ [ ] 1.6 Verificar con \dt, \d {tabla}                               │
│ [ ] 1.7 Actualizar DATABASE_INVENTORY.yml                           │
│ [ ] 1.8 Registrar en TRAZA-TAREAS-DATABASE.md                       │
│                                                                      │
│ GATE: Carga limpia exitosa antes de continuar                       │
└─────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────┐
│                    FASE 2: BACKEND                                   │
│                    (Backend-Agent)                                   │
├─────────────────────────────────────────────────────────────────────┤
│ [ ] 2.1 Crear Entity alineada con DDL (ver MAPEO-TIPOS.md)          │
│ [ ] 2.2 Crear CreateDto con validaciones                            │
│ [ ] 2.3 Crear UpdateDto (extends PartialType)                       │
│ [ ] 2.4 Crear ResponseDto                                           │
│ [ ] 2.5 Crear Service con lógica de negocio                         │
│ [ ] 2.6 Crear Controller con Swagger decorators                     │
│ [ ] 2.7 Registrar en Module                                         │
│ [ ] 2.8 Ejecutar: npm run build                                     │
│ [ ] 2.9 Ejecutar: npm run lint                                      │
│ [ ] 2.10 Ejecutar: npm run test (si hay tests)                      │
│ [ ] 2.11 Actualizar BACKEND_INVENTORY.yml                           │
│ [ ] 2.12 Registrar en TRAZA-TAREAS-BACKEND.md                       │
│                                                                      │
│ GATE: Build y lint pasan antes de continuar                         │
└─────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────┐
│                    FASE 3: FRONTEND                                  │
│                    (Frontend-Agent)                                  │
├─────────────────────────────────────────────────────────────────────┤
│ [ ] 3.1 Crear types/interfaces (alineados con ResponseDto)          │
│ [ ] 3.2 Crear Zod schema (alineado con CreateDto)                   │
│ [ ] 3.3 Crear API service                                           │
│ [ ] 3.4 Crear custom hook (useQuery/useMutation)                    │
│ [ ] 3.5 Crear componentes necesarios                                │
│ [ ] 3.6 Crear página/formulario                                     │
│ [ ] 3.7 Ejecutar: npm run build                                     │
│ [ ] 3.8 Ejecutar: npm run lint                                      │
│ [ ] 3.9 Ejecutar: npm run typecheck                                 │
│ [ ] 3.10 Actualizar FRONTEND_INVENTORY.yml                          │
│ [ ] 3.11 Registrar en TRAZA-TAREAS-FRONTEND.md                      │
│                                                                      │
│ GATE: Build, lint y typecheck pasan                                 │
└─────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────┐
│                    FASE 4: INTEGRACIÓN                               │
│                    (Orquestador)                                     │
├─────────────────────────────────────────────────────────────────────┤
│ [ ] 4.1 Verificar flujo completo funciona                           │
│ [ ] 4.2 Verificar Swagger documenta correctamente                   │
│ [ ] 4.3 Tests e2e (si existen)                                      │
│ [ ] 4.4 Actualizar MASTER_INVENTORY.yml                             │
│ [ ] 4.5 Actualizar PROXIMA-ACCION.md                                │
│ [ ] 4.6 Propagar a niveles superiores (SIMCO-PROPAGACION.md)        │
│                                                                      │
│ GATE: Todo funciona end-to-end                                      │
└─────────────────────────────────────────────────────────────────────┘

2. POR QUÉ DDL-FIRST

Problema: Backend-First

// Alguien crea Entity primero sin DDL...
@Entity()
export class ProductEntity {
    @Column()
    price: number;  // ← Asume que existe en BD
}

// Resultado:
// - TypeORM syncronize: Crea tabla con tipos incorrectos
// - Sin syncronize: Error en runtime "column not found"
// - Nadie sabe qué tipo debería ser price (DECIMAL? NUMERIC? INTEGER?)

Solución: DDL-First

-- 1. DDL define la verdad
CREATE TABLE products (
    price DECIMAL(10,2) NOT NULL  -- Explícito: 10 dígitos, 2 decimales
);
// 2. Entity REFLEJA la verdad
@Column({ type: 'decimal', precision: 10, scale: 2 })
price: string;  // String para precisión decimal

// 3. DTO documenta para Swagger
@ApiProperty({ example: 99.99 })
@IsNumber({ maxDecimalPlaces: 2 })
price: number;

3. DEPENDENCIAS ENTRE CAPAS

Diagrama de Dependencias

                    ┌──────────────┐
                    │   DATABASE   │
                    │    (DDL)     │
                    └──────┬───────┘
                           │
                           │ Entity refleja DDL
                           ▼
                    ┌──────────────┐
                    │   BACKEND    │
                    │ (Entity,DTO) │
                    └──────┬───────┘
                           │
                           │ Types reflejan DTOs
                           ▼
                    ┌──────────────┐
                    │   FRONTEND   │
                    │(Types,Forms) │
                    └──────────────┘

Reglas de Dependencia

Si cambias... Debes actualizar... En ese orden
DDL columna Entity → DTO → Types DDL → BE → FE
Entity campo DTO → Types BE → FE
DTO campo Types BE → FE
Types - FE solo

4. ANTI-PATRONES DE ORDEN

Anti-Patrón 1: Frontend First

❌ INCORRECTO:
1. Frontend-Agent crea formulario
2. Backend-Agent crea endpoint
3. Database-Agent... ¿qué campos necesita?

RESULTADO:
- Frontend asume campos que no existen
- Backend inventa estructura
- Database no sabe qué crear
- Retrabajos múltiples

Anti-Patrón 2: Parallel sin Coordinación

❌ INCORRECTO:
1. Database-Agent crea tabla (en paralelo)
2. Backend-Agent crea entity (en paralelo)
3. Frontend-Agent crea types (en paralelo)

RESULTADO:
- Cada uno asume diferente
- Tipos no coinciden
- Errores en integración

Anti-Patrón 3: Saltar Validación

❌ INCORRECTO:
1. Database-Agent crea tabla (OK)
2. Backend-Agent crea entity (sin build)
3. Frontend-Agent crea types (sin typecheck)

RESULTADO:
- Errores no detectados hasta runtime
- Bugs en producción
- Debug difícil

5. TEMPLATES POR CASO

Caso A: Feature Nueva Completa

TAREA: Crear sistema de comentarios

FASE 1: DATABASE (Database-Agent)
═══════════════════════════════════════════════════════════════
Crear: schemas/core/tables/05-comments.sql

CREATE TABLE core.comments (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    content TEXT NOT NULL,
    user_id UUID NOT NULL REFERENCES auth.users(id),
    post_id UUID NOT NULL REFERENCES core.posts(id),
    parent_id UUID REFERENCES core.comments(id),
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

CREATE INDEX idx_comments_post ON core.comments(post_id);
CREATE INDEX idx_comments_user ON core.comments(user_id);

Validar: ./recreate-database.sh && psql -c "\d core.comments"

FASE 2: BACKEND (Backend-Agent)
═══════════════════════════════════════════════════════════════
Crear:
- modules/comment/entities/comment.entity.ts
- modules/comment/dto/create-comment.dto.ts
- modules/comment/dto/update-comment.dto.ts
- modules/comment/dto/comment-response.dto.ts
- modules/comment/services/comment.service.ts
- modules/comment/controllers/comment.controller.ts
- modules/comment/comment.module.ts

Validar: npm run build && npm run lint

FASE 3: FRONTEND (Frontend-Agent)
═══════════════════════════════════════════════════════════════
Crear:
- shared/types/comment.types.ts
- shared/services/comment.service.ts
- apps/web/hooks/useComments.ts
- apps/web/components/comments/CommentCard.tsx
- apps/web/components/comments/CommentForm.tsx
- apps/web/components/comments/CommentList.tsx

Validar: npm run build && npm run lint && npm run typecheck

FASE 4: INTEGRACIÓN
═══════════════════════════════════════════════════════════════
- Test flujo completo
- Verificar Swagger
- Actualizar inventarios

Caso B: Agregar Campo a Feature Existente

TAREA: Agregar campo "rating" a comments

FASE 1: DATABASE
═══════════════════════════════════════════════════════════════
ALTER TABLE core.comments ADD COLUMN rating INTEGER CHECK (rating BETWEEN 1 AND 5);

Validar: Carga limpia

FASE 2: BACKEND
═══════════════════════════════════════════════════════════════
- Agregar @Column en CommentEntity
- Agregar campo en CreateCommentDto con @IsInt @Min(1) @Max(5)
- Agregar en ResponseDto

Validar: npm run build

FASE 3: FRONTEND
═══════════════════════════════════════════════════════════════
- Agregar rating en Comment interface
- Agregar input en CommentForm
- Mostrar en CommentCard

Validar: npm run build && npm run typecheck

Caso C: Cambio Solo en Backend (Nueva Lógica)

TAREA: Agregar validación de spam en comentarios

FASE 1: DATABASE
═══════════════════════════════════════════════════════════════
- SIN CAMBIOS (lógica no afecta schema)

FASE 2: BACKEND
═══════════════════════════════════════════════════════════════
- Agregar SpamService
- Modificar CommentService.create() para validar

Validar: npm run build && npm run test

FASE 3: FRONTEND
═══════════════════════════════════════════════════════════════
- SIN CAMBIOS (endpoint sigue igual)
- Posible: Mostrar error si spam detectado

6. CHECKLIST RÁPIDO

Antes de empezar implementación:
[ ] ¿La tabla existe en DDL? Si no → DATABASE primero
[ ] ¿Entity refleja DDL actual? Si no → Actualizar Entity
[ ] ¿DTOs coinciden con Entity? Si no → Actualizar DTOs
[ ] ¿Types coinciden con DTOs? Si no → Actualizar Types

Durante implementación:
[ ] No crear Entity sin DDL
[ ] No crear Types sin DTOs
[ ] No modificar DDL sin actualizar Entity
[ ] No modificar DTO sin actualizar Types

Después de cada capa:
[ ] Build pasa
[ ] Lint pasa
[ ] Tests pasan (si existen)
[ ] Inventario actualizado

7. COMANDOS DE VALIDACIÓN

# FASE 1: Validar Database
cd {DB_SCRIPTS_PATH}
./recreate-database.sh
psql -d {DB_NAME} -c "\dt {schema}.*"
psql -d {DB_NAME} -c "\d {schema}.{tabla}"

# FASE 2: Validar Backend
cd {BACKEND_ROOT}
npm run build
npm run lint
npm run test

# FASE 3: Validar Frontend
cd {FRONTEND_ROOT}
npm run build
npm run lint
npm run typecheck

# FASE 4: Validar Integración
curl http://localhost:3000/api/{endpoint}
# Verificar respuesta correcta

8. MATRIZ DE DELEGACIÓN

Tarea Database-Agent Backend-Agent Frontend-Agent Orquestador
Crear tabla Coordina
Modificar DDL Coordina
Crear Entity Verifica
Crear DTO Verifica
Crear Service Verifica
Crear Controller Verifica
Crear Types Verifica
Crear Component Verifica
Integración

Versión: 1.0.0 | Sistema: SIMCO | Tipo: Guía de Proceso