import dotenv from 'dotenv'; import { userModel } from '../../schemas/management/user.schema.js'; import log4js from 'log4js'; import mongoose from 'mongoose'; import { distributeUpdate, editAuditLog } from '../../utils.js'; dotenv.config(); const logger = log4js.getLogger('Users'); logger.level = process.env.LOG_LEVEL; export const listUsersRouteHandler = async ( req, res, page = 1, limit = 25, property = '', filter = {}, search = '', sort = '', order = 'ascend' ) => { try { // Calculate the skip value based on the page number and limit const skip = (page - 1) * limit; let user; let aggregateCommand = []; if (search) { // Add a text search match stage for name and brand fields aggregateCommand.push({ $match: { $text: { $search: search, }, }, }); } if (filter != {}) { // use filtering if present aggregateCommand.push({ $match: filter }); } if (property != '') { aggregateCommand.push({ $group: { _id: `$${property}` } }); // group all same properties aggregateCommand.push({ $project: { _id: 0, [property]: '$_id' } }); // rename _id to the property name } // Add sorting if sort parameter is provided if (sort) { const sortOrder = order === 'descend' ? -1 : 1; aggregateCommand.push({ $sort: { [sort]: sortOrder } }); } aggregateCommand.push({ $skip: skip }); aggregateCommand.push({ $limit: Number(limit) }); console.log(aggregateCommand); user = await userModel.aggregate(aggregateCommand); logger.trace(`List of users (Page ${page}, Limit ${limit}, Property ${property}):`, user); res.send(user); } catch (error) { logger.error('Error listing users:', error); res.status(500).send({ error: error }); } }; export const getUserRouteHandler = async (req, res) => { try { // Get ID from params const id = new mongoose.Types.ObjectId(req.params.id); // Fetch the user with the given ID const user = await userModel.findOne({ _id: id, }); if (!user) { logger.warn(`User not found with supplied id.`); return res.status(404).send({ error: 'User not found.' }); } logger.trace(`User with ID: ${id}:`, user); res.send({ ...user._doc }); } catch (error) { logger.error('Error fetching User:', error); res.status(500).send({ error: error.message }); } }; export const editUserRouteHandler = async (req, res) => { try { // Get ID from params const id = new mongoose.Types.ObjectId(req.params.id); // Fetch the user with the given ID const user = await userModel.findOne({ _id: id }); if (!user) { // Error handling logger.warn(`User not found with supplied id.`); return res.status(404).send({ error: 'User not found.' }); } logger.trace(`User with ID: ${id}:`, user); try { const updateData = { updatedAt: new Date(), username: req.body.username, name: req.body.name, firstName: req.body.firstName, lastName: req.body.lastName, email: req.body.email, }; console.log(req.user); // Create audit log before updating await editAuditLog(user.toObject(), updateData, id, 'user', req.user); const result = await userModel.updateOne({ _id: id }, { $set: updateData }); if (result.nModified === 0) { logger.error('No User updated.'); res.status(500).send({ error: 'No users updated.' }); } await distributeUpdate(updateData, id, 'user'); } catch (updateError) { logger.error('Error updating user:', updateError); res.status(500).send({ error: updateError.message }); } res.send('OK'); } catch (fetchError) { logger.error('Error fetching user:', fetchError); res.status(500).send({ error: fetchError.message }); } };