# ============================================================================= # BACKEND INVENTORY - ERP CONSTRUCCION # ============================================================================= # Version: 1.0.0 # Ultima actualizacion: 2025-12-06 # Proposito: Inventario canonico de objetos backend # ============================================================================= metadata: proyecto: ERP Construccion version: 1.1.0 fecha_actualizacion: 2025-12-18 base_core: erp-core # ============================================================================= # STACK TECNOLOGICO # ============================================================================= stack: runtime: Node.js 20+ framework: Express.js 4.18+ language: TypeScript 5.3+ orm: TypeORM 0.3.17 database: PostgreSQL 15+ (PostGIS) cache: Redis 7+ storage: MinIO (S3) validation: class-validator + Zod auth: JWT + bcryptjs documentation: Swagger/OpenAPI # ============================================================================= # CONFIGURACION # ============================================================================= configuracion: puerto: 3100 api_prefix: /api/v1 cors_origin: http://localhost:5174 multi_tenant: true rls_enabled: true # ============================================================================= # RESUMEN DE COMPONENTES # ============================================================================= resumen: modulos: 18 services: 73 controllers: 60 endpoints: 345 entities: 125 dtos: 185 guards: 15 decorators: 20 middlewares: 8 # ESTADO REAL DE IMPLEMENTACIÓN (2025-12-18) estado_implementacion: porcentaje: "35%" archivos_ts: 95 entities_implementadas: 70 services_implementados: 10 controllers_implementados: 10 modulos_implementados: construction: entities: [Proyecto, Fraccionamiento, Etapa, Manzana, Lote, Prototipo] services: [ProyectoService, FraccionamientoService, EtapaService, ManzanaService, LoteService, PrototipoService] controllers: [ProyectoController, FraccionamientoController, EtapaController, ManzanaController, LoteController, PrototipoController] estado: "FUNCIONAL" hr: entities: [Employee, Puesto, EmployeeFraccionamiento] services: [] controllers: [] estado: "ENTITIES_COMPLETAS" hse: entities: 58 entities_por_area: incidentes: [Incidente, IncidenteInvolucrado, IncidenteAccion, IncidenteEvidencia, IncidenteInvestigacion] capacitaciones: [Capacitacion, CapacitacionAsistente, CapacitacionSesion, CapacitacionMatriz, ConstanciaDC3] inspecciones: [Inspeccion, ChecklistItem, Hallazgo, HallazgoEvidencia, HallazgoCorreccion, VerificacionCorreccion] epp: [EppCatalogo, EppMatrizPuesto, EppAsignacion, EppInspeccion, EppBaja, EppInventario, EppMovimiento] stps: [NormaStps, NormaRequisito, ComisionSeguridad, ComisionIntegrante, ComisionRecorrido, CumplimientoObra, ProgramaSeguridad, ProgramaActividad, DocumentoStps, Auditoria] ambiental: [ResiduoCatalogo, GeneracionResiduo, AlmacenTemporal, ProveedorAmbiental, ManifiestoResiduo, ManifiestoDetalle, ImpactoAmbiental, QuejaAmbiental] permisos: [TipoPermisoTrabajo, PermisoTrabajo, PermisoPersonal, PermisoAutorizacion, PermisoChecklist, PermisoMonitoreo, PermisoEvento, PermisoDocumento] indicadores: [IndicadorConfig, IndicadorMetaObra, IndicadorValor, HorasTrabajadas, DiasSinAccidente, ReporteProgramado, AlertaIndicador] services: - IncidenteService - CapacitacionService - InspeccionService - EppService - StpsService - AmbientalService - PermisoTrabajoService - IndicadorService controllers: - IncidenteController - CapacitacionController - InspeccionController - EppController - StpsController - AmbientalController - PermisoTrabajoController - IndicadorController estado: "IMPLEMENTADO_COMPLETO" core: entities: [User, Tenant, RefreshToken] estado: "BASE" gap_documentacion_vs_codigo: documentacion_md: 449 archivos_codigo: 95 ratio: "21%" nota: "Gap significativamente reducido - HSE module completamente implementado" herencia_core: version_core: "1.1.0" base: "apps/erp-core/" stack_heredado: runtime: Node.js 20+ framework: Express.js 4.18+ orm: TypeORM 0.3.17 modulos_core_extendidos: - MGN-001 (auth) - MGN-002 (tenants) - MGN-003 (users) - MGN-004 (roles) - MGN-010 (financial) - MGN-011 (inventory) # ============================================================================= # MODULOS BACKEND - FASE 1 # ============================================================================= modulos_fase_1: # --------------------------------------------------------------------------- # MAI-001: Fundamentos # --------------------------------------------------------------------------- - codigo: MAI-001 nombre: fundamentos extiende_core: [MGN-001, MGN-002, MGN-003, MGN-004] ubicacion: src/modules/fundamentos/ services: - nombre: AuthService extiende: CoreAuthService metodos: [login, logout, refresh, validateToken, validateTenantAccess] - nombre: UserService extiende: CoreUserService metodos: [findAll, findById, create, update, delete, assignToProject] - nombre: RoleService extiende: CoreRoleService metodos: [findAll, create, assignPermissions, getProjectRoles] controllers: - nombre: AuthController prefix: /auth endpoints: - { method: POST, path: /login, descripcion: Login multi-tenant } - { method: POST, path: /logout, descripcion: Logout } - { method: POST, path: /refresh, descripcion: Refresh token } - nombre: UserController prefix: /users endpoints: - { method: GET, path: /, descripcion: Listar usuarios } - { method: GET, path: /:id, descripcion: Obtener usuario } - { method: POST, path: /, descripcion: Crear usuario } - { method: PATCH, path: /:id, descripcion: Actualizar usuario } - { method: DELETE, path: /:id, descripcion: Eliminar usuario } - { method: POST, path: /:id/projects, descripcion: Asignar a proyecto } entities: - nombre: User extiende: CoreUser campos_adicionales: [projectAssignments, constructionRole] dtos: 12 guards: [JwtGuard, TenantGuard, RolesGuard, ProjectGuard] # --------------------------------------------------------------------------- # MAI-002: Proyectos y Estructura # --------------------------------------------------------------------------- - codigo: MAI-002 nombre: proyectos ubicacion: src/modules/proyectos/ services: - nombre: FraccionamientoService metodos: [findAll, findById, create, update, delete, getEtapas, getStatistics] - nombre: EtapaService metodos: [findAll, findById, create, update, delete, getManzanas, getTorres] - nombre: ManzanaService metodos: [findAll, findById, create, update, getLotes] - nombre: LoteService metodos: [findAll, findById, create, update, assignPrototipo, getAvance] - nombre: TorreService metodos: [findAll, findById, create, update, getNiveles] - nombre: DepartamentoService metodos: [findAll, findById, create, update, assignPrototipo] - nombre: PrototipoService metodos: [findAll, findById, create, update, delete, getAsignaciones] controllers: - nombre: FraccionamientoController prefix: /fraccionamientos endpoints: - { method: GET, path: /, descripcion: Listar fraccionamientos } - { method: GET, path: /:id, descripcion: Obtener fraccionamiento } - { method: POST, path: /, descripcion: Crear fraccionamiento } - { method: PATCH, path: /:id, descripcion: Actualizar } - { method: DELETE, path: /:id, descripcion: Eliminar } - { method: GET, path: /:id/etapas, descripcion: Obtener etapas } - { method: GET, path: /:id/statistics, descripcion: Estadisticas } - nombre: EtapaController prefix: /etapas endpoints: 8 - nombre: UnidadesController prefix: /unidades endpoints: 12 descripcion: Maneja manzanas, lotes, torres, departamentos - nombre: PrototipoController prefix: /prototipos endpoints: 6 entities: - nombre: Fraccionamiento tabla: project_management.fraccionamientos campos: [id, tenant_id, codigo, nombre, ubicacion_geo, tipo, estado] - nombre: Etapa tabla: project_management.etapas campos: [id, fraccionamiento_id, numero, nombre, fecha_inicio, fecha_fin] - nombre: Manzana tabla: project_management.manzanas campos: [id, etapa_id, numero, total_lotes] - nombre: Lote tabla: project_management.lotes campos: [id, manzana_id, numero, superficie, prototipo_id, estado] - nombre: Torre tabla: project_management.torres campos: [id, etapa_id, numero, niveles_count] - nombre: Departamento tabla: project_management.departamentos campos: [id, torre_id, nivel, numero, prototipo_id, estado] - nombre: Prototipo tabla: project_management.prototipos campos: [id, codigo, nombre, superficie, recamaras, banos, precio_base] dtos: 18 endpoints_total: 35 # --------------------------------------------------------------------------- # MAI-003: Presupuestos y Costos # --------------------------------------------------------------------------- - codigo: MAI-003 nombre: presupuestos ubicacion: src/modules/presupuestos/ services: - nombre: PresupuestoService metodos: [findAll, findById, create, update, clone, compareVsReal] - nombre: PartidaService metodos: [findAll, findById, create, update, getSubpartidas] - nombre: ConceptoService metodos: [findAll, findById, create, update, getInsumos, calculatePU] - nombre: InsumoService metodos: [findAll, findById, create, update, explosion] controllers: - nombre: PresupuestoController prefix: /presupuestos endpoints: 12 - nombre: PartidaController prefix: /partidas endpoints: 8 - nombre: ConceptoController prefix: /conceptos endpoints: 10 entities: - nombre: Presupuesto tabla: financial_management.presupuestos campos: [id, proyecto_id, version, monto_total, estado] - nombre: Partida tabla: financial_management.partidas campos: [id, presupuesto_id, codigo, nombre, monto] - nombre: Subpartida tabla: financial_management.subpartidas campos: [id, partida_id, codigo, nombre, monto] - nombre: Concepto tabla: financial_management.conceptos campos: [id, subpartida_id, codigo, descripcion, unidad, cantidad, pu, importe] dtos: 16 endpoints_total: 30 # --------------------------------------------------------------------------- # MAI-004: Compras e Inventarios # --------------------------------------------------------------------------- - codigo: MAI-004 nombre: compras ubicacion: src/modules/compras/ extiende_core: [MGN-011] services: - nombre: RequisicionService metodos: [findAll, findById, create, approve, reject, convertToOC] - nombre: OrdenCompraService metodos: [findAll, findById, create, send, receive, cancel] - nombre: AlmacenService metodos: [findAll, findById, create, getInventario] - nombre: MovimientoService metodos: [entrada, salida, transferencia, ajuste] controllers: - nombre: RequisicionController prefix: /requisiciones endpoints: 8 - nombre: OrdenCompraController prefix: /ordenes-compra endpoints: 10 - nombre: AlmacenController prefix: /almacenes endpoints: 8 - nombre: InventarioController prefix: /inventario endpoints: 10 entities: 8 dtos: 20 endpoints_total: 36 # --------------------------------------------------------------------------- # MAI-005: Control de Obra # --------------------------------------------------------------------------- - codigo: MAI-005 nombre: control-obra ubicacion: src/modules/control-obra/ services: - nombre: AvanceService metodos: [registrar, findByUnidad, findByConcepto, getResumen] - nombre: RecursoService metodos: [asignar, reasignar, liberar, getDisponibilidad] - nombre: BitacoraService metodos: [createEntry, findByFecha, findByProyecto, exportar] - nombre: FotoEvidenciaService metodos: [upload, findByAvance, delete, getGeolocated] controllers: - nombre: AvanceController prefix: /avances endpoints: 12 - nombre: RecursoController prefix: /recursos endpoints: 8 - nombre: BitacoraController prefix: /bitacora endpoints: 6 entities: - nombre: Avance tabla: construction_management.avances campos: [id, unidad_id, concepto_id, porcentaje, fecha, evidencia_fotos] - nombre: RecursoAsignado tabla: construction_management.recursos_asignados campos: [id, proyecto_id, tipo, cantidad, fecha_asignacion] - nombre: BitacoraEntrada tabla: construction_management.bitacora_entradas campos: [id, proyecto_id, fecha, descripcion, usuario_id] dtos: 14 endpoints_total: 26 # --------------------------------------------------------------------------- # MAI-006 a MAI-018 (resumen) # --------------------------------------------------------------------------- - codigo: MAI-006 nombre: reportes services: 4 controllers: 2 endpoints: 15 dtos: 8 - codigo: MAI-007 nombre: rrhh services: 5 controllers: 4 endpoints: 22 dtos: 18 especial: [biometrico, geolocalizacion, destajo] - codigo: MAI-008 nombre: estimaciones services: 4 controllers: 3 endpoints: 18 dtos: 16 directiva: DIRECTIVA-ESTIMACIONES.md - codigo: MAI-009 nombre: calidad services: 3 controllers: 2 endpoints: 12 dtos: 10 - codigo: MAI-010 nombre: crm services: 4 controllers: 3 endpoints: 16 dtos: 14 - codigo: MAI-011 nombre: infonavit services: 5 controllers: 3 endpoints: 20 dtos: 18 directiva: DIRECTIVA-INTEGRACION-INFONAVIT.md - codigo: MAI-012 nombre: contratos services: 3 controllers: 2 endpoints: 14 dtos: 12 - codigo: MAI-013 nombre: administracion services: 4 controllers: 3 endpoints: 18 dtos: 14 # --------------------------------------------------------------------------- # MAI-017: HSE (Salud, Seguridad y Medio Ambiente) - IMPLEMENTADO # --------------------------------------------------------------------------- - codigo: MAI-017 nombre: hse ubicacion: src/modules/hse/ estado: IMPLEMENTADO_COMPLETO fecha_implementacion: 2025-12-18 services: - nombre: IncidenteService metodos: [findAll, findById, create, updateEstado, addInvolucrado, addAccion, getStats] requerimiento: RF-MAA017-001 - nombre: CapacitacionService metodos: [findAll, findById, create, update, addSesion, addAsistente, generateDC3, getMatriz] requerimiento: RF-MAA017-002 - nombre: InspeccionService metodos: [findAll, findById, create, addHallazgo, addCorreccion, verificarCorreccion, getStats] requerimiento: RF-MAA017-003 - nombre: EppService metodos: [findCatalogo, createEpp, getMatrizPuesto, asignarEpp, registrarBaja, getInventario, getStats] requerimiento: RF-MAA017-004 - nombre: StpsService metodos: [findNormas, createComision, addRecorrido, createPrograma, addActividad, getCumplimiento, getStats] requerimiento: RF-MAA017-005 - nombre: AmbientalService metodos: [findResiduos, registrarGeneracion, createManifiesto, addDetalle, registrarImpacto, getStats] requerimiento: RF-MAA017-006 - nombre: PermisoTrabajoService metodos: [findTipos, findPermisos, create, updateEstado, addPersonal, addAutorizacion, getStats] requerimiento: RF-MAA017-007 - nombre: IndicadorService metodos: [findIndicadores, createIndicador, setMeta, registrarValor, getHorasTrabajadas, getDiasSinAccidente, getAlertas] requerimiento: RF-MAA017-008 controllers: - nombre: IncidenteController prefix: /incidentes endpoints: - { method: GET, path: /, descripcion: Listar incidentes } - { method: GET, path: /stats, descripcion: Estadisticas } - { method: GET, path: /:id, descripcion: Obtener incidente } - { method: POST, path: /, descripcion: Crear incidente } - { method: PATCH, path: /:id/estado, descripcion: Cambiar estado } - { method: POST, path: /:id/involucrados, descripcion: Agregar involucrado } - { method: POST, path: /:id/acciones, descripcion: Agregar accion } - nombre: CapacitacionController prefix: /capacitaciones endpoints: - { method: GET, path: /, descripcion: Listar capacitaciones } - { method: GET, path: /matriz, descripcion: Matriz de capacitacion } - { method: GET, path: /:id, descripcion: Obtener capacitacion } - { method: POST, path: /, descripcion: Crear capacitacion } - { method: POST, path: /:id/sesiones, descripcion: Agregar sesion } - { method: POST, path: /:id/asistentes, descripcion: Agregar asistente } - { method: POST, path: /dc3/:asistenciaId, descripcion: Generar DC3 } - nombre: InspeccionController prefix: /inspecciones endpoints: - { method: GET, path: /, descripcion: Listar inspecciones } - { method: GET, path: /stats, descripcion: Estadisticas } - { method: GET, path: /:id, descripcion: Obtener inspeccion } - { method: POST, path: /, descripcion: Crear inspeccion } - { method: POST, path: /:id/hallazgos, descripcion: Agregar hallazgo } - { method: POST, path: /hallazgos/:id/correcciones, descripcion: Agregar correccion } - nombre: EppController prefix: /epp endpoints: - { method: GET, path: /catalogo, descripcion: Catalogo EPP } - { method: GET, path: /matriz, descripcion: Matriz por puesto } - { method: GET, path: /asignaciones, descripcion: Asignaciones } - { method: GET, path: /inventario, descripcion: Inventario } - { method: POST, path: /asignaciones, descripcion: Asignar EPP } - { method: POST, path: /bajas, descripcion: Registrar baja } - nombre: StpsController prefix: /stps endpoints: - { method: GET, path: /normas, descripcion: Normas STPS } - { method: GET, path: /comisiones, descripcion: Comisiones seguridad } - { method: GET, path: /programas, descripcion: Programas seguridad } - { method: GET, path: /cumplimiento, descripcion: Cumplimiento por obra } - { method: POST, path: /comisiones, descripcion: Crear comision } - { method: POST, path: /comisiones/:id/recorridos, descripcion: Registrar recorrido } - nombre: AmbientalController prefix: /ambiental endpoints: - { method: GET, path: /residuos, descripcion: Catalogo residuos } - { method: GET, path: /manifiestos, descripcion: Manifiestos } - { method: GET, path: /impactos, descripcion: Impactos ambientales } - { method: POST, path: /generaciones, descripcion: Registrar generacion } - { method: POST, path: /manifiestos, descripcion: Crear manifiesto } - nombre: PermisoTrabajoController prefix: /permisos-trabajo endpoints: - { method: GET, path: /tipos, descripcion: Tipos de permiso } - { method: GET, path: /, descripcion: Listar permisos } - { method: GET, path: /stats, descripcion: Estadisticas } - { method: GET, path: /:id, descripcion: Obtener permiso } - { method: POST, path: /, descripcion: Crear permiso } - { method: PATCH, path: /:id/estado, descripcion: Cambiar estado } - nombre: IndicadorController prefix: /indicadores endpoints: - { method: GET, path: /, descripcion: Listar indicadores } - { method: GET, path: /stats, descripcion: Estadisticas } - { method: GET, path: /alertas/list, descripcion: Alertas activas } - { method: GET, path: /:id/valores, descripcion: Valores historicos } - { method: POST, path: /, descripcion: Crear indicador } entities: 58 dtos: 45 endpoints_total: 65 - codigo: MAI-018 nombre: preconstruccion services: 3 controllers: 2 endpoints: 12 dtos: 10 # ============================================================================= # MODULOS BACKEND - FASE 2 # ============================================================================= modulos_fase_2: - codigo: MAE-014 nombre: finanzas extiende_core: [MGN-010] services: 6 controllers: 4 endpoints: 25 dtos: 20 - codigo: MAE-015 nombre: activos services: 4 controllers: 3 endpoints: 18 dtos: 14 - codigo: MAE-016 nombre: documentos services: 4 controllers: 2 endpoints: 15 dtos: 12 # ============================================================================= # COMPONENTES COMPARTIDOS # ============================================================================= shared: guards: - nombre: JwtAuthGuard ubicacion: src/shared/guards/jwt-auth.guard.ts descripcion: Validacion JWT - nombre: TenantGuard ubicacion: src/shared/guards/tenant.guard.ts descripcion: Validacion de tenant en header - nombre: RolesGuard ubicacion: src/shared/guards/roles.guard.ts descripcion: Validacion RBAC - nombre: ProjectGuard ubicacion: src/shared/guards/project.guard.ts descripcion: Validacion acceso a proyecto especifico decorators: - nombre: CurrentUser descripcion: Obtiene usuario actual de request - nombre: CurrentTenant descripcion: Obtiene tenant_id del header - nombre: Roles descripcion: Define roles permitidos para endpoint - nombre: ProjectAccess descripcion: Valida acceso a proyecto middlewares: - nombre: TenantMiddleware descripcion: Extrae y valida X-Tenant-Id header - nombre: LoggerMiddleware descripcion: Logging de requests - nombre: RateLimitMiddleware descripcion: Rate limiting por IP/tenant interceptors: - nombre: TransformInterceptor descripcion: Transforma responses al formato estandar - nombre: TimeoutInterceptor descripcion: Manejo de timeouts - nombre: CacheInterceptor descripcion: Cache de responses filters: - nombre: HttpExceptionFilter descripcion: Manejo global de excepciones - nombre: ValidationExceptionFilter descripcion: Errores de validacion DTO # ============================================================================= # ESTRUCTURA DE CARPETAS # ============================================================================= estructura: - path: src/ contenido: - path: config/ descripcion: Configuraciones (database, redis, s3) - path: modules/ descripcion: Modulos de negocio MAI/MAE - path: shared/ contenido: - guards/ - decorators/ - middlewares/ - interceptors/ - filters/ - utils/ - types/ - constants/ - path: database/ descripcion: Entities base, migrations - path: app.ts descripcion: Configuracion Express - path: server.ts descripcion: Punto de entrada # ============================================================================= # METADATA # ============================================================================= metadata: creado_por: Requirements-Analyst fecha_creacion: 2025-12-06 ultima_actualizacion: 2025-12-06 version_documento: 1.0.0