89 lines
2.8 KiB
JavaScript
89 lines
2.8 KiB
JavaScript
const express = require('express');
|
|
const { canReadAttendance } = require('../policies/accessPolicy');
|
|
|
|
const parseAttendance = (attendance) => ({
|
|
...attendance,
|
|
attention_points: typeof attendance.attention_points === 'string' ? JSON.parse(attendance.attention_points) : attendance.attention_points,
|
|
improvement_points: typeof attendance.improvement_points === 'string' ? JSON.parse(attendance.improvement_points) : attendance.improvement_points,
|
|
converted: Boolean(attendance.converted),
|
|
});
|
|
|
|
const createAttendancesRouter = ({ pool }) => {
|
|
const router = express.Router();
|
|
|
|
router.get('/attendances', async (req, res) => {
|
|
try {
|
|
const { tenantId, userId, teamId, startDate, endDate, funnelStage, origin } = req.query;
|
|
const effectiveTenantId = req.user.role === 'super_admin' ? tenantId : req.user.tenant_id;
|
|
|
|
let q = 'SELECT a.*, u.team_id FROM attendances a JOIN users u ON a.user_id = u.id WHERE a.tenant_id = ?';
|
|
const params = [effectiveTenantId];
|
|
|
|
if (startDate && endDate) {
|
|
q += ' AND a.created_at BETWEEN ? AND ?';
|
|
params.push(new Date(startDate), new Date(endDate));
|
|
}
|
|
|
|
if (req.user.role === 'agent') {
|
|
q += ' AND a.user_id = ?';
|
|
params.push(req.user.id);
|
|
} else {
|
|
if (req.user.role === 'manager') {
|
|
q += ' AND u.team_id = ?';
|
|
params.push(req.user.team_id);
|
|
} else if (teamId && teamId !== 'all') {
|
|
q += ' AND u.team_id = ?';
|
|
params.push(teamId);
|
|
}
|
|
|
|
if (userId && userId !== 'all') {
|
|
if (userId.startsWith('u_') || userId.length === 36) {
|
|
q += ' AND a.user_id = ?';
|
|
params.push(userId);
|
|
} else {
|
|
q += ' AND u.slug = ?';
|
|
params.push(userId);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (funnelStage && funnelStage !== 'all') {
|
|
q += ' AND a.funnel_stage = ?';
|
|
params.push(funnelStage);
|
|
}
|
|
if (origin && origin !== 'all') {
|
|
q += ' AND a.origin = ?';
|
|
params.push(origin);
|
|
}
|
|
|
|
q += ' ORDER BY a.created_at DESC';
|
|
const [rows] = await pool.query(q, params);
|
|
res.json(rows.map(parseAttendance));
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
router.get('/attendances/:id', async (req, res) => {
|
|
try {
|
|
const [rows] = await pool.query(
|
|
'SELECT a.*, u.team_id FROM attendances a JOIN users u ON a.user_id = u.id WHERE a.id = ?',
|
|
[req.params.id]
|
|
);
|
|
if (rows.length === 0) return res.status(404).json({ error: 'Not found' });
|
|
|
|
if (!canReadAttendance(req.user, rows[0])) return res.status(403).json({ error: 'Acesso negado.' });
|
|
|
|
res.json(parseAttendance(rows[0]));
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
return router;
|
|
};
|
|
|
|
module.exports = {
|
|
createAttendancesRouter,
|
|
};
|