170 lines
4.6 KiB
JavaScript
170 lines
4.6 KiB
JavaScript
import dotenv from "dotenv";
|
|
import { vendorModel } from "../../schemas/management/vendor.schema.js";
|
|
import jwt from "jsonwebtoken";
|
|
import log4js from "log4js";
|
|
import mongoose from "mongoose";
|
|
import { newAuditLog } from "../../util/index.js";
|
|
import { auditLogModel } from "../../schemas/management/auditlog.schema.js";
|
|
|
|
dotenv.config();
|
|
|
|
const logger = log4js.getLogger("Vendors");
|
|
logger.level = process.env.LOG_LEVEL;
|
|
|
|
export const listVendorsRouteHandler = async (
|
|
req,
|
|
res,
|
|
page = 1,
|
|
limit = 25,
|
|
property = "",
|
|
filter = {},
|
|
) => {
|
|
try {
|
|
// Calculate the skip value based on the page number and limit
|
|
const skip = (page - 1) * limit;
|
|
|
|
let vendor;
|
|
let aggregateCommand = [];
|
|
|
|
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: { image: 0, url: 0 } });
|
|
}
|
|
|
|
aggregateCommand.push({ $skip: skip });
|
|
aggregateCommand.push({ $limit: Number(limit) });
|
|
|
|
console.log(aggregateCommand);
|
|
|
|
vendor = await vendorModel.aggregate(aggregateCommand);
|
|
|
|
logger.trace(
|
|
`List of vendors (Page ${page}, Limit ${limit}, Property ${property}):`,
|
|
vendor,
|
|
);
|
|
res.send(vendor);
|
|
} catch (error) {
|
|
logger.error("Error listing vendors:", error);
|
|
res.status(500).send({ error: error });
|
|
}
|
|
};
|
|
|
|
export const getVendorRouteHandler = async (req, res) => {
|
|
try {
|
|
// Get ID from params
|
|
const id = new mongoose.Types.ObjectId(req.params.id);
|
|
// Fetch the vendor with the given remote address
|
|
const vendor = await vendorModel.findOne({
|
|
_id: id,
|
|
});
|
|
|
|
if (!vendor) {
|
|
logger.warn(`Vendor not found with supplied id.`);
|
|
return res.status(404).send({ error: "Print job not found." });
|
|
}
|
|
|
|
logger.trace(`Vendor with ID: ${id}:`, vendor);
|
|
|
|
const auditLogs = await auditLogModel.find({
|
|
target: id
|
|
}).populate('owner');
|
|
|
|
res.send({...vendor._doc, auditLogs: auditLogs});
|
|
} catch (error) {
|
|
logger.error("Error fetching Vendor:", error);
|
|
res.status(500).send({ error: error.message });
|
|
}
|
|
};
|
|
|
|
export const editVendorRouteHandler = async (req, res) => {
|
|
try {
|
|
// Get ID from params
|
|
const id = new mongoose.Types.ObjectId(req.params.id);
|
|
// Fetch the vendor with the given remote address
|
|
const vendor = await vendorModel.findOne({ _id: id });
|
|
|
|
if (!vendor) {
|
|
// Error handling
|
|
logger.warn(`Vendor not found with supplied id.`);
|
|
return res.status(404).send({ error: "Print job not found." });
|
|
}
|
|
|
|
logger.trace(`Vendor with ID: ${id}:`, vendor);
|
|
|
|
try {
|
|
const updateData = {
|
|
updatedAt: new Date(),
|
|
contact: req.body.contact,
|
|
country: req.body.country,
|
|
name: req.body.name,
|
|
website: req.body.website,
|
|
phone: req.body.phone,
|
|
email: req.body.email,
|
|
};
|
|
|
|
console.log(req.user)
|
|
|
|
// Create audit log before updating
|
|
await newAuditLog(
|
|
vendor.toObject(),
|
|
updateData,
|
|
id,
|
|
'Vendor',
|
|
req.user._id,
|
|
'User'
|
|
);
|
|
|
|
const result = await vendorModel.updateOne(
|
|
{ _id: id },
|
|
{ $set: updateData },
|
|
);
|
|
if (result.nModified === 0) {
|
|
logger.error("No Vendor updated.");
|
|
res.status(500).send({ error: "No vendors updated." });
|
|
}
|
|
} catch (updateError) {
|
|
logger.error("Error updating vendor:", updateError);
|
|
res.status(500).send({ error: updateError.message });
|
|
}
|
|
res.send("OK");
|
|
} catch (fetchError) {
|
|
logger.error("Error fetching vendor:", fetchError);
|
|
res.status(500).send({ error: fetchError.message });
|
|
}
|
|
};
|
|
|
|
export const newVendorRouteHandler = async (req, res) => {
|
|
try {
|
|
let { ...newVendor } = req.body;
|
|
newVendor = { ...newVendor, createdAt: new Date(), updatedAt: new Date() };
|
|
|
|
const result = await vendorModel.create(newVendor);
|
|
if (result.nCreated === 0) {
|
|
logger.error("No vendor created.");
|
|
res.status(500).send({ error: "No vendor created." });
|
|
}
|
|
|
|
// Create audit log for new vendor
|
|
await newAuditLog(
|
|
{},
|
|
newVendor,
|
|
result._id,
|
|
'Vendor',
|
|
req.user.id, // Assuming user ID is available in req.user
|
|
'User'
|
|
);
|
|
|
|
res.status(200).send({ status: "ok" });
|
|
} catch (updateError) {
|
|
logger.error("Error updating vendor:", updateError);
|
|
res.status(500).send({ error: updateError.message });
|
|
}
|
|
};
|