81 lines
2.9 KiB
JavaScript
81 lines
2.9 KiB
JavaScript
const express = require('express');
|
|
|
|
const createSearchRouter = ({ pool }) => {
|
|
const router = express.Router();
|
|
|
|
router.get('/search', async (req, res) => {
|
|
const { q } = req.query;
|
|
if (!q || q.length < 2) return res.json({ members: [], teams: [], attendances: [], organizations: [] });
|
|
|
|
const queryStr = `%${q}%`;
|
|
const results = { members: [], teams: [], attendances: [], organizations: [] };
|
|
|
|
try {
|
|
if (req.user.role !== 'agent') {
|
|
let membersQ = 'SELECT id, name, email, slug, role, team_id, avatar_url FROM users WHERE (name LIKE ? OR email LIKE ?)';
|
|
const membersParams = [queryStr, queryStr];
|
|
|
|
if (req.user.role === 'admin') {
|
|
membersQ += ' AND tenant_id = ?';
|
|
membersParams.push(req.user.tenant_id);
|
|
} else if (req.user.role === 'manager') {
|
|
membersQ += ' AND tenant_id = ? AND (team_id = ? OR id = ?)';
|
|
membersParams.push(req.user.tenant_id, req.user.team_id, req.user.id);
|
|
}
|
|
|
|
const [members] = await pool.query(membersQ, membersParams);
|
|
results.members = members;
|
|
}
|
|
|
|
if (req.user.role !== 'agent') {
|
|
let teamsQ = 'SELECT id, name, description FROM teams WHERE name LIKE ?';
|
|
const teamsParams = [queryStr];
|
|
|
|
if (req.user.role === 'admin') {
|
|
teamsQ += ' AND tenant_id = ?';
|
|
teamsParams.push(req.user.tenant_id);
|
|
} else if (req.user.role === 'manager') {
|
|
teamsQ += ' AND tenant_id = ? AND id = ?';
|
|
teamsParams.push(req.user.tenant_id, req.user.team_id);
|
|
}
|
|
|
|
const [teams] = await pool.query(teamsQ, teamsParams);
|
|
results.teams = teams;
|
|
}
|
|
|
|
if (req.user.role === 'super_admin') {
|
|
const [orgs] = await pool.query('SELECT id, name, slug, status FROM tenants WHERE name LIKE ? OR slug LIKE ? LIMIT 5', [queryStr, queryStr]);
|
|
results.organizations = orgs;
|
|
}
|
|
|
|
let attendancesQ = 'SELECT a.id, a.title, a.created_at, u.name as user_name FROM attendances a JOIN users u ON a.user_id = u.id WHERE a.title LIKE ?';
|
|
const attendancesParams = [queryStr];
|
|
|
|
if (req.user.role === 'admin') {
|
|
attendancesQ += ' AND a.tenant_id = ?';
|
|
attendancesParams.push(req.user.tenant_id);
|
|
} else if (req.user.role === 'manager') {
|
|
attendancesQ += ' AND a.tenant_id = ? AND u.team_id = ?';
|
|
attendancesParams.push(req.user.tenant_id, req.user.team_id);
|
|
} else if (req.user.role !== 'super_admin') {
|
|
attendancesQ += ' AND a.user_id = ?';
|
|
attendancesParams.push(req.user.id);
|
|
}
|
|
|
|
attendancesQ += ' LIMIT 10';
|
|
const [attendances] = await pool.query(attendancesQ, attendancesParams);
|
|
results.attendances = attendances;
|
|
|
|
res.json(results);
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
return router;
|
|
};
|
|
|
|
module.exports = {
|
|
createSearchRouter,
|
|
};
|