const express = require("express"); const { ActivityLog, User } = require("../models"); const { authenticate } = require("../middleware/auth"); const router = express.Router(); // Get all activity logs (admin only) router.get("/", authenticate, async (req, res) => { try { if (req.user.role !== "admin") { return res.status(403).json({ error: "Access denied" }); } const logs = await ActivityLog.findAll({ include: [ { model: User, attributes: ["id", "username", "role"], }, ], order: [["timestamp", "DESC"]], }); res.json(logs); } catch (error) { console.error("Error fetching activity logs:", error); res.status(500).json({ error: "Internal server error" }); } }); // Get activity logs for managers and users (manager only) router.get("/managed", authenticate, async (req, res) => { try { if (req.user.role !== "manager" && req.user.role !== "admin") { return res.status(403).json({ error: "Access denied" }); } const logs = await ActivityLog.findAll({ include: [ { model: User, attributes: ["id", "username", "role"], }, ], where: { "$User.role$": ["manager", "user"], }, order: [["timestamp", "DESC"]], }); res.json(logs); } catch (error) { console.error("Error fetching managed activity logs:", error); res.status(500).json({ error: "Internal server error" }); } }); // Log an activity (internal function) const logActivity = async (userId, action, details = null) => { try { await ActivityLog.create({ userId, action, details, timestamp: new Date(), }); } catch (error) { console.error("Error logging activity:", error); } }; module.exports = { router, logActivity };