Merged in release/2024-11-01 (pull request #1865)

Release/2024 11 01
This commit is contained in:
Dave Richer
2024-10-29 18:05:04 +00:00
13 changed files with 126 additions and 68 deletions

View File

@@ -39,8 +39,8 @@ exports.default = async function ReloadCdkMakes(req, res) {
const deleteResult = await client const deleteResult = await client
.setHeaders({ Authorization: BearerToken }) .setHeaders({ Authorization: BearerToken })
.request(queries.DELETE_ALL_DMS_VEHICLES, {}); .request(queries.DELETE_ALL_DMS_VEHICLES, {});
console.log("🚀 ~ file: cdk-get-makes.js ~ line 53 ~ deleteResult", deleteResult);
// logger.logger.debug("🚀 ~ file: cdk-get-makes.js ~ line 53 ~ deleteResult", { deleteResult });
//Insert the new ones. //Insert the new ones.
const insertResult = await client.setHeaders({ Authorization: BearerToken }).request(queries.INSERT_DMS_VEHICLES, { const insertResult = await client.setHeaders({ Authorization: BearerToken }).request(queries.INSERT_DMS_VEHICLES, {
@@ -59,6 +59,7 @@ exports.default = async function ReloadCdkMakes(req, res) {
cdk_dealerid, cdk_dealerid,
count: newList.length count: newList.length
}); });
res.sendStatus(200); res.sendStatus(200);
} catch (error) { } catch (error) {
logger.log("cdk-replace-makes-models-error", "ERROR", req.user.email, null, { logger.log("cdk-replace-makes-models-error", "ERROR", req.user.email, null, {

View File

@@ -21,7 +21,7 @@ const getImage = async (imageUrl) => {
// Log the email in the database // Log the email in the database
const logEmail = async (req, email) => { const logEmail = async (req, email) => {
try { try {
const insertresult = await client.request(queries.INSERT_EMAIL_AUDIT, { await client.request(queries.INSERT_EMAIL_AUDIT, {
email: { email: {
to: email.to, to: email.to,
cc: email.cc, cc: email.cc,
@@ -34,13 +34,13 @@ const logEmail = async (req, email) => {
status: "Sent" status: "Sent"
} }
}); });
console.log(insertresult);
} catch (error) { } catch (error) {
logger.log("email-log-error", "error", req.user.email, null, { logger.log("email-log-error", "error", req?.user?.email, null, {
from: `${req.body.from.name} <${req.body.from.address}>`, from: `${req.body.from.name} <${req.body.from.address}>`,
to: req.body.to, to: req?.body?.to,
cc: req.body.cc, cc: req?.body?.cc,
subject: req.body.subject subject: req?.body?.subject,
email
// info, // info,
}); });
} }
@@ -70,12 +70,11 @@ const sendServerEmail = async ({ subject, text }) => {
} }
}, },
(err, info) => { (err, info) => {
console.log(err || info); logger.log("server-email-failure", err ? "error" : "debug", null, null, { message: err || info });
} }
); );
} catch (error) { } catch (error) {
console.log(error); logger.log("server-email-failure", "error", null, null, { error });
logger.log("server-email-failure", "error", null, null, error);
} }
}; };
@@ -88,8 +87,7 @@ const sendProManagerWelcomeEmail = async ({ to, subject, html }) => {
html html
}); });
} catch (error) { } catch (error) {
console.log(error); logger.log("server-email-failure", "error", null, null, { error });
logger.log("server-email-failure", "error", null, null, error);
} }
}; };
@@ -108,12 +106,12 @@ const sendTaskEmail = async ({ to, subject, type = "text", html, text, attachmen
attachments: attachments || null attachments: attachments || null
}, },
(err, info) => { (err, info) => {
console.log(err || info); // (message, type, user, record, meta
logger.log("server-email", err ? "error" : "debug", null, null, { message: err || info });
} }
); );
} catch (error) { } catch (error) {
console.log(error); logger.log("server-email-failure", "error", null, null, { error });
logger.log("server-email-failure", "error", null, null, error);
} }
}; };
@@ -184,9 +182,8 @@ const sendEmail = async (req, res) => {
} }
}, },
(err, info) => { (err, info) => {
console.log(err || info);
if (info) { if (info) {
logger.log("send-email-success", "DEBUG", req.user.email, null, { logger.log("send-email-success", "DEBUG", req?.user?.email, null, {
from: `${req.body.from.name} <${req.body.from.address}>`, from: `${req.body.from.name} <${req.body.from.address}>`,
replyTo: req.body.ReplyTo.Email, replyTo: req.body.ReplyTo.Email,
to: req.body.to, to: req.body.to,
@@ -205,7 +202,7 @@ const sendEmail = async (req, res) => {
success: true //response: info success: true //response: info
}); });
} else { } else {
logger.log("send-email-failure", "ERROR", req.user.email, null, { logger.log("send-email-failure", "ERROR", req?.user?.email, null, {
from: `${req.body.from.name} <${req.body.from.address}>`, from: `${req.body.from.name} <${req.body.from.address}>`,
replyTo: req.body.ReplyTo.Email, replyTo: req.body.ReplyTo.Email,
to: req.body.to, to: req.body.to,
@@ -290,7 +287,9 @@ ${body.bounce?.bouncedRecipients.map(
` `
}, },
(err, info) => { (err, info) => {
console.log("***", err || info); logger.log("sns-error", err ? "error" : "debug", "api", null, {
message: err ? JSON.stringify(error) : info
});
} }
); );
} }

View File

@@ -18,10 +18,10 @@ const tasksEmailQueue = taskEmailQueue();
const tasksEmailQueueCleanup = async () => { const tasksEmailQueueCleanup = async () => {
try { try {
// Example async operation // Example async operation
console.log("Performing Tasks Email Reminder process cleanup..."); // console.log("Performing Tasks Email Reminder process cleanup...");
await new Promise((resolve) => tasksEmailQueue.destroy(() => resolve())); await new Promise((resolve) => tasksEmailQueue.destroy(() => resolve()));
} catch (err) { } catch (err) {
console.error("Tasks Email Reminder process cleanup failed:", err); // console.error("Tasks Email Reminder process cleanup failed:", err);
} }
}; };

View File

@@ -10,8 +10,9 @@ const logger = require("../utils/logger");
const taskEmailQueue = () => const taskEmailQueue = () =>
new Queue( new Queue(
(taskIds, cb) => { (taskIds, cb) => {
console.log("Processing reminds for taskIds: ", taskIds.join(", ")); logger.log("Processing reminds for taskIds: ", "silly", null, null, {
taskIds: taskIds?.join(", ")
});
// Set the remind_at_sent to the current time. // Set the remind_at_sent to the current time.
const now = moment().toISOString(); const now = moment().toISOString();

View File

@@ -269,10 +269,14 @@ const sendNotification = async (req, res) => {
}) })
.then((response) => { .then((response) => {
// Response is a message ID string. // Response is a message ID string.
console.log("Successfully sent message:", response); logger.log("Successfully sent message:", "debug", req?.user?.email, null, {
response
});
}) })
.catch((error) => { .catch((error) => {
console.log("Error sending message:", error); logger.log("Successfully sent message:", "error", req?.user?.email, null, {
error
});
}); });
res.sendStatus(200); res.sendStatus(200);

View File

@@ -19,7 +19,8 @@ async function JobCosting(req, res) {
const BearerToken = req.BearerToken; const BearerToken = req.BearerToken;
const client = req.userGraphQLClient; const client = req.userGraphQLClient;
logger.log("job-costing-start", "DEBUG", req.user.email, jobid, null); //Uncomment for further testing
// logger.log("job-costing-start", "DEBUG", req.user.email, jobid, null);
try { try {
const resp = await client.setHeaders({ Authorization: BearerToken }).request(queries.QUERY_JOB_COSTING_DETAILS, { const resp = await client.setHeaders({ Authorization: BearerToken }).request(queries.QUERY_JOB_COSTING_DETAILS, {
@@ -46,7 +47,10 @@ async function JobCostingMulti(req, res) {
const BearerToken = req.BearerToken; const BearerToken = req.BearerToken;
const client = req.userGraphQLClient; const client = req.userGraphQLClient;
logger.log("job-costing-multi-start", "DEBUG", req.user.email, jobids, null); //Uncomment for further testing
// logger.log("job-costing-multi-start", "DEBUG", req?.user?.email, null, {
// jobids
// });
try { try {
const resp = await client const resp = await client
@@ -244,7 +248,8 @@ async function JobCostingMulti(req, res) {
data: ret data: ret
}); });
} catch (error) { } catch (error) {
logger.log("job-costing-multi-error", "ERROR", req.user.email, [jobids], { logger.log("job-costing-multi-error", "ERROR", req?.user?.email, null, {
jobids,
message: error.message, message: error.message,
stack: error.stack stack: error.stack
}); });
@@ -282,7 +287,13 @@ function GenerateCostingData(job) {
if (val.mod_lbr_ty) { if (val.mod_lbr_ty) {
const laborProfitCenter = val.profitcenter_labor || defaultProfits[val.mod_lbr_ty] || "Unknown"; const laborProfitCenter = val.profitcenter_labor || defaultProfits[val.mod_lbr_ty] || "Unknown";
if (laborProfitCenter === "Unknown") console.log("Unknown type", val.line_desc, val.mod_lbr_ty); //Uncomment for further testing
// if (laborProfitCenter === "Unknown") {
// logger.log("job-costing unknown type", "debug", null, null, {
// line_desc: val.line_desc,
// mod_lbr_ty: val.mod_lbr_ty
// });
// }
const rateName = `rate_${(val.mod_lbr_ty || "").toLowerCase()}`; const rateName = `rate_${(val.mod_lbr_ty || "").toLowerCase()}`;
@@ -349,10 +360,22 @@ function GenerateCostingData(job) {
if (val.part_type && val.part_type !== "PAE" && val.part_type !== "PAS" && val.part_type !== "PASL") { if (val.part_type && val.part_type !== "PAE" && val.part_type !== "PAS" && val.part_type !== "PASL") {
const partsProfitCenter = val.profitcenter_part || defaultProfits[val.part_type] || "Unknown"; const partsProfitCenter = val.profitcenter_part || defaultProfits[val.part_type] || "Unknown";
if (partsProfitCenter === "Unknown") console.log("Unknown type", val.line_desc, val.part_type); //Uncomment for further testing
// if (partsProfitCenter === "Unknown" || !partsProfitCenter) {
// logger.log(
// partsProfitCenter === "Unknown"
// ? "job-costing unknown type"
// : "Unknown cost/profit center mapping for parts.",
// "debug",
// null,
// null,
// {
// line_desc: val.line_desc,
// part_type: val.part_type
// }
// );
// }
if (!partsProfitCenter)
console.log("Unknown cost/profit center mapping for parts.", val.line_desc, val.part_type);
let partsAmount = Dinero({ let partsAmount = Dinero({
amount: val.act_price_before_ppc amount: val.act_price_before_ppc
? Math.round(val.act_price_before_ppc * 100) ? Math.round(val.act_price_before_ppc * 100)
@@ -409,10 +432,22 @@ function GenerateCostingData(job) {
if (val.part_type && val.part_type !== "PAE" && (val.part_type === "PAS" || val.part_type === "PASL")) { if (val.part_type && val.part_type !== "PAE" && (val.part_type === "PAS" || val.part_type === "PASL")) {
const partsProfitCenter = val.profitcenter_part || defaultProfits[val.part_type] || "Unknown"; const partsProfitCenter = val.profitcenter_part || defaultProfits[val.part_type] || "Unknown";
if (partsProfitCenter === "Unknown") console.log("Unknown type", val.line_desc, val.part_type); //Uncomment for further testing
// if (partsProfitCenter === "Unknown" || !partsProfitCenter) {
// logger.log(
// partsProfitCenter === "Unknown"
// ? "job-costing unknown type"
// : "job-costing Unknown cost/profit center mapping for sublet",
// "debug",
// null,
// null,
// {
// line_desc: val.line_desc,
// part_type: val.part_type
// }
// );
// }
if (!partsProfitCenter)
console.log("Unknown cost/profit center mapping for sublet.", val.line_desc, val.part_type);
const partsAmount = Dinero({ const partsAmount = Dinero({
amount: Math.round((val.act_price || 0) * 100) amount: Math.round((val.act_price || 0) * 100)
}) })
@@ -443,9 +478,14 @@ function GenerateCostingData(job) {
//If so, use it, otherwise try to use the same from the auto-allocate logic in IO app jobs-close-auto-allocate. //If so, use it, otherwise try to use the same from the auto-allocate logic in IO app jobs-close-auto-allocate.
const partsProfitCenter = val.profitcenter_part || getAdditionalCostCenter(val, defaultProfits) || "Unknown"; const partsProfitCenter = val.profitcenter_part || getAdditionalCostCenter(val, defaultProfits) || "Unknown";
if (partsProfitCenter === "Unknown") { //Uncomment for further testing
console.log("Unknown type", val.line_desc, val.part_type); // if (partsProfitCenter === "Unknown") {
} // logger.log("job-costing unknown type", "debug", null, null, {
// line_desc: val.line_desc,
// part_type: val.part_type
// });
// }
const partsAmount = Dinero({ const partsAmount = Dinero({
amount: Math.round((val.act_price || 0) * 100) amount: Math.round((val.act_price || 0) * 100)
}) })

View File

@@ -26,7 +26,7 @@ exports.totalsSsu = async function (req, res) {
const BearerToken = req.BearerToken; const BearerToken = req.BearerToken;
const client = req.userGraphQLClient; const client = req.userGraphQLClient;
logger.log("job-totals-ssu-USA", "DEBUG", req.user.email, id, null); logger.log("job-totals-ssu-USA", "DEBUG", req?.user?.email, id);
try { try {
const job = await client.setHeaders({ Authorization: BearerToken }).request(queries.GET_JOB_BY_PK, { const job = await client.setHeaders({ Authorization: BearerToken }).request(queries.GET_JOB_BY_PK, {
@@ -47,7 +47,7 @@ exports.totalsSsu = async function (req, res) {
res.status(200).send(); res.status(200).send();
} catch (error) { } catch (error) {
logger.log("job-totals-ssu-USA-error", "ERROR", req.user.email, id, { logger.log("job-totals-ssu-USA-error", "ERROR", req?.user?.email, id, {
jobid: id, jobid: id,
error error
}); });
@@ -84,12 +84,10 @@ async function Totals(req, res) {
const logger = req.logger; const logger = req.logger;
const client = req.userGraphQLClient; const client = req.userGraphQLClient;
logger.log("job-totals-USA", "DEBUG", req.user.email, job.id, { logger.log("job-totals-ssu-USA", "DEBUG", req.user.email, job.id, {
jobid: job.id jobid: job.id
}); });
logger.log("job-totals-ssu-USA", "DEBUG", req.user.email, id, null);
await AutoAddAtsIfRequired({ job, client }); await AutoAddAtsIfRequired({ job, client });
try { try {
@@ -961,7 +959,9 @@ function CalculateTaxesTotals(job, otherTotals) {
} }
} }
} catch (error) { } catch (error) {
console.error("Key with issue", key); logger.log("job-totals-USA Key with issue", "error", null, null, {
key
});
} }
}); });
@@ -1026,7 +1026,9 @@ function CalculateTaxesTotals(job, otherTotals) {
totalTaxByTier[taxTierKey] = totalTaxByTier[taxTierKey].add(taxAmountToAdd); totalTaxByTier[taxTierKey] = totalTaxByTier[taxTierKey].add(taxAmountToAdd);
} }
} catch (error) { } catch (error) {
console.error("PFP Calculation error", error); logger.log("job-totals-USA - PFP Calculation Error", "error", null, null, {
error
});
} }
}); });

View File

@@ -16,7 +16,11 @@ const validateFirebaseIdTokenMiddleware = async (req, res, next) => {
(!req.headers.authorization || !req.headers.authorization.startsWith("Bearer ")) && (!req.headers.authorization || !req.headers.authorization.startsWith("Bearer ")) &&
!(req.cookies && req.cookies.__session) !(req.cookies && req.cookies.__session)
) { ) {
console.error("Unauthorized attempt. No authorization provided."); logger.log("api-authorization-call", "warn", req?.user?.email, null, {
type: "unauthorized",
path: req.path,
body: req.body
});
return res.status(403).send("Unauthorized"); return res.status(403).send("Unauthorized");
} }
@@ -32,10 +36,10 @@ const validateFirebaseIdTokenMiddleware = async (req, res, next) => {
idToken = req.cookies.__session; idToken = req.cookies.__session;
} else { } else {
// No cookie // No cookie
console.error("Unauthorized attempt. No cookie provided."); logger.log("api-unauthorized-call", "warn", null, null, {
logger.log("api-unauthorized-call", "WARN", null, null, { type: "unauthorized",
req, path: req.path,
type: "no-cookie" body: req.body
}); });
return res.status(403).send("Unauthorized"); return res.status(403).send("Unauthorized");
@@ -47,11 +51,11 @@ const validateFirebaseIdTokenMiddleware = async (req, res, next) => {
req.user = decodedIdToken; req.user = decodedIdToken;
next(); next();
} catch (error) { } catch (error) {
logger.log("api-unauthorized-call", "WARN", null, null, { logger.log("api-unauthorized-call", "warn", null, null, {
path: req.path, path: req.path,
body: req.body, body: req.body,
type: "unauthroized", type: "unauthorized",
...error ...error
}); });

View File

@@ -45,12 +45,12 @@ exports.payall = async function (req, res) {
const path = diffParser(diff); const path = diffParser(diff);
if (diff.op === "add") { if (diff.op === "add") {
console.log(Object.keys(diff.val)); // console.log(Object.keys(diff.val));
if (typeof diff.val === "object" && Object.keys(diff.val).length > 1) { if (typeof diff.val === "object" && Object.keys(diff.val).length > 1) {
//Multiple values to add. //Multiple values to add.
Object.keys(diff.val).forEach((key) => { Object.keys(diff.val).forEach((key) => {
console.log("Hours", diff.val[key][Object.keys(diff.val[key])[0]]); // console.log("Hours", diff.val[key][Object.keys(diff.val[key])[0]]);
console.log("Rate", Object.keys(diff.val[key])[0]); // console.log("Rate", Object.keys(diff.val[key])[0]);
ticketsToInsert.push({ ticketsToInsert.push({
task_name: "Pay All", task_name: "Pay All",
jobid: job.id, jobid: job.id,

View File

@@ -49,7 +49,7 @@ exports.job = async (req, res) => {
if (bucketId) { if (bucketId) {
load.productionTotal[bucketId].count = load.productionTotal[bucketId].count + 1; load.productionTotal[bucketId].count = load.productionTotal[bucketId].count + 1;
} else { } else {
console.log("Uh oh, this job doesn't fit in a bucket!", item); // console.log("Uh oh, this job doesn't fit in a bucket!", item);
} }
}); });
@@ -254,7 +254,7 @@ const CalculateLoad = (currentLoad, buckets, jobsIn, jobsOut) => {
if (bucketId) { if (bucketId) {
newLoad[bucketId].count = newLoad[bucketId].count + 1; newLoad[bucketId].count = newLoad[bucketId].count + 1;
} else { } else {
console.log("[Util Arr Job]Uh oh, this job doesn't fit in a bucket!", job); // console.log("[Util Arr Job]Uh oh, this job doesn't fit in a bucket!", job);
} }
}); });
@@ -263,10 +263,10 @@ const CalculateLoad = (currentLoad, buckets, jobsIn, jobsOut) => {
if (bucketId) { if (bucketId) {
newLoad[bucketId].count = newLoad[bucketId].count - 1; newLoad[bucketId].count = newLoad[bucketId].count - 1;
if (newLoad[bucketId].count < 0) { if (newLoad[bucketId].count < 0) {
console.log("***ERROR: NEGATIVE LOAD Bucket =>", bucketId, job); // console.log("***ERROR: NEGATIVE LOAD Bucket =>", bucketId, job);
} }
} else { } else {
console.log("[Util Out Job]Uh oh, this job doesn't fit in a bucket!", job); // console.log("[Util Out Job]Uh oh, this job doesn't fit in a bucket!", job);
} }
}); });

View File

@@ -39,7 +39,7 @@ const processor = async (req, res) => {
} }
}); });
} catch (error) { } catch (error) {
console.log("error", error); // console.log("error", error);
res.status(400).send(error); res.status(400).send(error);
} }
}; };

View File

@@ -6,10 +6,11 @@ const client = require("../graphql-client/graphql-client").client;
const emailer = require("../email/sendemail"); const emailer = require("../email/sendemail");
const moment = require("moment-timezone"); const moment = require("moment-timezone");
const converter = require("json-2-csv"); const converter = require("json-2-csv");
const logger = require("../utils/logger");
exports.taskHandler = async (req, res) => { exports.taskHandler = async (req, res) => {
try { try {
const { bodyshopid, query, variables, text, to, subject, timezone } = req.body; const { query, variables, text, to, subject, timezone } = req.body;
//Check the variables to see if they are an object. //Check the variables to see if they are an object.
Object.keys(variables).forEach((key) => { Object.keys(variables).forEach((key) => {
@@ -32,8 +33,10 @@ exports.taskHandler = async (req, res) => {
text, text,
attachments: [{ filename: "query.csv", content: csv }] attachments: [{ filename: "query.csv", content: csv }]
}) })
.catch((err) => { .catch((error) => {
console.error("Errors sending CSV Email."); logger.log("Tasks - Error sending CSV EMAIL", "error", req?.user?.email, null, {
error
});
}); });
return res.status(200).send(csv); return res.status(200).send(csv);

View File

@@ -41,7 +41,8 @@ const redisSocketEvents = ({
// Register Socket Events // Register Socket Events
const registerSocketEvents = (socket) => { const registerSocketEvents = (socket) => {
createLogEvent(socket, "debug", `Registering RedisIO Socket Events.`); // Uncomment for further testing
// createLogEvent(socket, "debug", `Registering RedisIO Socket Events.`);
// Token Update Events // Token Update Events
const registerUpdateEvents = (socket) => { const registerUpdateEvents = (socket) => {
@@ -54,12 +55,13 @@ const redisSocketEvents = ({
// If We ever want to persist user Data across workers // If We ever want to persist user Data across workers
// await setSessionData(socket.id, "user", user); // await setSessionData(socket.id, "user", user);
createLogEvent(socket, "debug", "Token updated successfully"); // Uncomment for further testing
// createLogEvent(socket, "debug", "Token updated successfully");
socket.emit("token-updated", { success: true }); socket.emit("token-updated", { success: true });
} catch (error) { } catch (error) {
if (error.code === "auth/id-token-expired") { if (error.code === "auth/id-token-expired") {
createLogEvent(socket, "WARNING", "Stale token received, waiting for new token"); createLogEvent(socket, "warn", "Stale token received, waiting for new token");
socket.emit("token-updated", { socket.emit("token-updated", {
success: false, success: false,
error: "Stale token." error: "Stale token."
@@ -114,7 +116,9 @@ const redisSocketEvents = ({
// Disconnect Events // Disconnect Events
const registerDisconnectEvents = (socket) => { const registerDisconnectEvents = (socket) => {
const disconnect = () => { const disconnect = () => {
createLogEvent(socket, "debug", `User disconnected.`); // Uncomment for further testing
// createLogEvent(socket, "debug", `User disconnected.`);
const rooms = Array.from(socket.rooms).filter((room) => room !== socket.id); const rooms = Array.from(socket.rooms).filter((room) => room !== socket.id);
for (const room of rooms) { for (const room of rooms) {
socket.leave(room); socket.leave(room);