erp-construccion-backend/dist/modules/hr/controllers/employee.controller.js

288 lines
11 KiB
JavaScript

"use strict";
/**
* EmployeeController - Controller de empleados
*
* Endpoints REST para gestión de empleados y asignaciones a obras.
*
* @module HR
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createEmployeeController = createEmployeeController;
const express_1 = require("express");
const employee_service_1 = require("../services/employee.service");
const auth_middleware_1 = require("../../auth/middleware/auth.middleware");
const auth_service_1 = require("../../auth/services/auth.service");
const employee_entity_1 = require("../entities/employee.entity");
const employee_fraccionamiento_entity_1 = require("../entities/employee-fraccionamiento.entity");
const user_entity_1 = require("../../core/entities/user.entity");
const tenant_entity_1 = require("../../core/entities/tenant.entity");
const refresh_token_entity_1 = require("../../auth/entities/refresh-token.entity");
/**
* Crear router de empleados
*/
function createEmployeeController(dataSource) {
const router = (0, express_1.Router)();
// Repositorios
const employeeRepository = dataSource.getRepository(employee_entity_1.Employee);
const asignacionRepository = dataSource.getRepository(employee_fraccionamiento_entity_1.EmployeeFraccionamiento);
const userRepository = dataSource.getRepository(user_entity_1.User);
const tenantRepository = dataSource.getRepository(tenant_entity_1.Tenant);
const refreshTokenRepository = dataSource.getRepository(refresh_token_entity_1.RefreshToken);
// Servicios
const employeeService = new employee_service_1.EmployeeService(employeeRepository, asignacionRepository);
const authService = new auth_service_1.AuthService(userRepository, tenantRepository, refreshTokenRepository);
const authMiddleware = new auth_middleware_1.AuthMiddleware(authService, dataSource);
// Helper para crear contexto de servicio
const getContext = (req) => {
if (!req.tenantId) {
throw new Error('Tenant ID is required');
}
return {
tenantId: req.tenantId,
userId: req.user?.sub,
};
};
/**
* GET /empleados
* Listar empleados con filtros
*/
router.get('/', authMiddleware.authenticate, async (req, res, next) => {
try {
const tenantId = req.tenantId;
if (!tenantId) {
res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
return;
}
const page = parseInt(req.query.page) || 1;
const limit = Math.min(parseInt(req.query.limit) || 20, 100);
const filters = {
estado: req.query.estado,
puestoId: req.query.puestoId,
departamento: req.query.departamento,
fraccionamientoId: req.query.fraccionamientoId,
search: req.query.search,
};
const result = await employeeService.findWithFilters(getContext(req), filters, page, limit);
res.status(200).json({
success: true,
data: result.data,
pagination: result.meta,
});
}
catch (error) {
next(error);
}
});
/**
* GET /empleados/stats
* Obtener estadísticas de empleados
*/
router.get('/stats', authMiddleware.authenticate, async (req, res, next) => {
try {
const tenantId = req.tenantId;
if (!tenantId) {
res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
return;
}
const stats = await employeeService.getStats(getContext(req));
res.status(200).json({ success: true, data: stats });
}
catch (error) {
next(error);
}
});
/**
* GET /empleados/by-fraccionamiento/:fraccionamientoId
* Obtener empleados asignados a un fraccionamiento
*/
router.get('/by-fraccionamiento/:fraccionamientoId', authMiddleware.authenticate, async (req, res, next) => {
try {
const tenantId = req.tenantId;
if (!tenantId) {
res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
return;
}
const employees = await employeeService.getEmployeesByFraccionamiento(getContext(req), req.params.fraccionamientoId);
res.status(200).json({ success: true, data: employees });
}
catch (error) {
next(error);
}
});
/**
* GET /empleados/:id
* Obtener empleado por ID con detalles
*/
router.get('/:id', authMiddleware.authenticate, async (req, res, next) => {
try {
const tenantId = req.tenantId;
if (!tenantId) {
res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
return;
}
const employee = await employeeService.findById(getContext(req), req.params.id);
if (!employee) {
res.status(404).json({ error: 'Not Found', message: 'Employee not found' });
return;
}
res.status(200).json({ success: true, data: employee });
}
catch (error) {
next(error);
}
});
/**
* POST /empleados
* Crear empleado
*/
router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director'), async (req, res, next) => {
try {
const tenantId = req.tenantId;
if (!tenantId) {
res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
return;
}
const dto = req.body;
if (!dto.codigo || !dto.nombre || !dto.apellidoPaterno || !dto.fechaIngreso) {
res.status(400).json({
error: 'Bad Request',
message: 'codigo, nombre, apellidoPaterno and fechaIngreso are required',
});
return;
}
const employee = await employeeService.create(getContext(req), dto);
res.status(201).json({ success: true, data: employee });
}
catch (error) {
if (error instanceof Error && error.message.includes('already exists')) {
res.status(409).json({ error: 'Conflict', message: error.message });
return;
}
next(error);
}
});
/**
* PATCH /empleados/:id
* Actualizar empleado
*/
router.patch('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director'), async (req, res, next) => {
try {
const tenantId = req.tenantId;
if (!tenantId) {
res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
return;
}
const dto = req.body;
const employee = await employeeService.update(getContext(req), req.params.id, dto);
if (!employee) {
res.status(404).json({ error: 'Not Found', message: 'Employee not found' });
return;
}
res.status(200).json({ success: true, data: employee });
}
catch (error) {
if (error instanceof Error && error.message.includes('already exists')) {
res.status(409).json({ error: 'Conflict', message: error.message });
return;
}
next(error);
}
});
/**
* POST /empleados/:id/status
* Cambiar estado del empleado
*/
router.post('/:id/status', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director'), async (req, res, next) => {
try {
const tenantId = req.tenantId;
if (!tenantId) {
res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
return;
}
const { estado, fechaBaja } = req.body;
if (!estado || !['activo', 'inactivo', 'baja'].includes(estado)) {
res.status(400).json({
error: 'Bad Request',
message: 'estado must be one of: activo, inactivo, baja',
});
return;
}
const employee = await employeeService.changeStatus(getContext(req), req.params.id, estado, fechaBaja ? new Date(fechaBaja) : undefined);
if (!employee) {
res.status(404).json({ error: 'Not Found', message: 'Employee not found' });
return;
}
res.status(200).json({
success: true,
data: employee,
message: `Employee status changed to ${estado}`,
});
}
catch (error) {
next(error);
}
});
/**
* POST /empleados/:id/assign
* Asignar empleado a fraccionamiento
*/
router.post('/:id/assign', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'engineer'), async (req, res, next) => {
try {
const tenantId = req.tenantId;
if (!tenantId) {
res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
return;
}
const dto = req.body;
if (!dto.fraccionamientoId || !dto.fechaInicio) {
res.status(400).json({
error: 'Bad Request',
message: 'fraccionamientoId and fechaInicio are required',
});
return;
}
dto.fechaInicio = new Date(dto.fechaInicio);
if (dto.fechaFin) {
dto.fechaFin = new Date(dto.fechaFin);
}
const asignacion = await employeeService.assignToFraccionamiento(getContext(req), req.params.id, dto);
res.status(201).json({
success: true,
data: asignacion,
message: 'Employee assigned to project',
});
}
catch (error) {
if (error instanceof Error && error.message === 'Employee not found') {
res.status(404).json({ error: 'Not Found', message: error.message });
return;
}
next(error);
}
});
/**
* DELETE /empleados/:id/assign/:fraccionamientoId
* Remover empleado de fraccionamiento
*/
router.delete('/:id/assign/:fraccionamientoId', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'engineer'), async (req, res, next) => {
try {
const tenantId = req.tenantId;
if (!tenantId) {
res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
return;
}
const removed = await employeeService.removeFromFraccionamiento(getContext(req), req.params.id, req.params.fraccionamientoId);
if (!removed) {
res.status(404).json({ error: 'Not Found', message: 'Assignment not found' });
return;
}
res.status(200).json({ success: true, message: 'Employee removed from project' });
}
catch (error) {
next(error);
}
});
return router;
}
exports.default = createEmployeeController;
//# sourceMappingURL=employee.controller.js.map