Tom Butcher 6a730294b1 Refactor filter handling in various routes to include master filter support
This commit updates multiple routes across the management and inventory modules to enhance the handling of property value requests. The `/values` endpoints are modified to incorporate a filtering mechanism that allows for both a standard filter and an optional master filter, improving the flexibility and accuracy of data retrieval. Additionally, debug logging statements are added to assist in tracking the filter parameters during requests. This refactor aims to streamline the data fetching process and improve the overall user experience when interacting with the API.
2026-08-30 12:25:10 +01:00

251 lines
5.5 KiB
JavaScript

import config from '../../config.js';
import { clientModel } from '../../database/schemas/sales/client.schema.js';
import log4js from 'log4js';
import mongoose from 'mongoose';
import {
deleteObject,
listObjects,
getObject,
editObject,
newObject,
listObjectsByProperties,
getModelStats,
getModelHistory,
searchObjects,
getPropertyValues,
getObjectNeighbors,
} from '../../database/database.js';
const logger = log4js.getLogger('Clients');
logger.level = config.server.logLevel;
export const listClientsRouteHandler = async (
req,
res,
page = 1,
limit = 25,
property = '',
filter = {},
search = '',
sort = '',
order = 'ascend'
) => {
const result = await listObjects({
model: clientModel,
page,
limit,
property,
filter,
search,
sort,
order,
});
if (result?.error) {
logger.error('Error listing clients.');
res.status(result.code).send(result);
return;
}
logger.debug(`List of clients (Page ${page}, Limit ${limit}). Count: ${result.length}.`);
res.send(result);
};
export const listClientsByPropertiesRouteHandler = async (
req,
res,
properties = '',
filter = {},
masterFilter = {}
) => {
const result = await listObjectsByProperties({
model: clientModel,
properties,
filter,
masterFilter,
});
if (result?.error) {
logger.error('Error listing clients.');
res.status(result.code).send(result);
return;
}
logger.debug(`List of clients. Count: ${result.length}`);
res.send(result);
};
export const getClientPropertyValuesRouteHandler = async (
req,
res,
property,
filter,
masterFilter
) => {
const result = await getPropertyValues({
model: clientModel,
property,
filter: { ...filter, ...masterFilter },
});
res.send(result);
};
export const searchClientsRouteHandler = async (req, res, search) => {
const result = await searchObjects({
model: clientModel,
search,
});
res.send(result);
};
export const getClientRouteHandler = async (req, res) => {
const id = req.params.id;
const result = await getObject({
model: clientModel,
id,
});
if (result?.error) {
logger.warn(`Client not found with supplied id.`);
return res.status(result.code).send(result);
}
logger.debug(`Retreived client with ID: ${id}`);
res.send(result);
};
export const editClientRouteHandler = async (req, res) => {
// Get ID from params
const id = new mongoose.Types.ObjectId(req.params.id);
logger.trace(`Client with ID: ${id}`);
const updateData = {
updatedAt: new Date(),
country: req.body.country,
name: req.body.name,
phone: req.body.phone,
email: req.body.email,
address: req.body.address,
active: req.body.active,
tags: req.body.tags,
marketplace: req.body.marketplace,
};
// Create audit log before updating
const result = await editObject({
model: clientModel,
id,
updateData,
user: req.user,
});
if (result.error) {
logger.error('Error editing client:', result.error);
res.status(result).send(result);
return;
}
logger.debug(`Edited client with ID: ${id}`);
res.send(result);
};
export const newClientRouteHandler = async (req, res) => {
const newData = {
updatedAt: new Date(),
country: req.body.country,
name: req.body.name,
phone: req.body.phone,
email: req.body.email,
address: req.body.address,
active: req.body.active,
tags: req.body.tags,
marketplace: req.body.marketplace,
};
const result = await newObject({
model: clientModel,
newData,
user: req.user,
});
if (result.error) {
logger.error('No client created:', result.error);
return res.status(result.code).send(result);
}
logger.debug(`New client with ID: ${result._id}`);
res.send(result);
};
export const deleteClientRouteHandler = async (req, res) => {
// Get ID from params
const id = new mongoose.Types.ObjectId(req.params.id);
logger.trace(`Client with ID: ${id}`);
const result = await deleteObject({
model: clientModel,
id,
user: req.user,
});
if (result.error) {
logger.error('No client deleted:', result.error);
return res.status(result.code).send(result);
}
logger.debug(`Deleted client with ID: ${result._id}`);
res.send(result);
};
export const getClientStatsRouteHandler = async (req, res) => {
const result = await getModelStats({ model: clientModel });
if (result?.error) {
logger.error('Error fetching client stats:', result.error);
return res.status(result.code).send(result);
}
logger.trace('Client stats:', result);
res.send(result);
};
export const getClientHistoryRouteHandler = async (req, res) => {
const from = req.query.from;
const to = req.query.to;
const result = await getModelHistory({ model: clientModel, from, to });
if (result?.error) {
logger.error('Error fetching client history:', result.error);
return res.status(result.code).send(result);
}
logger.trace('Client history:', result);
res.send(result);
};
export const getClientNeighborsRouteHandler = 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: clientModel,
id,
filter,
search,
sort,
order,
});
if (result?.error) {
logger.error('Error fetching client neighbors.');
return res.status(result.code).send(result);
}
logger.debug(`Retrieved client neighbors for ID: ${id}`);
res.send(result);
};