import express from 'express'; import db from '../config/database.js'; import { authenticateToken, authorize } from '../middleware/auth.js'; const router = express.Router(); // Get all work allocations router.get('/', authenticateToken, async (req, res) => { try { const { employeeId, status, departmentId } = req.query; let query = ` SELECT wa.*, e.name as employee_name, e.username as employee_username, s.name as supervisor_name, c.name as contractor_name, sd.name as sub_department_name, d.name as department_name FROM work_allocations wa JOIN users e ON wa.employee_id = e.id JOIN users s ON wa.supervisor_id = s.id JOIN users c ON wa.contractor_id = c.id LEFT JOIN sub_departments sd ON wa.sub_department_id = sd.id LEFT JOIN departments d ON e.department_id = d.id WHERE 1=1 `; const params = []; // Role-based filtering if (req.user.role === 'Supervisor') { query += ' AND wa.supervisor_id = ?'; params.push(req.user.id); } else if (req.user.role === 'Employee') { query += ' AND wa.employee_id = ?'; params.push(req.user.id); } else if (req.user.role === 'Contractor') { query += ' AND wa.contractor_id = ?'; params.push(req.user.id); } if (employeeId) { query += ' AND wa.employee_id = ?'; params.push(employeeId); } if (status) { query += ' AND wa.status = ?'; params.push(status); } if (departmentId) { query += ' AND e.department_id = ?'; params.push(departmentId); } query += ' ORDER BY wa.assigned_date DESC, wa.created_at DESC'; const [allocations] = await db.query(query, params); res.json(allocations); } catch (error) { console.error('Get work allocations error:', error); res.status(500).json({ error: 'Internal server error' }); } }); // Get work allocation by ID router.get('/:id', authenticateToken, async (req, res) => { try { const [allocations] = await db.query( `SELECT wa.*, e.name as employee_name, e.username as employee_username, s.name as supervisor_name, c.name as contractor_name, sd.name as sub_department_name, d.name as department_name FROM work_allocations wa JOIN users e ON wa.employee_id = e.id JOIN users s ON wa.supervisor_id = s.id JOIN users c ON wa.contractor_id = c.id LEFT JOIN sub_departments sd ON wa.sub_department_id = sd.id LEFT JOIN departments d ON e.department_id = d.id WHERE wa.id = ?`, [req.params.id] ); if (allocations.length === 0) { return res.status(404).json({ error: 'Work allocation not found' }); } res.json(allocations[0]); } catch (error) { console.error('Get work allocation error:', error); res.status(500).json({ error: 'Internal server error' }); } }); // Create work allocation (Supervisor or SuperAdmin) router.post('/', authenticateToken, authorize('Supervisor', 'SuperAdmin'), async (req, res) => { try { const { employeeId, contractorId, subDepartmentId, activity, description, assignedDate, rate, units, totalAmount, departmentId } = req.body; if (!employeeId || !contractorId || !assignedDate) { return res.status(400).json({ error: 'Missing required fields' }); } // SuperAdmin can create for any department, Supervisor only for their own let targetDepartmentId = req.user.role === 'SuperAdmin' ? departmentId : req.user.departmentId; // Verify employee exists (SuperAdmin can assign any employee, Supervisor only their department) let employeeQuery = 'SELECT * FROM users WHERE id = ?'; let employeeParams = [employeeId]; if (req.user.role === 'Supervisor') { employeeQuery += ' AND department_id = ?'; employeeParams.push(req.user.departmentId); } const [employees] = await db.query(employeeQuery, employeeParams); if (employees.length === 0) { return res.status(403).json({ error: 'Employee not found or not in your department' }); } // Use provided rate or get contractor's current rate let finalRate = rate; if (!finalRate) { const [rates] = await db.query( 'SELECT rate FROM contractor_rates WHERE contractor_id = ? ORDER BY effective_date DESC LIMIT 1', [contractorId] ); finalRate = rates.length > 0 ? rates[0].rate : null; } const [result] = await db.query( `INSERT INTO work_allocations (employee_id, supervisor_id, contractor_id, sub_department_id, activity, description, assigned_date, rate, units, total_amount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [employeeId, req.user.id, contractorId, subDepartmentId || null, activity || null, description || null, assignedDate, finalRate, units || null, totalAmount || null] ); const [newAllocation] = await db.query( `SELECT wa.*, e.name as employee_name, e.username as employee_username, s.name as supervisor_name, c.name as contractor_name, sd.name as sub_department_name, d.name as department_name FROM work_allocations wa JOIN users e ON wa.employee_id = e.id JOIN users s ON wa.supervisor_id = s.id JOIN users c ON wa.contractor_id = c.id LEFT JOIN sub_departments sd ON wa.sub_department_id = sd.id LEFT JOIN departments d ON e.department_id = d.id WHERE wa.id = ?`, [result.insertId] ); res.status(201).json(newAllocation[0]); } catch (error) { console.error('Create work allocation error:', error); res.status(500).json({ error: 'Internal server error' }); } }); // Update work allocation status (Supervisor or SuperAdmin) router.put('/:id/status', authenticateToken, authorize('Supervisor', 'SuperAdmin'), async (req, res) => { try { const { status, completionDate } = req.body; if (!status) { return res.status(400).json({ error: 'Status required' }); } // SuperAdmin can update any allocation, Supervisor only their own let query = 'SELECT * FROM work_allocations WHERE id = ?'; let params = [req.params.id]; if (req.user.role === 'Supervisor') { query += ' AND supervisor_id = ?'; params.push(req.user.id); } const [allocations] = await db.query(query, params); if (allocations.length === 0) { return res.status(403).json({ error: 'Work allocation not found or access denied' }); } await db.query( 'UPDATE work_allocations SET status = ?, completion_date = ? WHERE id = ?', [status, completionDate || null, req.params.id] ); const [updatedAllocation] = await db.query( `SELECT wa.*, e.name as employee_name, e.username as employee_username, s.name as supervisor_name, c.name as contractor_name, sd.name as sub_department_name, d.name as department_name FROM work_allocations wa JOIN users e ON wa.employee_id = e.id JOIN users s ON wa.supervisor_id = s.id JOIN users c ON wa.contractor_id = c.id LEFT JOIN sub_departments sd ON wa.sub_department_id = sd.id LEFT JOIN departments d ON e.department_id = d.id WHERE wa.id = ?`, [req.params.id] ); res.json(updatedAllocation[0]); } catch (error) { console.error('Update work allocation error:', error); res.status(500).json({ error: 'Internal server error' }); } }); // Delete work allocation (Supervisor or SuperAdmin) router.delete('/:id', authenticateToken, authorize('Supervisor', 'SuperAdmin'), async (req, res) => { try { // SuperAdmin can delete any allocation, Supervisor only their own let query = 'SELECT * FROM work_allocations WHERE id = ?'; let params = [req.params.id]; if (req.user.role === 'Supervisor') { query += ' AND supervisor_id = ?'; params.push(req.user.id); } const [allocations] = await db.query(query, params); if (allocations.length === 0) { return res.status(403).json({ error: 'Work allocation not found or access denied' }); } await db.query('DELETE FROM work_allocations WHERE id = ?', [req.params.id]); res.json({ message: 'Work allocation deleted successfully' }); } catch (error) { console.error('Delete work allocation error:', error); res.status(500).json({ error: 'Internal server error' }); } }); export default router;