import config from '../../config.js'; import { filamentStockModel } from '../../database/schemas/inventory/filamentstock.schema.js'; import log4js from 'log4js'; import mongoose from 'mongoose'; import { deleteObject, deleteObjects, listObjects, getObject, editObject, editObjects, newObject, listObjectsByProperties, getModelStats, getModelHistory, checkStates, searchObjects, getPropertyValues, getObjectNeighbors, } from '../../database/database.js'; import { stockEventModel } from '../../database/schemas/inventory/stockevent.schema.js'; const logger = log4js.getLogger('Filament Stocks'); logger.level = config.server.logLevel; const FILAMENT_STOCK_POPULATE = [ { path: 'filament' }, { path: 'filamentSku', populate: 'filament' }, { path: 'stockLocation' }, ]; export const listFilamentStocksRouteHandler = async ( req, res, page = 1, limit = 25, property = '', filter = {}, search = '', sort = '', order = 'ascend' ) => { const result = await listObjects({ model: filamentStockModel, page, limit, property, filter, search, sort, order, populate: [ { path: 'filament' }, { path: 'filamentSku', populate: 'filament' }, { path: 'stockLocation' }, ], }); if (result?.error) { logger.error('Error listing filament stocks.'); res.status(result.code).send(result); return; } logger.debug(`List of filament stocks (Page ${page}, Limit ${limit}). Count: ${result.length}`); res.send(result); }; export const listFilamentStocksByPropertiesRouteHandler = async ( req, res, properties = '', filter = {}, masterFilter = {} ) => { const result = await listObjectsByProperties({ model: filamentStockModel, properties, filter, populate: ['filament', 'filamentSku', 'stockLocation'], masterFilter, }); if (result?.error) { logger.error('Error listing filament stocks.'); res.status(result.code).send(result); return; } logger.debug(`List of filament stocks. Count: ${result.length}`); res.send(result); }; export const getFilamentStockPropertyValuesRouteHandler = async ( req, res, property, filter, masterFilter ) => { const result = await getPropertyValues({ model: filamentStockModel, property, filter: { ...filter, ...masterFilter }, }); res.send(result); }; export const searchFilamentStocksRouteHandler = async (req, res, search) => { const result = await searchObjects({ model: filamentStockModel, search, }); res.send(result); }; export const getFilamentStockRouteHandler = async (req, res) => { const id = req.params.id; const result = await getObject({ model: filamentStockModel, id, populate: [ { path: 'filament' }, { path: 'filamentSku', populate: 'filament' }, { path: 'stockLocation' }, ], }); if (result?.error) { logger.warn(`Filament Stock not found with supplied id.`); return res.status(result.code).send(result); } logger.debug(`Retreived filament stock with ID: ${id}`); res.send(result); }; export const editFilamentStockRouteHandler = async (req, res) => { // Get ID from params const id = new mongoose.Types.ObjectId(req.params.id); logger.trace(`Filament Stock with ID: ${id}`); const checkStatesResult = await checkStates({ model: filamentStockModel, id, states: ['draft'] }); if (checkStatesResult.error) { logger.error('Error checking filament stock states:', checkStatesResult.error); res.status(checkStatesResult.code).send(checkStatesResult); return; } if (checkStatesResult === false) { logger.error('Filament stock is not in draft state.'); res.status(400).send({ error: 'Filament stock is not in draft state.', code: 400 }); return; } const updateData = { filament: req.body?.filament, filamentSku: req.body?.filamentSku, stockLocation: req.body?.stockLocation, startingWeight: req.body?.startingWeight, currentWeight: req.body?.currentWeight ?? req.body?.startingWeight, }; const result = await editObject({ model: filamentStockModel, id, updateData, user: req.user, populate: FILAMENT_STOCK_POPULATE, }); if (result.error) { logger.error('Error editing filament stock:', result.error); res.status(result).send(result); return; } logger.debug(`Edited filament stock with ID: ${id}`); res.send(result); }; export const editMultipleFilamentStocksRouteHandler = async (req, res) => { const updates = req.body.map((update) => ({ _id: update._id, })); if (!Array.isArray(updates)) { return res.status(400).send({ error: 'Body must be an array of updates.', code: 400 }); } const result = await editObjects({ model: filamentStockModel, updates, user: req.user, }); if (result.error) { logger.error('Error editing filament stocks:', result.error); res.status(result.code || 500).send(result); return; } logger.debug(`Edited ${updates.length} filament stocks`); res.send(result); }; export const newFilamentStockRouteHandler = async (req, res) => { const startingWeight = req.body.startingWeight; const newData = { updatedAt: new Date(), startingWeight, currentWeight: req.body.currentWeight ?? startingWeight, filament: req.body.filament, filamentSku: req.body.filamentSku, state: req.body.state ?? { type: 'draft' }, stockLocation: req.body.stockLocation, }; const result = await newObject({ model: filamentStockModel, newData, user: req.user, }); if (result.error) { logger.error('No filament stock created:', result.error); return res.status(result.code).send(result); } logger.debug(`New filament stock with ID: ${result._id}`); res.send(result); }; export const deleteFilamentStockByFilterRouteHandler = async ( req, res, filter = {}, masterFilter = {} ) => { const result = await deleteObjects({ model: filamentStockModel, filter: { ...masterFilter, ...filter }, user: req.user, states: ['draft'], }); if (result.error) { logger.error('Failed to delete filtered FilamentStock:', result.error); return res.status(result.code || 500).send(result); } res.send(result); }; export const deleteFilamentStockRouteHandler = async (req, res) => { // Get ID from params const id = new mongoose.Types.ObjectId(req.params.id); logger.trace(`Filament Stock with ID: ${id}`); const checkStatesResult = await checkStates({ model: filamentStockModel, id, states: ['draft'] }); if (checkStatesResult.error) { logger.error('Error checking filament stock states:', checkStatesResult.error); res.status(checkStatesResult.code).send(checkStatesResult); return; } if (checkStatesResult === false) { logger.error('Filament stock is not in draft state.'); res.status(400).send({ error: 'Filament stock is not in draft state.', code: 400 }); return; } const result = await deleteObject({ model: filamentStockModel, id, user: req.user, }); if (result.error) { logger.error('No filament stock deleted:', result.error); return res.status(result.code).send(result); } logger.debug(`Deleted filament stock with ID: ${result._id}`); res.send(result); }; export const postFilamentStockRouteHandler = async (req, res) => { const id = new mongoose.Types.ObjectId(req.params.id); logger.trace(`Filament Stock with ID: ${id}`); const checkStatesResult = await checkStates({ model: filamentStockModel, id, states: ['draft'] }); if (checkStatesResult.error) { logger.error('Error checking filament stock states:', checkStatesResult.error); res.status(checkStatesResult.code).send(checkStatesResult); return; } if (checkStatesResult === false) { logger.error('Filament stock is not in draft state.'); res.status(400).send({ error: 'Filament stock is not in draft state.', code: 400 }); return; } const filamentStock = await getObject({ model: filamentStockModel, id, populate: FILAMENT_STOCK_POPULATE, }); if (filamentStock?.error) { logger.error('Error loading filament stock to post:', filamentStock.error); res.status(filamentStock.code || 500).send(filamentStock); return; } const initialStockEventResult = await newObject({ model: stockEventModel, newData: { value: filamentStock.startingWeight.net, unit: 'g', parent: { _id: id }, parentType: 'filamentStock', owner: { _id: req.user._id }, ownerType: 'user', }, recalculate: true, user: req.user, }); if (initialStockEventResult?.error) { logger.error('Error creating initial stock event:', initialStockEventResult.error); res.status(initialStockEventResult.code || 500).send(initialStockEventResult); return; } const updateData = { updatedAt: new Date(), state: { type: 'unconsumed' }, postedAt: new Date(), currentWeight: filamentStock.startingWeight, }; const result = await editObject({ model: filamentStockModel, id, updateData, user: req.user, populate: FILAMENT_STOCK_POPULATE, }); if (result.error) { logger.error('Error posting filament stock:', result.error); res.status(result.code).send(result); return; } logger.debug(`Posted filament stock with ID: ${id}`); res.send(result); }; export const getFilamentStockStatsRouteHandler = async (req, res) => { const result = await getModelStats({ model: filamentStockModel }); if (result?.error) { logger.error('Error fetching filament stock stats:', result.error); return res.status(result.code).send(result); } logger.trace('Filament stock stats:', result); res.send(result); }; export const getFilamentStockHistoryRouteHandler = async (req, res) => { const from = req.query.from; const to = req.query.to; const result = await getModelHistory({ model: filamentStockModel, from, to }); if (result?.error) { logger.error('Error fetching filament stock history:', result.error); return res.status(result.code).send(result); } logger.trace('Filament stock history:', result); res.send(result); }; export const getFilamentStockNeighborsRouteHandler = async ( req, res, property = '', filter = {}, search = '', sort = '', order = 'ascend', id ) => { if (!id) { return res.status(400).send({ error: 'Missing id parameter', code: 400 }); } const result = await getObjectNeighbors({ model: filamentStockModel, id, filter, search, sort, order, }); if (result?.error) { logger.error('Error fetching filamentStock neighbors.'); return res.status(result.code).send(result); } logger.debug(`Retrieved filamentStock neighbors for ID: ${id}`); res.send(result); };