Files
planilla/api/routes/planillas/planillas.js

219 lines
6.3 KiB
JavaScript

import express from 'express';
const router = express.Router();
import { PrismaClient, Prisma } from '../../prisma/generated/client/index.js';
const prisma = new PrismaClient();
const log = (...args) => console.log('[PLANILLA]', ...args);
// 📡 Log de cada request entrante
router.use((req, _res, next) => {
log(`${req.method} ${req.originalUrl}`, req.method === 'GET' ? req.query : req.body);
next();
});
// GET all planillas
router.get('/', async (_req, res) => {
try {
log('findMany planilla');
const planillas = await prisma.planilla.findMany();
log('Planillas encontradas', planillas.length);
res.json(planillas);
} catch (e) {
console.error(e);
res.status(500).json({ message: 'Error al obtener planillas.' });
}
});
// 🔍 GET /api/planillas/search
router.get('/search', async (req, res) => {
const {
q,
empleado_id,
estado,
titulo,
fecha_desde_desde,
fecha_desde_hasta,
fecha_hasta_desde,
fecha_hasta_hasta,
limit = 0,
} = req.query;
try {
const where = {};
// filtros directos
if (empleado_id) where.empleado_id = parseInt(empleado_id);
if (estado) where.estado = { contains: estado, mode: 'insensitive' };
if (titulo) where.titulo = { contains: titulo, mode: 'insensitive' };
// rangos de fechas
if (fecha_desde_desde || fecha_desde_hasta) {
where.fecha_desde = {};
if (fecha_desde_desde) where.fecha_desde.gte = new Date(fecha_desde_desde);
if (fecha_desde_hasta) where.fecha_desde.lte = new Date(fecha_desde_hasta);
}
if (fecha_hasta_desde || fecha_hasta_hasta) {
where.fecha_hasta = {};
if (fecha_hasta_desde) where.fecha_hasta.gte = new Date(fecha_hasta_desde);
if (fecha_hasta_hasta) where.fecha_hasta.lte = new Date(fecha_hasta_hasta);
}
// búsqueda libre
if (q) {
const qi = parseInt(q);
where.OR = [
...(isNaN(qi) ? [] : [{ id: qi }, { empleado_id: qi }]),
{ titulo: { contains: q, mode: 'insensitive' } },
{ estado: { contains: q, mode: 'insensitive' } },
];
}
const take = parseInt(limit) || (Object.keys(where).length ? undefined : 100);
log('search planillas', { where, take });
const planillas = await prisma.planilla.findMany({
where,
take,
orderBy: { id: 'desc' },
});
res.json(planillas);
} catch (e) {
console.error(e);
res.status(500).json({ message: 'Error al buscar planillas.' });
}
});
// GET planilla by ID
router.get('/:id(\\d+)', async (req, res) => {
const id = parseInt(req.params.id);
try {
log('findUnique planilla', id);
const planilla = await prisma.planilla.findUnique({ where: { id: parseInt(id) } });
if (planilla) {
res.json(planilla);
} else {
res.status(404).json({ message: 'Planilla no encontrada.' });
}
} catch (e) {
console.error(e);
res.status(500).json({ message: 'Error al obtener planilla.' });
}
});
// POST create new planilla
router.post('/', async (req, res) => {
const {
empleado_id,
fecha_desde,
fecha_hasta,
titulo,
total,
estado,
fecha_anulado,
creador_id,
anulador_id,
} = req.body;
if (!empleado_id || !fecha_desde || !fecha_hasta || !titulo) {
return res.status(400).json({
message: 'Los campos empleado_id, fecha_desde, fecha_hasta y titulo son obligatorios.',
});
}
try {
log('create planilla', req.body);
const nuevaPlanilla = await prisma.planilla.create({
data: {
empleado_id: parseInt(empleado_id),
fecha_desde: new Date(fecha_desde),
fecha_hasta: new Date(fecha_hasta),
titulo,
total: total ? parseFloat(total) : null,
estado: estado || 'pagado',
fecha_anulado: fecha_anulado ? new Date(fecha_anulado) : null,
creador_id,
anulador_id,
},
});
res.status(201).json(nuevaPlanilla);
log(nuevaPlanilla, 'resultado create planilla');
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2003') {
return res.status(400).json({ message: 'El empleado_id proporcionado no existe.' });
}
log('Error al crear planilla', e);
console.error(e);
res.status(500).json({ message: 'Error al crear planilla.' });
}
});
// PUT update planilla by ID
router.put('/:id', async (req, res) => {
const { id } = req.params;
const {
empleado_id,
fecha_desde,
fecha_hasta,
titulo,
total,
estado,
fecha_anulado,
anulador_id,
} = req.body;
try {
const updateData = {};
if (empleado_id !== undefined) updateData.empleado_id = parseInt(empleado_id);
if (fecha_desde !== undefined) updateData.fecha_desde = new Date(fecha_desde);
if (fecha_hasta !== undefined) updateData.fecha_hasta = new Date(fecha_hasta);
if (titulo !== undefined) updateData.titulo = titulo;
if (total !== undefined) updateData.total = total ? parseFloat(total) : null;
if (estado !== undefined) updateData.estado = estado;
if (fecha_anulado !== undefined)
updateData.fecha_anulado = fecha_anulado ? new Date(fecha_anulado) : null;
if (anulador_id !== undefined) updateData.anulador_id = anulador_id;
log('update planilla', { id, ...updateData });
const planillaActualizada = await prisma.planilla.update({
where: { id: parseInt(id) },
data: updateData,
});
res.json(planillaActualizada);
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === 'P2025')
return res.status(404).json({ message: 'Planilla no encontrada para actualizar.' });
if (e.code === 'P2003')
return res.status(400).json({ message: 'El empleado_id proporcionado no existe.' });
}
console.error(e);
res.status(500).json({ message: 'Error al actualizar planilla.' });
}
});
// DELETE planilla by ID
router.delete('/:id', async (req, res) => {
const { id } = req.params;
try {
log('delete planilla', id);
await prisma.planilla.delete({ where: { id: parseInt(id) } });
res.status(204).send();
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2025') {
return res.status(404).json({ message: 'Planilla no encontrada para eliminar.' });
}
console.error(e);
res.status(500).json({ message: 'Error al eliminar planilla.' });
}
});
export default router;