Adds Express.js routes and Prisma-based handlers for common database operations (Create, Read, Update, Delete) for the following modules: - Empleados (subset of Cliente model) - Asistencias - Tareas (TareaRealizada model) - Planillas Each module's routes are separated into their own files within `api/routes/`. The new routes are registered in `api/server.js`. Basic error handling, including try-catch blocks and checks for common Prisma errors (e.g., P2025 for record not found, P2003 for foreign key violations), has been implemented in each endpoint.
157 lines
4.9 KiB
JavaScript
157 lines
4.9 KiB
JavaScript
import express from 'express';
|
|
const router = express.Router();
|
|
import { PrismaClient } from '../../prisma/generated/client/index.js';
|
|
const prisma = new PrismaClient();
|
|
|
|
// GET all tareas
|
|
router.get('/', async (req, res) => {
|
|
try {
|
|
const tareas = await prisma.tareaRealizada.findMany();
|
|
res.json(tareas);
|
|
} catch (error) {
|
|
console.error(error);
|
|
res.status(500).json({ error: 'Error al obtener tareas.' });
|
|
}
|
|
});
|
|
|
|
// GET tarea by ID
|
|
router.get('/:id', async (req, res) => {
|
|
const { id } = req.params;
|
|
try {
|
|
const tarea = await prisma.tareaRealizada.findUnique({
|
|
where: { id: parseInt(id) },
|
|
});
|
|
if (tarea) {
|
|
res.json(tarea);
|
|
} else {
|
|
res.status(404).json({ error: 'Tarea no encontrada.' });
|
|
}
|
|
} catch (error) {
|
|
console.error(error);
|
|
res.status(500).json({ error: 'Error al obtener tarea.' });
|
|
}
|
|
});
|
|
|
|
// POST create new tarea
|
|
router.post('/', async (req, res) => {
|
|
const {
|
|
empleado_id,
|
|
planilla_id,
|
|
titulo,
|
|
precio,
|
|
estado,
|
|
observacion,
|
|
fecha,
|
|
tipo,
|
|
fecha_anulado,
|
|
creador_id, // Should ideally be from authenticated user
|
|
anulador_id,
|
|
} = req.body;
|
|
|
|
try {
|
|
// Basic validation
|
|
if (!empleado_id || !titulo || !fecha) {
|
|
return res.status(400).json({ error: 'Los campos empleado_id, titulo y fecha son obligatorios.' });
|
|
}
|
|
|
|
const nuevaTarea = await prisma.tareaRealizada.create({
|
|
data: {
|
|
empleado_id: parseInt(empleado_id),
|
|
planilla_id: planilla_id ? parseInt(planilla_id) : null,
|
|
titulo,
|
|
precio: precio ? parseFloat(precio) : null,
|
|
estado: estado || 'pendiente', // Default to 'pendiente' if not provided
|
|
observacion,
|
|
fecha: new Date(fecha),
|
|
tipo: tipo || '', // Default to empty string if not provided
|
|
fecha_anulado: fecha_anulado ? new Date(fecha_anulado) : null,
|
|
creador_id,
|
|
anulador_id,
|
|
},
|
|
});
|
|
res.status(201).json(nuevaTarea);
|
|
} catch (error) {
|
|
console.error(error);
|
|
if (error.code === 'P2003') { // Foreign key constraint failed
|
|
if (error.meta?.field_name?.includes('empleado_id')) {
|
|
return res.status(400).json({ error: 'El empleado_id proporcionado no existe.' });
|
|
}
|
|
if (error.meta?.field_name?.includes('planilla_id')) {
|
|
return res.status(400).json({ error: 'El planilla_id proporcionado no existe.' });
|
|
}
|
|
}
|
|
res.status(500).json({ error: 'Error al crear tarea.' });
|
|
}
|
|
});
|
|
|
|
// PUT update tarea by ID
|
|
router.put('/:id', async (req, res) => {
|
|
const { id } = req.params;
|
|
const {
|
|
empleado_id,
|
|
planilla_id,
|
|
titulo,
|
|
precio,
|
|
estado,
|
|
observacion,
|
|
fecha,
|
|
tipo,
|
|
fecha_anulado,
|
|
anulador_id,
|
|
} = req.body;
|
|
|
|
try {
|
|
const updateData = {};
|
|
if (empleado_id !== undefined) updateData.empleado_id = parseInt(empleado_id);
|
|
if (planilla_id !== undefined) updateData.planilla_id = planilla_id ? parseInt(planilla_id) : null;
|
|
if (titulo !== undefined) updateData.titulo = titulo;
|
|
if (precio !== undefined) updateData.precio = precio ? parseFloat(precio) : null;
|
|
if (estado !== undefined) updateData.estado = estado;
|
|
if (observacion !== undefined) updateData.observacion = observacion;
|
|
if (fecha !== undefined) updateData.fecha = new Date(fecha);
|
|
if (tipo !== undefined) updateData.tipo = tipo;
|
|
if (fecha_anulado !== undefined) updateData.fecha_anulado = fecha_anulado ? new Date(fecha_anulado) : null;
|
|
if (anulador_id !== undefined) updateData.anulador_id = anulador_id;
|
|
// creador_id is typically not updated.
|
|
|
|
const tareaActualizada = await prisma.tareaRealizada.update({
|
|
where: { id: parseInt(id) },
|
|
data: updateData,
|
|
});
|
|
res.json(tareaActualizada);
|
|
} catch (error) {
|
|
console.error(error);
|
|
if (error.code === 'P2025') { // Record to update not found
|
|
return res.status(404).json({ error: 'Tarea no encontrada para actualizar.' });
|
|
}
|
|
if (error.code === 'P2003') { // Foreign key constraint failed
|
|
if (error.meta?.field_name?.includes('empleado_id')) {
|
|
return res.status(400).json({ error: 'El empleado_id proporcionado no existe.' });
|
|
}
|
|
if (error.meta?.field_name?.includes('planilla_id')) {
|
|
return res.status(400).json({ error: 'El planilla_id proporcionado no existe.' });
|
|
}
|
|
}
|
|
res.status(500).json({ error: 'Error al actualizar tarea.' });
|
|
}
|
|
});
|
|
|
|
// DELETE tarea by ID
|
|
router.delete('/:id', async (req, res) => {
|
|
const { id } = req.params;
|
|
try {
|
|
await prisma.tareaRealizada.delete({
|
|
where: { id: parseInt(id) },
|
|
});
|
|
res.status(204).send(); // No content
|
|
} catch (error) {
|
|
console.error(error);
|
|
if (error.code === 'P2025') { // Record to delete not found
|
|
return res.status(404).json({ error: 'Tarea no encontrada para eliminar.' });
|
|
}
|
|
res.status(500).json({ error: 'Error al eliminar tarea.' });
|
|
}
|
|
});
|
|
|
|
export default router;
|