farmcontrol-api/src/services/finance/paymentpolicies.js
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

240 lines
5.9 KiB
JavaScript

import config from '../../config.js';
import { paymentPolicyModel } from '../../database/schemas/finance/paymentpolicy.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';
import { syncPaymentPolicy } from '../../integrations/marketplace.js';
import { startPolicyMarketplaceSync } from '../misc/syncPolicyMarketplaces.js';
const logger = log4js.getLogger('PaymentPolicies');
logger.level = config.server.logLevel;
export const PAYMENT_POLICY_POPULATE = ['marketplaces.marketplace'];
const policyFields = (body = {}) => ({
name: body.name,
description: body.description,
immediatePay: body.immediatePay,
paymentInstructions: body.paymentInstructions,
marketplaces: body.marketplaces,
});
export const listPaymentPoliciesRouteHandler = async (
req,
res,
page = 1,
limit = 25,
property = '',
filter = {},
search = '',
sort = '',
order = 'ascend'
) => {
const result = await listObjects({
model: paymentPolicyModel,
page,
limit,
property,
filter,
search,
sort,
order,
populate: PAYMENT_POLICY_POPULATE,
});
if (result?.error) {
logger.error('Error listing payment policies.');
res.status(result.code).send(result);
return;
}
logger.debug(`List of payment policies (Page ${page}, Limit ${limit}). Count: ${result.length}.`);
res.send(result);
};
export const listPaymentPoliciesByPropertiesRouteHandler = async (
req,
res,
properties = '',
filter = {},
masterFilter = {}
) => {
const result = await listObjectsByProperties({
model: paymentPolicyModel,
properties,
filter,
masterFilter,
populate: PAYMENT_POLICY_POPULATE,
});
if (result?.error) {
logger.error('Error listing payment policies.');
res.status(result.code).send(result);
return;
}
logger.debug(`List of payment policies. Count: ${result.length}`);
res.send(result);
};
export const getPaymentPolicyPropertyValuesRouteHandler = async (
req,
res,
property,
filter,
masterFilter
) => {
const result = await getPropertyValues({
model: paymentPolicyModel,
property,
filter: { ...filter, ...masterFilter },
});
res.send(result);
};
export const searchPaymentPoliciesRouteHandler = async (req, res, search) => {
const result = await searchObjects({
model: paymentPolicyModel,
search,
populate: PAYMENT_POLICY_POPULATE,
});
res.send(result);
};
export const getPaymentPolicyRouteHandler = async (req, res) => {
const id = req.params.id;
const result = await getObject({
model: paymentPolicyModel,
id,
populate: PAYMENT_POLICY_POPULATE,
});
if (result?.error) {
logger.warn('Payment policy not found with supplied id.');
return res.status(result.code).send(result);
}
logger.debug(`Retrieved payment policy with ID: ${id}`);
res.send(result);
};
export const editPaymentPolicyRouteHandler = async (req, res) => {
const id = new mongoose.Types.ObjectId(req.params.id);
const result = await editObject({
model: paymentPolicyModel,
id,
updateData: { updatedAt: new Date(), ...policyFields(req.body) },
user: req.user,
populate: PAYMENT_POLICY_POPULATE,
});
if (result.error) {
logger.error('Error editing payment policy:', result.error);
res.status(result.code).send(result);
return;
}
logger.debug(`Edited payment policy with ID: ${id}`);
const synced = await startPolicyMarketplaceSync({
policy: result,
user: req.user,
syncFn: syncPaymentPolicy,
logger,
model: paymentPolicyModel,
populate: PAYMENT_POLICY_POPULATE,
});
res.send(synced || result);
};
export const newPaymentPolicyRouteHandler = async (req, res) => {
const result = await newObject({
model: paymentPolicyModel,
newData: { updatedAt: new Date(), ...policyFields(req.body) },
user: req.user,
});
if (result.error) {
logger.error('No payment policy created:', result.error);
return res.status(result.code).send(result);
}
logger.debug(`New payment policy with ID: ${result._id}`);
res.send(result);
};
export const deletePaymentPolicyRouteHandler = async (req, res) => {
const id = new mongoose.Types.ObjectId(req.params.id);
const result = await deleteObject({
model: paymentPolicyModel,
id,
user: req.user,
});
if (result.error) {
logger.error('No payment policy deleted:', result.error);
return res.status(result.code).send(result);
}
logger.debug(`Deleted payment policy with ID: ${result._id}`);
res.send(result);
};
export const getPaymentPolicyStatsRouteHandler = async (req, res) => {
const result = await getModelStats({ model: paymentPolicyModel });
if (result?.error) {
logger.error('Error fetching payment policy stats:', result.error);
return res.status(result.code).send(result);
}
res.send(result);
};
export const getPaymentPolicyHistoryRouteHandler = async (req, res) => {
const from = req.query.from;
const to = req.query.to;
const result = await getModelHistory({ model: paymentPolicyModel, from, to });
if (result?.error) {
logger.error('Error fetching payment policy history:', result.error);
return res.status(result.code).send(result);
}
res.send(result);
};
export const getPaymentPolicyNeighborsRouteHandler = 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: paymentPolicyModel,
id,
filter,
search,
sort,
order,
});
if (result?.error) {
logger.error('Error fetching paymentPolicy neighbors.');
return res.status(result.code).send(result);
}
res.send(result);
};