import dotenv from 'dotenv'; import { subJobModel } from '../../schemas/production/subjob.schema.js'; import log4js from 'log4js'; dotenv.config(); const logger = log4js.getLogger('SubJobs'); logger.level = process.env.LOG_LEVEL; export const listSubJobsRouteHandler = 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 subJobs; let aggregateCommand = []; if (search) { // Add a text search match stage for name and other searchable fields aggregateCommand.push({ $match: { $text: { $search: search, }, }, }); } // Lookup printer aggregateCommand.push({ $lookup: { from: 'printers', // The name of the Printer collection localField: 'printer', foreignField: '_id', as: 'printer', }, }); // Lookup job aggregateCommand.push({ $lookup: { from: 'jobs', // The name of the Printer collection localField: 'job', foreignField: '_id', as: 'job', }, }); aggregateCommand.push({ $unwind: { path: '$printer', preserveNullAndEmptyArrays: true, // Keep documents without a matching filament }, }); aggregateCommand.push({ $unwind: { path: '$job', preserveNullAndEmptyArrays: true, // Keep documents without a matching filament }, }); 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 } else { aggregateCommand.push({ $project: { state: 1, _id: 1, createdAt: 1, startedAt: 1, 'printer._id': 1, 'job._id': 1, 'printer.name': 1, }, }); } // Add sorting if sort parameter is provided if (sort) { const sortOrder = order === 'descend' ? -1 : 1; aggregateCommand.push({ $sort: { [sort]: sortOrder } }); } else { // Default sorting by createdAt descending aggregateCommand.push({ $sort: { createdAt: -1 } }); } aggregateCommand.push({ $skip: skip }); aggregateCommand.push({ $limit: Number(limit) }); console.log(aggregateCommand); subJobs = await subJobModel.aggregate(aggregateCommand); logger.trace( `List of print subJobs (Page ${page}, Limit ${limit}, Property ${property}, Sort ${sort}, Order ${order}):`, subJobs ); res.send(subJobs); } catch (error) { logger.error('Error listing print subJobs:', error); res.status(500).send({ error: error }); } };