From f6062287924f9fadf1fb26b226e2800c0ca8600a Mon Sep 17 00:00:00 2001 From: Dave Richer Date: Wed, 11 Sep 2024 19:08:24 -0400 Subject: [PATCH] feature/IO-2742-redis - Checkpoint, Redis fully implemented. Signed-off-by: Dave Richer --- client/src/App/App.jsx | 4 +- .../dms-allocations-summary-ap.component.jsx | 115 +-- .../dms-log-events.component.jsx | 7 +- .../production-board-kanban.container.jsx | 1 + .../dms-payables/dms-payables.container.jsx | 37 +- client/src/pages/dms/dms.container.jsx | 40 +- server.js | 30 + server/accounting/pbs/pbs-ap-allocations.js | 133 +-- server/accounting/pbs/pbs-job-export.js | 391 +++++---- server/cdk/cdk-calculate-allocations.js | 49 +- server/cdk/cdk-get-makes.js | 2 +- server/cdk/cdk-job-export.js | 773 ++++++++++-------- server/cdk/cdk-wsdl.js | 15 +- server/web-sockets/web-socket.js | 137 +++- 14 files changed, 1012 insertions(+), 722 deletions(-) diff --git a/client/src/App/App.jsx b/client/src/App/App.jsx index 4cf5b5d35..c2bfc0a7d 100644 --- a/client/src/App/App.jsx +++ b/client/src/App/App.jsx @@ -214,7 +214,9 @@ export function App({ bodyshop, checkUserSession, currentUser, online, setOnline path="/tech/*" element={ - + + + } > diff --git a/client/src/components/dms-allocations-summary-ap/dms-allocations-summary-ap.component.jsx b/client/src/components/dms-allocations-summary-ap/dms-allocations-summary-ap.component.jsx index b4fc66577..abbde7277 100644 --- a/client/src/components/dms-allocations-summary-ap/dms-allocations-summary-ap.component.jsx +++ b/client/src/components/dms-allocations-summary-ap/dms-allocations-summary-ap.component.jsx @@ -1,62 +1,77 @@ import { SyncOutlined } from "@ant-design/icons"; import { Button, Card, Form, Input, Table } from "antd"; -import React, { useEffect, useState } from "react"; +import React, { useEffect, useState, useContext } from "react"; import { useTranslation } from "react-i18next"; import { connect } from "react-redux"; import { createStructuredSelector } from "reselect"; import { selectBodyshop } from "../../redux/user/user.selectors"; import { pageLimit } from "../../utils/config"; +import SocketContext from "../../contexts/SocketIO/socketContext.jsx"; // Import SocketContext const mapStateToProps = createStructuredSelector({ - //currentUser: selectCurrentUser bodyshop: selectBodyshop }); -const mapDispatchToProps = (dispatch) => ({ - //setUserLanguage: language => dispatch(setUserLanguage(language)) -}); +export default connect(mapStateToProps)(DmsAllocationsSummaryAp); -export default connect(mapStateToProps, mapDispatchToProps)(DmsAllocationsSummaryAp); - -export function DmsAllocationsSummaryAp({ socket, bodyshop, billids, title }) { +export function DmsAllocationsSummaryAp({ bodyshop, billids, title }) { const { t } = useTranslation(); const [allocationsSummary, setAllocationsSummary] = useState([]); + const { socket } = useContext(SocketContext); useEffect(() => { - socket.on("ap-export-success", (billid) => { + if (!socket) return; + + const handleSuccess = async (billid) => { setAllocationsSummary((allocationsSummary) => allocationsSummary.map((a) => { if (a.billid !== billid) return a; return { ...a, status: "Successful" }; }) ); - }); - socket.on("ap-export-failure", ({ billid, error }) => { - allocationsSummary.map((a) => { - if (a.billid !== billid) return a; - return { ...a, status: error }; - }); - }); - if (socket.disconnected) socket.connect(); - return () => { - socket.removeListener("ap-export-success"); - socket.removeListener("ap-export-failure"); - //socket.disconnect(); + try { + await new Promise((resolve, reject) => { + socket.emit("clear-dms-session", (response) => { + if (response && response.status === "ok") { + resolve(); + } else { + reject(new Error("Failed to clear DMS session")); + } + }); + }); + } catch (error) { + console.error("Failed to clear DMS session", error); + } }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + + const handleFailure = ({ billid, error }) => { + setAllocationsSummary((allocationsSummary) => + allocationsSummary.map((a) => { + if (a.billid !== billid) return a; + return { ...a, status: error }; + }) + ); + }; + + socket.on("ap-export-success", handleSuccess); + socket.on("ap-export-failure", handleFailure); + + return () => { + socket.off("ap-export-success", handleSuccess); + socket.off("ap-export-failure", handleFailure); + }; + }, [socket]); useEffect(() => { - if (socket.connected) { + if (socket && socket.connected) { socket.emit("pbs-calculate-allocations-ap", billids, (ack) => { setAllocationsSummary(ack); - socket.allocationsSummary = ack; }); } }, [socket, socket.connected, billids]); - console.log(allocationsSummary); + const columns = [ { title: t("general.labels.status"), @@ -68,35 +83,40 @@ export function DmsAllocationsSummaryAp({ socket, bodyshop, billids, title }) { dataIndex: ["Posting", "Reference"], key: "reference" }, - { title: t("jobs.fields.dms.lines"), dataIndex: "Lines", key: "Lines", render: (text, record) => ( - - - - - - {record.Posting.Lines.map((l, idx) => ( - - - - + + + + + - ))} + + + {record.Posting.Lines.map((l, idx) => ( + + + + + + ))} +
{t("bills.fields.invoice_number")}{t("bodyshop.fields.dms.dms_acctnumber")}{t("jobs.fields.dms.amount")}
{l.InvoiceNumber}{l.Account}{l.Amount}
{t("bills.fields.invoice_number")}{t("bodyshop.fields.dms.dms_acctnumber")}{t("jobs.fields.dms.amount")}
{l.InvoiceNumber}{l.Account}{l.Amount}
) } ]; const handleFinish = async (values) => { - socket.emit(`pbs-export-ap`, { - billids, - txEnvelope: values - }); + if (socket) { + socket.emit("pbs-export-ap", { + billids, + txEnvelope: values + }); + } }; return ( @@ -105,7 +125,9 @@ export function DmsAllocationsSummaryAp({ socket, bodyshop, billids, title }) { extra={ - {/* {*/} - {/* setLogs([]);*/} - {/* socket.disconnect();*/} - {/* socket.connect();*/} - {/* }}*/} - {/*>*/} - {/* Reconnect*/} - {/**/} + } > - + ); } - -export const determineDmsType = (bodyshop) => { - if (bodyshop.cdk_dealerid) return "cdk"; - else { - return "pbs"; - } -}; diff --git a/client/src/pages/dms/dms.container.jsx b/client/src/pages/dms/dms.container.jsx index c4f9ae5cd..ab1d40f95 100644 --- a/client/src/pages/dms/dms.container.jsx +++ b/client/src/pages/dms/dms.container.jsx @@ -104,7 +104,7 @@ export function DmsContainer({ bodyshop, setBreadcrumbs, setSelectedHeader, inse setLogs((logs) => [...logs, payload]); }; - const handleExportSuccess = (payload) => { + const handleExportSuccess = async (payload) => { notification.success({ message: t("jobs.successes.exported") }); @@ -113,6 +113,21 @@ export function DmsContainer({ bodyshop, setBreadcrumbs, setSelectedHeader, inse operation: AuditTrailMapping.jobexported(), type: "jobexported" }); + + try { + await new Promise((resolve, reject) => { + socket.emit("clear-dms-session", (response) => { + if (response && response.status === "ok") { + resolve(); + } else { + reject(new Error("Failed to clear DMS session")); + } + }); + }); + } catch (error) { + console.error("Failed to clear DMS session", error); + } + history("/manage/accounting/receivables"); }; @@ -186,20 +201,21 @@ export function DmsContainer({ bodyshop, setBreadcrumbs, setSelectedHeader, inse WARNING ERROR - - {/* {*/} - {/* setLogs([]);*/} - {/* socket.disconnect();*/} - {/* socket.connect();*/} - {/* }}*/} - {/*>*/} - {/* Reconnect*/} - {/**/} + 4 + } > - + diff --git a/server.js b/server.js index 2eb415cf3..f0897c3f5 100644 --- a/server.js +++ b/server.js @@ -141,6 +141,36 @@ const main = async () => { exports.redisClient = pubClient; + // Store session data in Redis + exports.setSessionData = async (socketId, key, value) => { + await pubClient.hSet(`socket:${socketId}`, key, JSON.stringify(value)); // Use Redis pubClient + }; + + // Retrieve session data from Redis + exports.getSessionData = async (socketId, key) => { + const data = await pubClient.hGet(`socket:${socketId}`, key); + return data ? JSON.parse(data) : null; + }; + + // Clear session data from Redis + exports.clearSessionData = async (socketId) => { + await pubClient.del(`socket:${socketId}`); + }; + + // TODO: Remove, just a demo of hGet and hSet + // async function demoSessionData() { + // // Store session data using setSessionData + // await exports.setSessionData("testSocketId", "field1", "Hello, Redis Hash!"); + // + // // Retrieve session data using getSessionData + // const value = await exports.getSessionData("testSocketId", "field1"); + // + // // Output the retrieved value + // console.log(value); + // } + // demoSessionData().catch(console.error); + // TODO: End of demo + require("./server/web-sockets/web-socket"); applyMiddleware(app); diff --git a/server/accounting/pbs/pbs-ap-allocations.js b/server/accounting/pbs/pbs-ap-allocations.js index 3b8a20996..e2212cae5 100644 --- a/server/accounting/pbs/pbs-ap-allocations.js +++ b/server/accounting/pbs/pbs-ap-allocations.js @@ -12,67 +12,90 @@ const AxiosLib = require("axios").default; const axios = AxiosLib.create(); const { PBS_ENDPOINTS, PBS_CREDENTIALS } = require("./pbs-constants"); const { CheckForErrors } = require("./pbs-job-export"); +const { getSessionData, setSessionData } = require("../../../server"); const uuid = require("uuid").v4; -axios.interceptors.request.use((x) => { - const socket = x.socket; - const headers = { - ...x.headers.common, - ...x.headers[x.method], - ...x.headers - }; - const printable = `${new Date()} | Request: ${x.method.toUpperCase()} | ${ - x.url - } | ${JSON.stringify(x.data)} | ${JSON.stringify(headers)}`; - console.log(printable); +axios.interceptors.request.use( + async (x) => { + const socket = x.socket; - CdkBase.createJsonEvent(socket, "TRACE", `Raw Request: ${printable}`, x.data); + const headers = { + ...x.headers.common, + ...x.headers[x.method], + ...x.headers + }; - return x; -}); + const printable = `${new Date()} | Request: ${x.method.toUpperCase()} | ${ + x.url + } | ${JSON.stringify(x.data)} | ${JSON.stringify(headers)}`; -axios.interceptors.response.use((x) => { - const socket = x.config.socket; + console.log(printable); - const printable = `${new Date()} | Response: ${x.status} | ${JSON.stringify(x.data)}`; - console.log(printable); - CdkBase.createJsonEvent(socket, "TRACE", `Raw Response: ${printable}`, x.data); + // Use await properly here for the async operation + await CdkBase.createJsonEvent(socket, "TRACE", `Raw Request: ${printable}`, x.data); - return x; -}); + return x; // Return the modified request + }, + (error) => { + return Promise.reject(error); // Proper error handling + } +); + +axios.interceptors.response.use( + async (x) => { + const socket = x.config.socket; + + const printable = `${new Date()} | Response: ${x.status} | ${JSON.stringify(x.data)}`; + + console.log(printable); + + // Use await properly here for the async operation + await CdkBase.createJsonEvent(socket, "TRACE", `Raw Response: ${printable}`, x.data); + + return x; // Return the modified response + }, + (error) => { + return Promise.reject(error); // Proper error handling + } +); async function PbsCalculateAllocationsAp(socket, billids) { try { - CdkBase.createLogEvent(socket, "DEBUG", `Received request to calculate allocations for ${billids}`); + await CdkBase.createLogEvent(socket, "DEBUG", `Received request to calculate allocations for ${billids}`); + const { bills, bodyshops } = await QueryBillData(socket, billids); const bodyshop = bodyshops[0]; - socket.bodyshop = bodyshop; - socket.bills = bills; + + await setSessionData(socket.id, "bills", bills); + await setSessionData(socket.id, "bodyshop", bodyshop); + + const txEnvelope = await getSessionData(socket.id, "txEnvelope"); //Each bill will enter it's own top level transaction. const transactionlist = []; if (bills.length === 0) { - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "ERROR", `No bills found for export. Ensure they have not already been exported and try again.` ); } + bills.forEach((bill) => { //Keep the allocations at the bill level. const transactionObject = { - SerialNumber: socket.bodyshop.pbs_serialnumber, + SerialNumber: bodyshop.pbs_serialnumber, billid: bill.id, Posting: { - Reference: bill.invoice_number, - JournalCode: socket.txEnvelope ? socket.txEnvelope.journal : null, - TransactionDate: moment().tz(socket.bodyshop.timezone).toISOString(), //"0001-01-01T00:00:00.0000000Z", //Description: "Bulk AP posting.", //AdditionalInfo: "String", - Source: "ImEX Online", //TODO:AIO Resolve this for rome online. - Lines: [] //socket.apAllocations, + Reference: bill.invoice_number, + JournalCode: txEnvelope?.journal, + TransactionDate: moment().tz(bodyshop.timezone).toISOString(), + Source: "ImEX Online", // TODO: Resolve this for Rome Online. + Lines: [] // Will be populated with allocation data, } }; @@ -117,13 +140,13 @@ async function PbsCalculateAllocationsAp(socket, billids) { }; } - //Add the line amount. + // Add the line amount. billHash[cc.name] = { ...billHash[cc.name], Amount: billHash[cc.name].Amount.add(lineDinero) }; - //Does the line have taxes? + // Does the line have taxes? if (bl.applicable_taxes.federal) { billHash[bodyshop.md_responsibility_centers.taxes.federal_itc.name] = { ...billHash[bodyshop.md_responsibility_centers.taxes.federal_itc.name], @@ -145,7 +168,7 @@ async function PbsCalculateAllocationsAp(socket, billids) { let APAmount = Dinero(); Object.keys(billHash).map((key) => { - if (billHash[key].Amount.getAmount() > 0 || billHash[key].Amount.getAmount() < 0) { + if (billHash[key].Amount.getAmount() !== 0) { transactionObject.Posting.Lines.push({ ...billHash[key], Amount: billHash[key].Amount.toFormat("0.00") @@ -169,19 +192,19 @@ async function PbsCalculateAllocationsAp(socket, billids) { return transactionlist; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error encountered in PbsCalculateAllocationsAp. ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error encountered in PbsCalculateAllocationsAp. ${error}`); } } exports.PbsCalculateAllocationsAp = PbsCalculateAllocationsAp; async function QueryBillData(socket, billids) { - CdkBase.createLogEvent(socket, "DEBUG", `Querying bill data for id(s) ${billids}`); + await CdkBase.createLogEvent(socket, "DEBUG", `Querying bill data for id(s) ${billids}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); const result = await client .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .request(queries.GET_PBS_AP_ALLOCATIONS, { billids: billids }); - CdkBase.createLogEvent(socket, "TRACE", `Bill data query result ${JSON.stringify(result, null, 2)}`); + await CdkBase.createLogEvent(socket, "TRACE", `Bill data query result ${JSON.stringify(result, null, 2)}`); return result; } @@ -196,40 +219,50 @@ function getCostAccount(billline, respcenters) { } exports.PbsExportAp = async function (socket, { billids, txEnvelope }) { - CdkBase.createLogEvent(socket, "DEBUG", `Exporting selected AP.`); + await CdkBase.createLogEvent(socket, "DEBUG", `Exporting selected AP.`); - //apAllocations has the same shap as the lines key for the accounting posting to PBS. - socket.apAllocations = await PbsCalculateAllocationsAp(socket, billids); - socket.txEnvelope = txEnvelope; - for (const allocation of socket.apAllocations) { + //apAllocations has the same shape as the lines key for the accounting posting to PBS. + const apAllocations = await PbsCalculateAllocationsAp(socket, billids); + await setSessionData(socket.id, "apAllocations", apAllocations); + + // Store txEnvelope in session + await setSessionData(socket.id, "txEnvelope", txEnvelope); + + for (const allocation of apAllocations) { const { billid, ...restAllocation } = allocation; const { data: AccountPostingChange } = await axios.post(PBS_ENDPOINTS.AccountingPostingChange, restAllocation, { auth: PBS_CREDENTIALS, socket }); - CheckForErrors(socket, AccountPostingChange); + CheckForErrors(socket, AccountPostingChange).catch((err) => + console.error(`Error running CheckingForErrors in pbs-ap-allocations`) + ); if (AccountPostingChange.WasSuccessful) { - CdkBase.createLogEvent(socket, "DEBUG", `Marking bill as exported.`); + await CdkBase.createLogEvent(socket, "DEBUG", `Marking bill as exported.`); await MarkApExported(socket, [billid]); socket.emit("ap-export-success", billid); } else { - CdkBase.createLogEvent(socket, "ERROR", `Export was not succesful.`); + await CdkBase.createLogEvent(socket, "ERROR", `Export was not successful.`); socket.emit("ap-export-failure", { billid, error: AccountPostingChange.Message }); } } + socket.emit("ap-export-complete"); }; async function MarkApExported(socket, billids) { - CdkBase.createLogEvent(socket, "DEBUG", `Marking bills as exported for id ${billids}`); + const bills = await getSessionData(socket.id, "bills"); + const bodyshop = await getSessionData(socket.id, "bodyshop"); + + await CdkBase.createLogEvent(socket, "DEBUG", `Marking bills as exported for id ${billids}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); - const result = await client + return await client .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .request(queries.MARK_BILLS_EXPORTED, { billids, @@ -237,13 +270,11 @@ async function MarkApExported(socket, billids) { exported: true, exported_at: new Date() }, - logs: socket.bills.map((bill) => ({ - bodyshopid: socket.bodyshop.id, + logs: bills.map((bill) => ({ + bodyshopid: bodyshop.id, billid: bill.id, successful: true, useremail: socket.user.email })) }); - - return result; } diff --git a/server/accounting/pbs/pbs-job-export.js b/server/accounting/pbs/pbs-job-export.js index 7101f2ad4..5ec38982f 100644 --- a/server/accounting/pbs/pbs-job-export.js +++ b/server/accounting/pbs/pbs-job-export.js @@ -12,136 +12,168 @@ const CalculateAllocations = require("../../cdk/cdk-calculate-allocations").defa const CdkBase = require("../../web-sockets/web-socket"); const moment = require("moment-timezone"); const Dinero = require("dinero.js"); +const { setSessionData, getSessionData } = require("../../../server"); const InstanceManager = require("../../utils/instanceMgr").default; const axios = AxiosLib.create(); -axios.interceptors.request.use((x) => { - const socket = x.socket; +axios.interceptors.request.use( + async (x) => { + const socket = x.socket; - const headers = { - ...x.headers.common, - ...x.headers[x.method], - ...x.headers - }; - const printable = `${new Date()} | Request: ${x.method.toUpperCase()} | ${ - x.url - } | ${JSON.stringify(x.data)} | ${JSON.stringify(headers)}`; - console.log(printable); + const headers = { + ...x.headers.common, + ...x.headers[x.method], + ...x.headers + }; - CdkBase.createJsonEvent(socket, "TRACE", `Raw Request: ${printable}`, x.data); + const printable = `${new Date()} | Request: ${x.method.toUpperCase()} | ${ + x.url + } | ${JSON.stringify(x.data)} | ${JSON.stringify(headers)}`; - return x; -}); + console.log(printable); -axios.interceptors.response.use((x) => { - const socket = x.config.socket; + await CdkBase.createJsonEvent(socket, "TRACE", `Raw Request: ${printable}`, x.data); - const printable = `${new Date()} | Response: ${x.status} | ${JSON.stringify(x.data)}`; - console.log(printable); - CdkBase.createJsonEvent(socket, "TRACE", `Raw Response: ${printable}`, x.data); + return x; // Make sure to return the request object + }, + (error) => { + return Promise.reject(error); + } +); - return x; -}); +axios.interceptors.response.use( + async (x) => { + const socket = x.config.socket; + + const printable = `${new Date()} | Response: ${x.status} | ${JSON.stringify(x.data)}`; + + console.log(printable); + + await CdkBase.createJsonEvent(socket, "TRACE", `Raw Response: ${printable}`, x.data); + + return x; // Make sure to return the response object + }, + (error) => { + return Promise.reject(error); + } +); exports.default = async function (socket, { txEnvelope, jobid }) { - socket.logEvents = []; - socket.recordid = jobid; - socket.txEnvelope = txEnvelope; try { - CdkBase.createLogEvent(socket, "DEBUG", `Received Job export request for id ${jobid}`); + await setSessionData(socket.id, "logEvents", []); + await setSessionData(socket.id, "recordid", jobid); + await setSessionData(socket.id, "txEnvelope", txEnvelope); + + await CdkBase.createLogEvent(socket, "DEBUG", `Received Job export request for id ${jobid}`); const JobData = await QueryJobData(socket, jobid); - socket.JobData = JobData; - CdkBase.createLogEvent(socket, "DEBUG", `Querying the DMS for the Vehicle Record.`); - //Query for the Vehicle record to get the associated customer. - socket.DmsVeh = await QueryVehicleFromDms(socket); + await setSessionData(socket.id, "JobData", JobData); + + await CdkBase.createLogEvent(socket, "DEBUG", `Querying the DMS for the Vehicle Record.`); + + // Query for the Vehicle record to get the associated customer + const DmsVeh = await QueryVehicleFromDms(socket); + await setSessionData(socket.id, "DmsVeh", DmsVeh); + + let DMSVehCustomer; + //Todo: Need to validate the lines and methods below. - if (socket.DmsVeh && socket.DmsVeh.CustomerRef) { - //Get the associated customer from the Vehicle Record. - socket.DMSVehCustomer = await QueryCustomerBycodeFromDms(socket, socket.DmsVeh.CustomerRef); + if (DmsVeh?.CustomerRef) { + // Get the associated customer from the Vehicle Record + DMSVehCustomer = await QueryCustomerBycodeFromDms(socket, DmsVeh.CustomerRef); + await setSessionData(socket.id, "DMSVehCustomer", DMSVehCustomer); } - socket.DMSCustList = await QueryCustomersFromDms(socket); + + const DMSCustList = await QueryCustomersFromDms(socket); + await setSessionData(socket.id, "DMSCustList", DMSCustList); socket.emit("pbs-select-customer", [ - ...(socket.DMSVehCustomer ? [{ ...socket.DMSVehCustomer, vinOwner: true }] : []), - ...socket.DMSCustList + ...(DMSVehCustomer ? [{ ...DMSVehCustomer, vinOwner: true }] : []), + ...DMSCustList ]); } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error encountered in PbsJobExport. ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error encountered in PbsJobExport. ${error}`); } }; exports.PbsSelectedCustomer = async function PbsSelectedCustomer(socket, selectedCustomerId) { try { - if (socket.JobData.bodyshop.pbs_configuration.disablecontactvehicle === false) { - CdkBase.createLogEvent(socket, "DEBUG", `User selected customer ${selectedCustomerId || "NEW"}`); + const JobData = await getSessionData(socket.id, "JobData"); - //Upsert the contact information as per Wafaa's Email. - CdkBase.createLogEvent( + if (JobData.bodyshop.pbs_configuration.disablecontactvehicle === false) { + await CdkBase.createLogEvent(socket, "DEBUG", `User selected customer ${selectedCustomerId || "NEW"}`); + + // Upsert the contact information as per Wafaa's Email + await CdkBase.createLogEvent( socket, "DEBUG", `Upserting contact information to DMS for ${ - socket.JobData.ownr_fn || "" - } ${socket.JobData.ownr_ln || ""} ${socket.JobData.ownr_co_nm || ""}` + JobData.ownr_fn || "" + } ${JobData.ownr_ln || ""} ${JobData.ownr_co_nm || ""}` ); + const ownerRef = await UpsertContactData(socket, selectedCustomerId); - CdkBase.createLogEvent(socket, "DEBUG", `Upserting vehicle information to DMS for ${socket.JobData.v_vin}`); + await CdkBase.createLogEvent(socket, "DEBUG", `Upserting vehicle information to DMS for ${JobData.v_vin}`); await UpsertVehicleData(socket, ownerRef.ReferenceId); } else { - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "DEBUG", `Contact and Vehicle updates disabled. Skipping to accounting data insert.` ); } - CdkBase.createLogEvent(socket, "DEBUG", `Inserting account data.`); - CdkBase.createLogEvent(socket, "DEBUG", `Inserting accounting posting data..`); + + await CdkBase.createLogEvent(socket, "DEBUG", `Inserting account data.`); + await CdkBase.createLogEvent(socket, "DEBUG", `Inserting accounting posting data..`); const insertResponse = await InsertAccountPostingData(socket); + // TODO: Insert Clear session if (insertResponse.WasSuccessful) { - CdkBase.createLogEvent(socket, "DEBUG", `Marking job as exported.`); - await MarkJobExported(socket, socket.JobData.id); + await CdkBase.createLogEvent(socket, "DEBUG", `Marking job as exported.`); + await MarkJobExported(socket, JobData.id); - socket.emit("export-success", socket.JobData.id); + socket.emit("export-success", JobData.id); } else { - CdkBase.createLogEvent(socket, "ERROR", `Export was not succesful.`); + await CdkBase.createLogEvent(socket, "ERROR", `Export was not successful.`); } } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkSelectedCustomer. ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error encountered in PbsSelectedCustomer. ${error}`); await InsertFailedExportLog(socket, error); } }; async function CheckForErrors(socket, response) { if (response.WasSuccessful === undefined || response.WasSuccessful === true) { - CdkBase.createLogEvent(socket, "DEBUG", `Successful response from DMS. ${response.Message || ""}`); + await CdkBase.createLogEvent(socket, "DEBUG", `Successful response from DMS. ${response.Message || ""}`); } else { - CdkBase.createLogEvent(socket, "ERROR", `Error received from DMS: ${response.Message}`); - CdkBase.createLogEvent(socket, "TRACE", `Error received from DMS: ${JSON.stringify(response)}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error received from DMS: ${response.Message}`); + await CdkBase.createLogEvent(socket, "TRACE", `Error received from DMS: ${JSON.stringify(response)}`); } } exports.CheckForErrors = CheckForErrors; async function QueryJobData(socket, jobid) { - CdkBase.createLogEvent(socket, "DEBUG", `Querying job data for id ${jobid}`); + await CdkBase.createLogEvent(socket, "DEBUG", `Querying job data for id ${jobid}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); const result = await client .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .request(queries.QUERY_JOBS_FOR_PBS_EXPORT, { id: jobid }); - CdkBase.createLogEvent(socket, "TRACE", `Job data query result ${JSON.stringify(result, null, 2)}`); + await CdkBase.createLogEvent(socket, "TRACE", `Job data query result ${JSON.stringify(result, null, 2)}`); return result.jobs_by_pk; } async function QueryVehicleFromDms(socket) { try { - if (!socket.JobData.v_vin) return null; + const JobData = await getSessionData(socket.id, "JobData"); + + if (!JobData.v_vin) return null; const { data: VehicleGetResponse, request } = await axios.post( PBS_ENDPOINTS.VehicleGet, { - SerialNumber: socket.JobData.bodyshop.pbs_serialnumber, + SerialNumber: JobData.bodyshop.pbs_serialnumber, // VehicleId: "00000000000000000000000000000000", // Year: "String", // Make: "String", @@ -149,7 +181,7 @@ async function QueryVehicleFromDms(socket) { // Trim: "String", // ModelNumber: "String", // StockNumber: "String", - VIN: socket.JobData.v_vin + VIN: JobData.v_vin // LicenseNumber: "String", // Lot: "String", // Status: "String", @@ -166,26 +198,31 @@ async function QueryVehicleFromDms(socket) { { auth: PBS_CREDENTIALS, socket } ); - CheckForErrors(socket, VehicleGetResponse); + await CheckForErrors(socket, VehicleGetResponse); + return VehicleGetResponse; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in QueryVehicleFromDms - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in QueryVehicleFromDms - ${error}`); throw new Error(error); } } async function QueryCustomersFromDms(socket) { try { + // Retrieve JobData from session storage + const JobData = await getSessionData(socket.id, "JobData"); + + // Make an API call to PBS to query customer details const { data: CustomerGetResponse } = await axios.post( PBS_ENDPOINTS.ContactGet, { - SerialNumber: socket.JobData.bodyshop.pbs_serialnumber, + SerialNumber: JobData.bodyshop.pbs_serialnumber, //ContactId: "00000000000000000000000000000000", - // ContactCode: socket.JobData.owner.accountingid, - FirstName: socket.JobData.ownr_fn, - LastName: socket.JobData.ownr_co_nm ? socket.JobData.ownr_co_nm : socket.JobData.ownr_ln, - PhoneNumber: socket.JobData.ownr_ph1, - EmailAddress: socket.JobData.ownr_ea + // ContactCode: JobData.owner.accountingid, + FirstName: JobData.ownr_fn, + LastName: JobData.ownr_co_nm ? JobData.ownr_co_nm : JobData.ownr_ln, + PhoneNumber: JobData.ownr_ph1, + EmailAddress: JobData.ownr_ea // ModifiedSince: "0001-01-01T00:00:00.0000000Z", // ModifiedUntil: "0001-01-01T00:00:00.0000000Z", // ContactIdList: ["00000000000000000000000000000000"], @@ -197,27 +234,36 @@ async function QueryCustomersFromDms(socket) { }, { auth: PBS_CREDENTIALS, socket } ); - CheckForErrors(socket, CustomerGetResponse); + + // Check for errors in the PBS response + await CheckForErrors(socket, CustomerGetResponse); + + // Return the list of contacts from the PBS response return CustomerGetResponse && CustomerGetResponse.Contacts; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in QueryCustomersFromDms - ${error}`); + // Log any errors encountered during the API call + await CdkBase.createLogEvent(socket, "ERROR", `Error in QueryCustomersFromDms - ${error}`); throw new Error(error); } } async function QueryCustomerBycodeFromDms(socket, CustomerRef) { try { + // Retrieve JobData from session storage + const JobData = await getSessionData(socket.id, "JobData"); + + // Make an API call to PBS to query customer by ContactId const { data: CustomerGetResponse } = await axios.post( PBS_ENDPOINTS.ContactGet, { - SerialNumber: socket.JobData.bodyshop.pbs_serialnumber, + SerialNumber: JobData.bodyshop.pbs_serialnumber, ContactId: CustomerRef - //ContactCode: socket.JobData.owner.accountingid, - //FirstName: socket.JobData.ownr_co_nm - // ? socket.JobData.ownr_co_nm - // : socket.JobData.ownr_fn, - //LastName: socket.JobData.ownr_ln, - //PhoneNumber: socket.JobData.ownr_ph1, + //ContactCode: JobData.owner.accountingid, + //FirstName: JobData.ownr_co_nm + // ? JobData.ownr_co_nm + // : JobData.ownr_fn, + //LastName: JobData.ownr_ln, + //PhoneNumber: JobData.ownr_ph1, // EmailAddress: "String", // ModifiedSince: "0001-01-01T00:00:00.0000000Z", // ModifiedUntil: "0001-01-01T00:00:00.0000000Z", @@ -230,33 +276,42 @@ async function QueryCustomerBycodeFromDms(socket, CustomerRef) { }, { auth: PBS_CREDENTIALS, socket } ); - CheckForErrors(socket, CustomerGetResponse); + + // Check for errors in the PBS response + await CheckForErrors(socket, CustomerGetResponse); + + // Return the list of contacts from the PBS response return CustomerGetResponse && CustomerGetResponse.Contacts; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in QueryCustomersFromDms - ${error}`); + // Log any errors encountered during the API call + await CdkBase.createLogEvent(socket, "ERROR", `Error in QueryCustomerBycodeFromDms - ${error}`); throw new Error(error); } } async function UpsertContactData(socket, selectedCustomerId) { try { + // Retrieve JobData from session storage + const JobData = await getSessionData(socket.id, "JobData"); + + // Make an API call to PBS to upsert contact data const { data: ContactChangeResponse } = await axios.post( PBS_ENDPOINTS.ContactChange, { ContactInfo: { - // Id: socket.JobData.owner.id, + // Id: JobData.owner.id, ...(selectedCustomerId ? { ContactId: selectedCustomerId } : {}), - SerialNumber: socket.JobData.bodyshop.pbs_serialnumber, - Code: socket.JobData.owner.accountingid, - ...(socket.JobData.ownr_co_nm + SerialNumber: JobData.bodyshop.pbs_serialnumber, + Code: JobData.owner.accountingid, + ...(JobData.ownr_co_nm ? { - //LastName: socket.JobData.ownr_ln, - FirstName: socket.JobData.ownr_co_nm, + //LastName: JobData.ownr_ln, + FirstName: JobData.ownr_co_nm, IsBusiness: true } : { - LastName: socket.JobData.ownr_ln, - FirstName: socket.JobData.ownr_fn, + LastName: JobData.ownr_ln, + FirstName: JobData.ownr_fn, IsBusiness: false }), @@ -266,20 +321,20 @@ async function UpsertContactData(socket, selectedCustomerId) { IsInactive: false, //ApartmentNumber: "String", - Address: socket.JobData.ownr_addr1, - City: socket.JobData.ownr_city, - //County: socket.JobData.ownr_addr1, - State: socket.JobData.ownr_st, - ZipCode: socket.JobData.ownr_zip, + Address: JobData.ownr_addr1, + City: JobData.ownr_city, + //County: JobData.ownr_addr1, + State: JobData.ownr_st, + ZipCode: JobData.ownr_zip, //BusinessPhone: "String", //BusinessPhoneExt: "String", - HomePhone: socket.JobData.ownr_ph2, - CellPhone: socket.JobData.ownr_ph1, + HomePhone: JobData.ownr_ph2, + CellPhone: JobData.ownr_ph1, //BusinessPhoneRawReverse: "String", //HomePhoneRawReverse: "String", //CellPhoneRawReverse: "String", //FaxNumber: "String", - EmailAddress: socket.JobData.ownr_ea + EmailAddress: JobData.ownr_ea //Notes: "String", //CriticalMemo: "String", //BirthDate: "0001-01-01T00:00:00.0000000Z", @@ -312,39 +367,43 @@ async function UpsertContactData(socket, selectedCustomerId) { }, { auth: PBS_CREDENTIALS, socket } ); - CheckForErrors(socket, ContactChangeResponse); + + await CheckForErrors(socket, ContactChangeResponse); + return ContactChangeResponse; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in UpsertContactData - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in UpsertContactData - ${error}`); throw new Error(error); } } async function UpsertVehicleData(socket, ownerRef) { try { + const JobData = await getSessionData(socket.id, "JobData"); + const { data: VehicleChangeResponse } = await axios.post( PBS_ENDPOINTS.VehicleChange, { VehicleInfo: { //Id: "string/00000000-0000-0000-0000-000000000000", //VehicleId: "00000000000000000000000000000000", - SerialNumber: socket.JobData.bodyshop.pbs_serialnumber, + SerialNumber: JobData.bodyshop.pbs_serialnumber, //StockNumber: "String", - VIN: socket.JobData.v_vin, - LicenseNumber: socket.JobData.plate_no, + VIN: JobData.v_vin, + LicenseNumber: JobData.plate_no, //FleetNumber: "String", //Status: "String", OwnerRef: ownerRef, // "00000000000000000000000000000000", - ModelNumber: socket.JobData.vehicle && socket.JobData.vehicle.v_makecode, - Make: socket.JobData.v_make_desc, - Model: socket.JobData.v_model_desc, - Trim: socket.JobData.vehicle && socket.JobData.vehicle.v_trimcode, + ModelNumber: JobData.vehicle && JobData.vehicle.v_makecode, + Make: JobData.v_make_desc, + Model: JobData.v_model_desc, + Trim: JobData.vehicle && JobData.vehicle.v_trimcode, //VehicleType: "String", - Year: socket.JobData.v_model_yr, - Odometer: socket.JobData.kmout, + Year: JobData.v_model_yr, + Odometer: JobData.kmout, ExteriorColor: { - Code: socket.JobData.v_color, - Description: socket.JobData.v_color + Code: JobData.v_color, + Description: JobData.v_color } // InteriorColor: { Code: "String", Description: "String" }, //Engine: "String", @@ -465,100 +524,113 @@ async function UpsertVehicleData(socket, ownerRef) { }, { auth: PBS_CREDENTIALS, socket } ); - CheckForErrors(socket, VehicleChangeResponse); + + await CheckForErrors(socket, VehicleChangeResponse); + return VehicleChangeResponse; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in UpsertVehicleData - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in UpsertVehicleData - ${error}`); throw new Error(error); } } async function InsertAccountPostingData(socket) { try { - const allocations = await CalculateAllocations(socket, socket.JobData.id); + const JobData = await getSessionData(socket.id, "JobData"); + const txEnvelope = await getSessionData(socket.id, "txEnvelope"); + + const allocations = await CalculateAllocations(socket, JobData.id); const wips = []; + allocations.forEach((alloc) => { - //Add the sale item from each allocation. + // Add the sale item from each allocation if the amount is greater than 0 and not a tax if (alloc.sale.getAmount() > 0 && !alloc.tax) { const item = { Account: alloc.profitCenter.dms_acctnumber, - ControlNumber: socket.JobData.ro_number, + ControlNumber: JobData.ro_number, Amount: alloc.sale.multiply(-1).toFormat("0.00"), - //Comment: "String", - //AdditionalInfo: "String", - InvoiceNumber: socket.JobData.ro_number, - InvoiceDate: moment(socket.JobData.date_invoiced).tz(socket.JobData.bodyshop.timezone).toISOString() + // Comment: "String", + // AdditionalInfo: "String", + InvoiceNumber: JobData.ro_number, + InvoiceDate: moment(JobData.date_invoiced).tz(JobData.bodyshop.timezone).toISOString() }; wips.push(item); } - //Add the cost Item. + // Add the cost item if the cost amount is greater than 0 and not a tax if (alloc.cost.getAmount() > 0 && !alloc.tax) { const item = { Account: alloc.costCenter.dms_acctnumber, - ControlNumber: socket.JobData.ro_number, + ControlNumber: JobData.ro_number, Amount: alloc.cost.toFormat("0.00"), - //Comment: "String", - //AdditionalInfo: "String", - InvoiceNumber: socket.JobData.ro_number, - InvoiceDate: moment(socket.JobData.date_invoiced).tz(socket.JobData.bodyshop.timezone).toISOString() + // Comment: "String", + // AdditionalInfo: "String", + InvoiceNumber: JobData.ro_number, + InvoiceDate: moment(JobData.date_invoiced).tz(JobData.bodyshop.timezone).toISOString() }; + wips.push(item); const itemWip = { Account: alloc.costCenter.dms_wip_acctnumber, - ControlNumber: socket.JobData.ro_number, + ControlNumber: JobData.ro_number, Amount: alloc.cost.multiply(-1).toFormat("0.00"), - //Comment: "String", - //AdditionalInfo: "String", - InvoiceNumber: socket.JobData.ro_number, - InvoiceDate: moment(socket.JobData.date_invoiced).tz(socket.JobData.bodyshop.timezone).toISOString() + // Comment: "String", + // AdditionalInfo: "String", + InvoiceNumber: JobData.ro_number, + InvoiceDate: moment(JobData.date_invoiced).tz(JobData.bodyshop.timezone).toISOString() }; + wips.push(itemWip); - //Add to the WIP account. + // Add to the WIP account. } + // Add tax-related entries if applicable if (alloc.tax) { if (alloc.sale.getAmount() > 0) { const item2 = { Account: alloc.profitCenter.dms_acctnumber, - ControlNumber: socket.JobData.ro_number, + ControlNumber: JobData.ro_number, Amount: alloc.sale.multiply(-1).toFormat("0.00"), - //Comment: "String", - //AdditionalInfo: "String", - InvoiceNumber: socket.JobData.ro_number, - InvoiceDate: moment(socket.JobData.date_invoiced).tz(socket.JobData.bodyshop.timezone).toISOString() + // Comment: "String", + // AdditionalInfo: "String", + InvoiceNumber: JobData.ro_number, + InvoiceDate: moment(JobData.date_invoiced).tz(JobData.bodyshop.timezone).toISOString() }; + wips.push(item2); } } }); - socket.txEnvelope.payers.forEach((payer) => { + + // Add payer information + txEnvelope.payers.forEach((payer) => { const item = { Account: payer.dms_acctnumber, ControlNumber: payer.controlnumber, Amount: Dinero({ amount: Math.round(payer.amount * 100) }).toFormat("0.0"), - //Comment: "String", - //AdditionalInfo: "String", - InvoiceNumber: socket.JobData.ro_number, - InvoiceDate: moment(socket.JobData.date_invoiced).tz(socket.JobData.bodyshop.timezone).toISOString() + // Comment: "String", + // AdditionalInfo: "String", + InvoiceNumber: JobData.ro_number, + InvoiceDate: moment(JobData.date_invoiced).tz(JobData.bodyshop.timezone).toISOString() }; wips.push(item); }); - socket.transWips = wips; + + await setSessionData(socket.id, "transWips", wips); const { data: AccountPostingChange } = await axios.post( PBS_ENDPOINTS.AccountingPostingChange, { - SerialNumber: socket.JobData.bodyshop.pbs_serialnumber, + SerialNumber: JobData.bodyshop.pbs_serialnumber, Posting: { - Reference: socket.JobData.ro_number, - JournalCode: socket.txEnvelope.journal, - TransactionDate: moment(socket.JobData.date_invoiced).tz(socket.JobData.bodyshop.timezone).toISOString(), //"0001-01-01T00:00:00.0000000Z", - Description: socket.txEnvelope.story, - //AdditionalInfo: "String", + Reference: JobData.ro_number, + JournalCode: txEnvelope.journal, + TransactionDate: moment(JobData.date_invoiced).tz(JobData.bodyshop.timezone).toISOString(), // "0001-01-01T00:00:00.0000000Z", + Description: txEnvelope.story, + // AdditionalInfo: "String", Source: InstanceManager({ imex: "ImEX Online", rome: "Rome Online" }), Lines: wips } @@ -566,54 +638,55 @@ async function InsertAccountPostingData(socket) { { auth: PBS_CREDENTIALS, socket } ); - CheckForErrors(socket, AccountPostingChange); + await CheckForErrors(socket, AccountPostingChange); + return AccountPostingChange; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in InsertAccountPostingData - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in InsertAccountPostingData - ${error}`); throw new Error(error); } } async function MarkJobExported(socket, jobid) { - CdkBase.createLogEvent(socket, "DEBUG", `Marking job as exported for id ${jobid}`); + await CdkBase.createLogEvent(socket, "DEBUG", `Marking job as exported for id ${jobid}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); - const result = await client + const JobData = await getSessionData(socket.id, "JobData"); + const transWips = await getSessionData(socket.id, "transWips"); + return await client .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .request(queries.MARK_JOB_EXPORTED, { jobId: jobid, job: { - status: socket.JobData.bodyshop.md_ro_statuses.default_exported || "Exported*", + status: JobData.bodyshop.md_ro_statuses.default_exported || "Exported*", date_exported: new Date() }, log: { - bodyshopid: socket.JobData.bodyshop.id, + bodyshopid: JobData.bodyshop.id, jobid: jobid, successful: true, useremail: socket.user.email, - metadata: socket.transWips + metadata: transWips }, bill: { exported: true, exported_at: new Date() } }); - - return result; } async function InsertFailedExportLog(socket, error) { const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); - const result = await client + const JobData = await getSessionData(socket.id, "JobData"); + + return await client .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .request(queries.INSERT_EXPORT_LOG, { log: { - bodyshopid: socket.JobData.bodyshop.id, - jobid: socket.JobData.id, + bodyshopid: JobData.bodyshop.id, + jobid: JobData.id, successful: false, message: [error], useremail: socket.user.email } }); - - return result; } diff --git a/server/cdk/cdk-calculate-allocations.js b/server/cdk/cdk-calculate-allocations.js index a1dd8cb7f..6a0693309 100644 --- a/server/cdk/cdk-calculate-allocations.js +++ b/server/cdk/cdk-calculate-allocations.js @@ -18,12 +18,12 @@ const { DiscountNotAlreadyCounted } = InstanceManager({ exports.defaultRoute = async function (req, res) { try { - CdkBase.createLogEvent(req, "DEBUG", `Received request to calculate allocations for ${req.body.jobid}`); + await CdkBase.createLogEvent(req, "DEBUG", `Received request to calculate allocations for ${req.body.jobid}`); const jobData = await QueryJobData(req, req.BearerToken, req.body.jobid); - return res.status(200).json({ data: calculateAllocations(req, jobData) }); + return res.status(200).json({ data: await calculateAllocations(req, jobData) }); } catch (error) { console.log(error); - CdkBase.createLogEvent(req, "ERROR", `Error encountered in CdkCalculateAllocations. ${error}`); + await CdkBase.createLogEvent(req, "ERROR", `Error encountered in CdkCalculateAllocations. ${error}`); res.status(500).json({ error: `Error encountered in CdkCalculateAllocations. ${error}` }); } }; @@ -31,22 +31,22 @@ exports.defaultRoute = async function (req, res) { exports.default = async function (socket, jobid) { try { const jobData = await QueryJobData(socket, "Bearer " + socket.handshake.auth.token, jobid); - return calculateAllocations(socket, jobData); + return await calculateAllocations(socket, jobData); } catch (error) { console.log(error); - CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkCalculateAllocations. ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkCalculateAllocations. ${error}`); } }; async function QueryJobData(connectionData, token, jobid) { - CdkBase.createLogEvent(connectionData, "DEBUG", `Querying job data for id ${jobid}`); + await CdkBase.createLogEvent(connectionData, "DEBUG", `Querying job data for id ${jobid}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); const result = await client.setHeaders({ Authorization: token }).request(queries.GET_CDK_ALLOCATIONS, { id: jobid }); - CdkBase.createLogEvent(connectionData, "TRACE", `Job data query result ${JSON.stringify(result, null, 2)}`); + await CdkBase.createLogEvent(connectionData, "TRACE", `Job data query result ${JSON.stringify(result, null, 2)}`); return result.jobs_by_pk; } -function calculateAllocations(connectionData, job) { +async function calculateAllocations(connectionData, job) { const { bodyshop } = job; const taxAllocations = InstanceManager({ @@ -171,7 +171,7 @@ function calculateAllocations(connectionData, job) { const selectedDmsAllocationConfig = bodyshop.md_responsibility_centers.dms_defaults.find( (d) => d.name === job.dms_allocation ); - CdkBase.createLogEvent( + await CdkBase.createLogEvent( connectionData, "DEBUG", `Using DMS Allocation ${selectedDmsAllocationConfig && selectedDmsAllocationConfig.name} for cost export.` @@ -361,9 +361,10 @@ function calculateAllocations(connectionData, job) { } if (InstanceManager({ rome: true })) { //profile level adjustments for parts - Object.keys(job.job_totals.parts.adjustments).forEach((key) => { + for (const key of Object.keys(job.job_totals.parts.adjustments)) { const accountName = selectedDmsAllocationConfig.profits[key]; const otherAccount = bodyshop.md_responsibility_centers.profits.find((c) => c.name === accountName); + if (otherAccount) { if (!profitCenterHash[accountName]) profitCenterHash[accountName] = Dinero(); @@ -371,31 +372,41 @@ function calculateAllocations(connectionData, job) { Dinero(job.job_totals.parts.adjustments[key]) ); } else { - CdkBase.createLogEvent( + // Use await correctly here + await CdkBase.createLogEvent( connectionData, "ERROR", - `Error encountered in CdkCalculateAllocations. Unable to find adjustment account. ${error}` + `Error encountered in CdkCalculateAllocations. Unable to find adjustment account for key ${key}.` ); } - }); + } + //profile level adjustments for labor and materials - Object.keys(job.job_totals.rates).forEach((key) => { - if (job.job_totals.rates[key] && job.job_totals.rates[key].adjustment && Dinero(job.job_totals.rates[key].adjustment).isZero() === false) { + for (const key of Object.keys(job.job_totals.rates)) { + if ( + job.job_totals.rates[key] && + job.job_totals.rates[key].adjustment && + Dinero(job.job_totals.rates[key].adjustment).isZero() === false + ) { const accountName = selectedDmsAllocationConfig.profits[key.toUpperCase()]; const otherAccount = bodyshop.md_responsibility_centers.profits.find((c) => c.name === accountName); + if (otherAccount) { if (!profitCenterHash[accountName]) profitCenterHash[accountName] = Dinero(); - profitCenterHash[accountName] = profitCenterHash[accountName].add(Dinero(job.job_totals.rates[key].adjustments)); + profitCenterHash[accountName] = profitCenterHash[accountName].add( + Dinero(job.job_totals.rates[key].adjustments) + ); } else { - CdkBase.createLogEvent( + // Await the log event creation here + await CdkBase.createLogEvent( connectionData, "ERROR", - `Error encountered in CdkCalculateAllocations. Unable to find adjustment account. ${error}` + `Error encountered in CdkCalculateAllocations. Unable to find adjustment account for key ${key}.` ); } } - }); + } } const jobAllocations = _.union(Object.keys(profitCenterHash), Object.keys(costCenterHash)).map((key) => { diff --git a/server/cdk/cdk-get-makes.js b/server/cdk/cdk-get-makes.js index 06ccc53e2..a7a56d646 100644 --- a/server/cdk/cdk-get-makes.js +++ b/server/cdk/cdk-get-makes.js @@ -86,7 +86,7 @@ async function GetCdkMakes(req, cdk_dealerid) { {} ); - CheckCdkResponseForError(null, soapResponseVehicleSearch); + await CheckCdkResponseForError(null, soapResponseVehicleSearch); const [result, rawResponse, , rawRequest] = soapResponseVehicleSearch; logger.log("cdk-replace-makes-models-request", "ERROR", req.user.email, null, { cdk_dealerid, diff --git a/server/cdk/cdk-job-export.js b/server/cdk/cdk-job-export.js index 3766f836c..592debf4c 100644 --- a/server/cdk/cdk-job-export.js +++ b/server/cdk/cdk-job-export.js @@ -12,146 +12,162 @@ const CalcualteAllocations = require("./cdk-calculate-allocations").default; const InstanceMgr = require("../utils/instanceMgr").default; const moment = require("moment-timezone"); +const { setSessionData, getSessionData } = require("../../server"); const replaceSpecialRegex = /[^a-zA-Z0-9 .,\n #]+/g; exports.default = async function (socket, { txEnvelope, jobid }) { - socket.logEvents = []; - socket.recordid = jobid; - socket.txEnvelope = txEnvelope; + await setSessionData(socket.id, "logEvents", []); + await setSessionData(socket.id, "recordid", jobid); + await setSessionData(socket.id, "txEnvelope", txEnvelope); + try { - CdkBase.createLogEvent(socket, "DEBUG", `Received Job export request for id ${jobid}`); + await CdkBase.createLogEvent(socket, "DEBUG", `Received Job export request for id ${jobid}`); const JobData = await QueryJobData(socket, jobid); - socket.JobData = JobData; + await setSessionData(socket.id, "JobData", JobData); + const DealerId = JobData.bodyshop.cdk_dealerid; - CdkBase.createLogEvent(socket, "DEBUG", `Dealer ID detected: ${JSON.stringify(DealerId)}`); + await CdkBase.createLogEvent(socket, "DEBUG", `Dealer ID detected: ${JSON.stringify(DealerId)}`); - CdkBase.createLogEvent(socket, "DEBUG", `{1} Begin Calculate DMS Vehicle ID using VIN: ${JobData.v_vin}`); - socket.DMSVid = await CalculateDmsVid(socket, JobData); + await CdkBase.createLogEvent(socket, "DEBUG", `{1} Begin Calculate DMS Vehicle ID using VIN: ${JobData.v_vin}`); + const DMSVid = await CalculateDmsVid(socket, JobData); + await setSessionData(socket.id, "DMSVid", DMSVid); - if (socket.DMSVid.newId === "N") { - CdkBase.createLogEvent( + if (DMSVid.newId === "N") { + await CdkBase.createLogEvent( socket, "DEBUG", - `{2.1} Querying the Vehicle using the DMSVid: ${socket.DMSVid.vehiclesVehId}` + `{2.1} Querying the Vehicle using the DMSVid: ${DMSVid.vehiclesVehId}` ); - socket.DMSVeh = await QueryDmsVehicleById(socket, JobData, socket.DMSVid); + const DMSVeh = await QueryDmsVehicleById(socket, JobData, DMSVid); + await setSessionData(socket.id, "DMSVeh", DMSVeh); - const DMSVehCustomer = - socket.DMSVeh && socket.DMSVeh.owners && socket.DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT"); + const DMSVehCustomer = DMSVeh && DMSVeh.owners && DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT"); - if (DMSVehCustomer && DMSVehCustomer.id && DMSVehCustomer.id.value) { - CdkBase.createLogEvent( + if (DMSVehCustomer?.id?.value) { + await CdkBase.createLogEvent( socket, "DEBUG", `{2.2} Querying the Customer using the ID from DMSVeh: ${DMSVehCustomer.id.value}` ); - socket.DMSVehCustomer = await QueryDmsCustomerById(socket, JobData, DMSVehCustomer.id.value); + const DMSVehCustomerData = await QueryDmsCustomerById(socket, JobData, DMSVehCustomer.id.value); + await setSessionData(socket.id, "DMSVehCustomer", DMSVehCustomerData); } } - CdkBase.createLogEvent(socket, "DEBUG", `{2.3} Querying the Customer using the name.`); + await CdkBase.createLogEvent(socket, "DEBUG", `{2.3} Querying the Customer using the name.`); - socket.DMSCustList = await QueryDmsCustomerByName(socket, JobData); + const DMSCustList = await QueryDmsCustomerByName(socket, JobData); + await setSessionData(socket.id, "DMSCustList", DMSCustList); + const DMSVehCustomerData = await getSessionData(socket.id, "DMSVehCustomer"); socket.emit("cdk-select-customer", [ - ...(socket.DMSVehCustomer ? [{ ...socket.DMSVehCustomer, vinOwner: true }] : []), - ...socket.DMSCustList + ...(DMSVehCustomerData ? [{ ...DMSVehCustomerData, vinOwner: true }] : []), + ...DMSCustList ]); } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkJobExport. ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkJobExport. ${error}`); } }; async function CdkSelectedCustomer(socket, selectedCustomerId) { try { - socket.selectedCustomerId = selectedCustomerId; - if (selectedCustomerId) { - CdkBase.createLogEvent(socket, "DEBUG", `{3.1} Querying the Customer using Customer ID: ${selectedCustomerId}`); - socket.DMSCust = await QueryDmsCustomerById(socket, socket.JobData, selectedCustomerId); - } else { - CdkBase.createLogEvent(socket, "DEBUG", `{3.2} Generating a new customer ID.`); - const newCustomerId = await GenerateDmsCustomerNumber(socket); - CdkBase.createLogEvent(socket, "DEBUG", `{3.3} Inserting new customer with ID: ${newCustomerId}`); - socket.DMSCust = await InsertDmsCustomer(socket, newCustomerId); - } + await setSessionData(socket.id, "selectedCustomerId", selectedCustomerId); + const JobData = await getSessionData(socket.id, "JobData"); - if (socket.DMSVid.newId === "Y") { - CdkBase.createLogEvent(socket, "DEBUG", `{4.1} Inserting new vehicle with ID: ID ${socket.DMSVid.vehiclesVehId}`); - socket.DMSVeh = await InsertDmsVehicle(socket); - } else { - CdkBase.createLogEvent( + if (selectedCustomerId) { + await CdkBase.createLogEvent( socket, "DEBUG", - `{4.2} Querying Existing Vehicle using ID ${socket.DMSVid.vehiclesVehId}` + `{3.1} Querying the Customer using Customer ID: ${selectedCustomerId}` ); - socket.DMSVeh = await QueryDmsVehicleById(socket, socket.JobData, socket.DMSVid); - CdkBase.createLogEvent(socket, "DEBUG", `{4.3} Updating Existing Vehicle to associate to owner.`); - socket.DMSVeh = await UpdateDmsVehicle(socket); + const DMSCust = await QueryDmsCustomerById(socket, JobData, selectedCustomerId); + await setSessionData(socket.id, "DMSCust", DMSCust); + } else { + await CdkBase.createLogEvent(socket, "DEBUG", `{3.2} Generating a new customer ID.`); + const newCustomerId = await GenerateDmsCustomerNumber(socket); + await CdkBase.createLogEvent(socket, "DEBUG", `{3.3} Inserting new customer with ID: ${newCustomerId}`); + const DMSCust = await InsertDmsCustomer(socket, newCustomerId); + await setSessionData(socket.id, "DMSCust", DMSCust); } - CdkBase.createLogEvent(socket, "DEBUG", `{5} Creating Transaction header with Dms Start WIP`); - socket.DMSTransHeader = await InsertDmsStartWip(socket); - CdkBase.createLogEvent(socket, "DEBUG", `{5.1} Creating Transaction with ID ${socket.DMSTransHeader.transID}`); + const DMSVid = await getSessionData(socket.id, "DMSVid"); - socket.DMSBatchTxn = await InsertDmsBatchWip(socket); - CdkBase.createLogEvent( + if (DMSVid.newId === "Y") { + await CdkBase.createLogEvent(socket, "DEBUG", `{4.1} Inserting new vehicle with ID: ID ${DMSVid.vehiclesVehId}`); + const DMSVeh = await InsertDmsVehicle(socket); + await setSessionData(socket.id, "DMSVeh", DMSVeh); + } else { + await CdkBase.createLogEvent(socket, "DEBUG", `{4.2} Querying Existing Vehicle using ID ${DMSVid.vehiclesVehId}`); + const DMSVeh = await QueryDmsVehicleById(socket, await getSessionData(socket.id, "JobData"), DMSVid); + await setSessionData(socket.id, "DMSVeh", DMSVeh); + + await CdkBase.createLogEvent(socket, "DEBUG", `{4.3} Updating Existing Vehicle to associate to owner.`); + const updatedDMSVeh = await UpdateDmsVehicle(socket); + await setSessionData(socket.id, "DMSVeh", updatedDMSVeh); + } + + await CdkBase.createLogEvent(socket, "DEBUG", `{5} Creating Transaction header with Dms Start WIP`); + const DMSTransHeader = await InsertDmsStartWip(socket); + await setSessionData(socket.id, "DMSTransHeader", DMSTransHeader); + + await CdkBase.createLogEvent(socket, "DEBUG", `{5.1} Creating Transaction with ID ${DMSTransHeader.transID}`); + const DMSBatchTxn = await InsertDmsBatchWip(socket); + await setSessionData(socket.id, "DMSBatchTxn", DMSBatchTxn); + + await CdkBase.createLogEvent( socket, "DEBUG", - `{6} Attempting to post Transaction with ID ${socket.DMSTransHeader.transID}` + `{6} Attempting to post Transaction with ID ${DMSTransHeader.transID}` ); - socket.DmsBatchTxnPost = await PostDmsBatchWip(socket); - if (socket.DmsBatchTxnPost.code === "success") { - //something - CdkBase.createLogEvent(socket, "DEBUG", `{6} Successfully posted sransaction to DMS.`); + const DmsBatchTxnPost = await PostDmsBatchWip(socket); - await MarkJobExported(socket, socket.JobData.id); + if (DmsBatchTxnPost.code === "success") { + await CdkBase.createLogEvent(socket, "DEBUG", `{6} Successfully posted transaction to DMS.`); + await MarkJobExported(socket, JobData.id); - CdkBase.createLogEvent(socket, "DEBUG", `{5} Updating Service Vehicle History.`); - socket.DMSVehHistory = await InsertServiceVehicleHistory(socket); - socket.emit("export-success", socket.JobData.id); + await CdkBase.createLogEvent(socket, "DEBUG", `{5} Updating Service Vehicle History.`); + const DMSVehHistory = await InsertServiceVehicleHistory(socket); + await setSessionData(socket.id, "DMSVehHistory", DMSVehHistory); + + // TODO: Clear goes here. + socket.emit("export-success", JobData.id); } else { - //Get the error code - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "DEBUG", - `{6.1} Getting errors for Transaction ID ${socket.DMSTransHeader.transID}` + `{6.1} Getting errors for Transaction ID ${DMSTransHeader.transID}` ); - socket.DmsError = await QueryDmsErrWip(socket); - //Delete the transaction - CdkBase.createLogEvent(socket, "DEBUG", `{6.2} Deleting Transaction ID ${socket.DMSTransHeader.transID}`); - socket.DmsBatchTxnPost = await DeleteDmsWip(socket); + const DmsError = await QueryDmsErrWip(socket); + await setSessionData(socket.id, "DmsError", DmsError); - socket.DmsError.errMsg - .split("|") - .map( - (e) => - e !== null && - e !== "" && - CdkBase.createLogEvent(socket, "ERROR", `Error(s) encountered in posting transaction. ${e}`) - ); + await CdkBase.createLogEvent(socket, "DEBUG", `{6.2} Deleting Transaction ID ${DMSTransHeader.transID}`); + await DeleteDmsWip(socket); + + for (const e of DmsError.errMsg.split("|")) { + if (e !== null && e !== "") { + await CdkBase.createLogEvent(socket, "ERROR", `Error(s) encountered in posting transaction. ${e}`); + } + } } } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkSelectedCustomer. ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkSelectedCustomer. ${error}`); await InsertFailedExportLog(socket, error); } finally { - //Ensure we always insert logEvents - //GQL to insert logevents. - - CdkBase.createLogEvent(socket, "DEBUG", `Capturing log events to database.`); + await CdkBase.createLogEvent(socket, "DEBUG", `Capturing log events to database.`); } } exports.CdkSelectedCustomer = CdkSelectedCustomer; async function QueryJobData(socket, jobid) { - CdkBase.createLogEvent(socket, "DEBUG", `Querying job data for id ${jobid}`); + await CdkBase.createLogEvent(socket, "DEBUG", `Querying job data for id ${jobid}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); const result = await client .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .request(queries.QUERY_JOBS_FOR_CDK_EXPORT, { id: jobid }); - CdkBase.createLogEvent(socket, "TRACE", `Job data query result ${JSON.stringify(result, null, 2)}`); + await CdkBase.createLogEvent(socket, "TRACE", `Job data query result ${JSON.stringify(result, null, 2)}`); return result.jobs_by_pk; } @@ -165,16 +181,16 @@ async function CalculateDmsVid(socket, JobData) { }); const [result, rawResponse, , rawRequest] = soapResponseVehicleInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.getVehIdsAsync request.`); + await CdkBase.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.getVehIdsAsync request.`); + await CdkBase.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.getVehIdsAsync response.`); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.getVehIdsAsync response.`); - - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "TRACE", `soapClientVehicleInsertUpdate.getVehIdsAsync Result ${JSON.stringify(result, null, 2)}` ); - CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); + + await CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); //if (result && result.return && result.return.length > 1) { return result.return.find((r) => r.vehiclesVehId); @@ -182,15 +198,15 @@ async function CalculateDmsVid(socket, JobData) { //return result && result.return && result.return[0]; } catch (error) { - CdkBase.createXmlEvent(socket, error.request, `soapClientVehicleInsertUpdate.getVehIdsAsync request.`, true); + await CdkBase.createXmlEvent(socket, error.request, `soapClientVehicleInsertUpdate.getVehIdsAsync request.`, true); - CdkBase.createXmlEvent( + await CdkBase.createXmlEvent( socket, error.response && error.response.data, `soapClientVehicleInsertUpdate.getVehIdsAsync response.`, true ); - CdkBase.createLogEvent(socket, "ERROR", `{1} Error in CalculateDmsVid - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `{1} Error in CalculateDmsVid - ${error}`); throw new Error(error); } } @@ -210,19 +226,21 @@ async function QueryDmsVehicleById(socket, JobData, DMSVid) { const [result, rawResponse, , rawRequest] = soapResponseVehicleInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.readAsync request.`); + await CdkBase.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.readAsync request.`); - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "TRACE", `soapClientVehicleInsertUpdate.readAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.readAsync response.`); - CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); - const VehicleFromDMS = result && result.return && result.return.vehicle; - return VehicleFromDMS; + + await CdkBase.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.readAsync response.`); + + await CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); + + return result && result.return && result.return.vehicle; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in QueryDmsVehicleById - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in QueryDmsVehicleById - ${error}`); throw new Error(error); } } @@ -241,28 +259,30 @@ async function QueryDmsCustomerById(socket, JobData, CustomerId) { const [result, rawResponse, , rawRequest] = soapResponseCustomerInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientCustomerInsertUpdate.readAsync request.`); + await CdkBase.createXmlEvent(socket, rawRequest, `soapClientCustomerInsertUpdate.readAsync request.`); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientCustomerInsertUpdate.readAsync response.`); - CdkBase.createLogEvent( + await CdkBase.createXmlEvent(socket, rawResponse, `soapClientCustomerInsertUpdate.readAsync response.`); + + await CdkBase.createLogEvent( socket, "TRACE", `soapClientCustomerInsertUpdate.readAsync Result ${JSON.stringify(result, null, 2)}` ); - CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate); - const CustomersFromDms = result && result.return && result.return.customerParty; - return CustomersFromDms; - } catch (error) { - CdkBase.createXmlEvent(socket, error.request, `soapClientCustomerInsertUpdate.readAsync request.`, true); - CdkBase.createXmlEvent( + await CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate); + + return result && result.return && result.return.customerParty; + } catch (error) { + await CdkBase.createXmlEvent(socket, error.request, `soapClientCustomerInsertUpdate.readAsync request.`, true); + + await CdkBase.createXmlEvent( socket, error.response && error.response.data, `soapClientCustomerInsertUpdate.readAsync response.`, true ); - CdkBase.createLogEvent(socket, "ERROR", `Error in QueryDmsCustomerById - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in QueryDmsCustomerById - ${error}`); throw new Error(error); } } @@ -274,7 +294,7 @@ async function QueryDmsCustomerByName(socket, JobData) { : `${JobData.ownr_ln},${JobData.ownr_fn}` ).replace(replaceSpecialRegex, ""); - CdkBase.createLogEvent(socket, "DEBUG", `Begin Query DMS Customer by Name using: ${ownerName}`); + await CdkBase.createLogEvent(socket, "DEBUG", `Begin Query DMS Customer by Name using: ${ownerName}`); try { const soapClientCustomerSearch = await soap.createClientAsync(CdkWsdl.CustomerSearch); @@ -289,210 +309,221 @@ async function QueryDmsCustomerByName(socket, JobData) { const [result, rawResponse, , rawRequest] = soapResponseCustomerSearch; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientCustomerSearch.executeSearchBulkAsync request.`); + await CdkBase.createXmlEvent(socket, rawRequest, `soapClientCustomerSearch.executeSearchBulkAsync request.`); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientCustomerSearch.executeSearchBulkAsync response.`); + await CdkBase.createXmlEvent(socket, rawResponse, `soapClientCustomerSearch.executeSearchBulkAsync response.`); - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "TRACE", `soapClientCustomerSearch.executeSearchBulkAsync Result ${JSON.stringify(result, null, 2)}` ); - CheckCdkResponseForError(socket, soapResponseCustomerSearch); - const CustomersFromDms = (result && result.return) || []; - return CustomersFromDms; - } catch (error) { - CdkBase.createXmlEvent(socket, error.request, `soapClientCustomerSearch.executeSearchBulkAsync request.`, true); - CdkBase.createXmlEvent( + await CheckCdkResponseForError(socket, soapResponseCustomerSearch); + + return (result && result.return) || []; + } catch (error) { + await CdkBase.createXmlEvent( + socket, + error.request, + `soapClientCustomerSearch.executeSearchBulkAsync request.`, + true + ); + + await CdkBase.createXmlEvent( socket, error.response && error.response.data, `soapClientCustomerSearch.executeSearchBulkAsync response.`, true ); - CdkBase.createLogEvent(socket, "ERROR", `Error in QueryDmsCustomerByName - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in QueryDmsCustomerByName - ${error}`); throw new Error(error); } } async function GenerateDmsCustomerNumber(socket) { try { + const JobData = await getSessionData(socket.id, "JobData"); + const soapClientCustomerInsertUpdate = await soap.createClientAsync(CdkWsdl.CustomerInsertUpdate); const soapResponseCustomerInsertUpdate = await soapClientCustomerInsertUpdate.getCustomerNumberAsync( { arg0: CDK_CREDENTIALS, - arg1: { dealerId: socket.JobData.bodyshop.cdk_dealerid }, //TODO: Verify why this does not follow the other standards. + arg1: { dealerId: JobData.bodyshop.cdk_dealerid }, // TODO: Verify why this does not follow the other standards. arg2: { userId: null } }, - {} ); const [result, rawResponse, , rawRequest] = soapResponseCustomerInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientCustomerInsertUpdate.getCustomerNumberAsync request.`); + await CdkBase.createXmlEvent(socket, rawRequest, `soapClientCustomerInsertUpdate.getCustomerNumberAsync request.`); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientCustomerInsertUpdate.getCustomerNumberAsync response.`); + await CdkBase.createXmlEvent( + socket, + rawResponse, + `soapClientCustomerInsertUpdate.getCustomerNumberAsync response.` + ); - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "TRACE", `soapClientCustomerInsertUpdate.getCustomerNumberAsync Result ${JSON.stringify(result, null, 2)}` ); - CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate); + await CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate); const customerNumber = result && result.return && result.return.customerNumber; return customerNumber; } catch (error) { - CdkBase.createXmlEvent( + await CdkBase.createXmlEvent( socket, error.request, `soapClientCustomerInsertUpdate.getCustomerNumberAsync request.`, true ); - CdkBase.createXmlEvent( + await CdkBase.createXmlEvent( socket, error.response && error.response.data, `soapClientCustomerInsertUpdate.getCustomerNumberAsync response.`, true ); - CdkBase.createLogEvent(socket, "ERROR", `Error in GenerateDmsCustomerNumber - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in GenerateDmsCustomerNumber - ${error}`); throw new Error(error); } } async function InsertDmsCustomer(socket, newCustomerNumber) { try { + const JobData = await getSessionData(socket.id, "JobData"); const soapClientCustomerInsertUpdate = await soap.createClientAsync(CdkWsdl.CustomerInsertUpdate); const soapResponseCustomerInsertUpdate = await soapClientCustomerInsertUpdate.insertAsync( { arg0: CDK_CREDENTIALS, - arg1: { dealerId: socket.JobData.bodyshop.cdk_dealerid }, + arg1: { dealerId: JobData.bodyshop.cdk_dealerid }, arg2: { userId: null }, arg3: { //Copied the required fields from the other integration. //TODO: Verify whether we need to bring more information in. id: { value: newCustomerNumber }, address: { - addressLine: socket.JobData.ownr_addr1 && socket.JobData.ownr_addr1.replace(replaceSpecialRegex, ""), - city: socket.JobData.ownr_city && socket.JobData.ownr_city.replace(replaceSpecialRegex, ""), - country: socket.JobData.ownr_ctry && socket.JobData.ownr_ctry.replace(replaceSpecialRegex, ""), + addressLine: JobData.ownr_addr1 && JobData.ownr_addr1.replace(replaceSpecialRegex, ""), + city: JobData.ownr_city && JobData.ownr_city.replace(replaceSpecialRegex, ""), + country: JobData.ownr_ctry && JobData.ownr_ctry.replace(replaceSpecialRegex, ""), postalCode: InstanceMgr({ - imex: - socket.JobData.ownr_zip && - socket.JobData.ownr_zip //TODO Need to remove for US Based customers. - .toUpperCase() - .replace(/\W/g, "") - .replace(/(...)/, "$1 "), - rome: socket.JobData.ownr_zip + imex: JobData.ownr_zip && JobData.ownr_zip.toUpperCase().replace(/\W/g, "").replace(/(...)/, "$1 "), + rome: JobData.ownr_zip }), - stateOrProvince: socket.JobData.ownr_st && socket.JobData.ownr_st.replace(replaceSpecialRegex, "") + stateOrProvince: JobData.ownr_st && JobData.ownr_st.replace(replaceSpecialRegex, "") }, contactInfo: { mainTelephoneNumber: { main: true, - value: socket.JobData.ownr_ph1 && socket.JobData.ownr_ph1.replace(replaceSpecialRegex, "") + value: JobData.ownr_ph1 && JobData.ownr_ph1.replace(replaceSpecialRegex, "") }, email: { - desc: socket.JobData.ownr_ea ? "Other" : "CustomerDeclined", - value: socket.JobData.ownr_ea ? socket.JobData.ownr_ea : null + desc: JobData.ownr_ea ? "Other" : "CustomerDeclined", + value: JobData.ownr_ea ? JobData.ownr_ea : null } }, demographics: null, name1: { - companyName: - socket.JobData.ownr_co_nm && socket.JobData.ownr_co_nm.replace(replaceSpecialRegex, "").toUpperCase(), - - firstName: socket.JobData.ownr_fn && socket.JobData.ownr_fn.replace(replaceSpecialRegex, "").toUpperCase(), + companyName: JobData.ownr_co_nm && JobData.ownr_co_nm.replace(replaceSpecialRegex, "").toUpperCase(), + firstName: JobData.ownr_fn && JobData.ownr_fn.replace(replaceSpecialRegex, "").toUpperCase(), fullname: null, - lastName: socket.JobData.ownr_ln && socket.JobData.ownr_ln.replace(replaceSpecialRegex, "").toUpperCase(), + lastName: JobData.ownr_ln && JobData.ownr_ln.replace(replaceSpecialRegex, "").toUpperCase(), middleName: null, - nameType: - socket.JobData.ownr_co_nm && String(socket.JobData.ownr_co_nm).trim() !== "" ? "Business" : "Person", + nameType: JobData.ownr_co_nm && String(JobData.ownr_co_nm).trim() !== "" ? "Business" : "Person", suffix: null, title: null } } }, - {} ); const [result, rawResponse, , rawRequest] = soapResponseCustomerInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientCustomerInsertUpdate.insertAsync request.`); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientCustomerInsertUpdate.insertAsync response.`); - CdkBase.createLogEvent( + await CdkBase.createXmlEvent(socket, rawRequest, `soapClientCustomerInsertUpdate.insertAsync request.`); + + await CdkBase.createXmlEvent(socket, rawResponse, `soapClientCustomerInsertUpdate.insertAsync response.`); + + await CdkBase.createLogEvent( socket, "TRACE", `soapClientCustomerInsertUpdate.insertAsync Result ${JSON.stringify(result, null, 2)}` ); - CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate); + await CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate); const customer = result && result.return && result.return.customerParty; return customer; } catch (error) { - CdkBase.createXmlEvent(socket, error.request, `soapClientCustomerInsertUpdate.insertAsync request.`, true); + await CdkBase.createXmlEvent(socket, error.request, `soapClientCustomerInsertUpdate.insertAsync request.`, true); - CdkBase.createXmlEvent( + await CdkBase.createXmlEvent( socket, error.response && error.response.data, `soapClientCustomerInsertUpdate.insertAsync response.`, true ); - CdkBase.createLogEvent(socket, "ERROR", `Error in InsertDmsCustomer - ${error}`); + + await CdkBase.createLogEvent(socket, "ERROR", `Error in InsertDmsCustomer - ${error}`); throw new Error(error); } } async function InsertDmsVehicle(socket) { try { + const JobData = await getSessionData(socket.id, "JobData"); + const txEnvelope = await getSessionData(socket.id, "txEnvelope"); + const DMSVid = await getSessionData(socket.id, "DMSVid"); + const DMSCust = await getSessionData(socket.id, "DMSCust"); + const soapClientVehicleInsertUpdate = await soap.createClientAsync(CdkWsdl.VehicleInsertUpdate); const soapResponseVehicleInsertUpdate = await soapClientVehicleInsertUpdate.insertAsync({ arg0: CDK_CREDENTIALS, - arg1: { id: socket.JobData.bodyshop.cdk_dealerid }, + arg1: { id: JobData.bodyshop.cdk_dealerid }, arg2: { dealer: { - dealerNumber: socket.JobData.bodyshop.cdk_dealerid, - ...(socket.txEnvelope.inservicedate && { + dealerNumber: JobData.bodyshop.cdk_dealerid, + ...(txEnvelope.inservicedate && { inServiceDate: - socket.txEnvelope.dms_unsold === true + txEnvelope.dms_unsold === true ? "" - : moment(socket.txEnvelope.inservicedate) - //.tz(socket.JobData.bodyshop.timezone) + : moment(txEnvelope.inservicedate) + //.tz(JobData.bodyshop.timezone) .startOf("day") .toISOString() }), - vehicleId: socket.DMSVid.vehiclesVehId + vehicleId: DMSVid.vehiclesVehId }, manufacturer: {}, vehicle: { deliveryDate: - socket.txEnvelope.dms_unsold === true + txEnvelope.dms_unsold === true ? "" : moment() - // .tz(socket.JobData.bodyshop.timezone) + //.tz(JobData.bodyshop.timezone) .format("YYYYMMDD"), licensePlateNo: - socket.JobData.plate_no === null + JobData.plate_no === null ? null - : String(socket.JobData.plate_no).replace(/([^\w]|_)/g, "").length === 0 + : String(JobData.plate_no).replace(/([^\w]|_)/g, "").length === 0 ? null - : String(socket.JobData.plate_no) + : String(JobData.plate_no) .replace(/([^\w]|_)/g, "") .toUpperCase(), - make: socket.txEnvelope.dms_make, - modelAbrev: socket.txEnvelope.dms_model, - modelYear: socket.JobData.v_model_yr, - odometerStatus: socket.txEnvelope.kmout, + make: txEnvelope.dms_make, + modelAbrev: txEnvelope.dms_model, + modelYear: JobData.v_model_yr, + odometerStatus: txEnvelope.kmout, saleClassValue: "MISC", - VIN: socket.JobData.v_vin + VIN: JobData.v_vin }, owners: { id: { assigningPartyId: "CURRENT", - value: socket.DMSCust.id.value + value: DMSCust.id.value } } }, @@ -501,19 +532,21 @@ async function InsertDmsVehicle(socket) { const [result, rawResponse, , rawRequest] = soapResponseVehicleInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.insertAsync request.`); + await CdkBase.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.insertAsync request.`); - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "TRACE", `soapClientVehicleInsertUpdate.insertAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.insertAsync response.`); - CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); - const VehicleFromDMS = result && result.return && result.return.vehicle; - return VehicleFromDMS; + + await CdkBase.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.insertAsync response.`); + + await CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); + + return result && result.return && result.return.vehicle; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in InsertDmsVehicle - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in InsertDmsVehicle - ${error}`); throw new Error(error); } } @@ -521,39 +554,37 @@ async function InsertDmsVehicle(socket) { async function UpdateDmsVehicle(socket) { try { const soapClientVehicleInsertUpdate = await soap.createClientAsync(CdkWsdl.VehicleInsertUpdate); + const JobData = await getSessionData(socket.id, "JobData"); + const DMSVeh = await getSessionData(socket.id, "DMSVeh"); + const DMSCust = await getSessionData(socket.id, "DMSCust"); + const selectedCustomerId = await getSessionData(socket.id, "selectedCustomerId"); + const txEnvelope = await getSessionData(socket.id, "txEnvelope"); let ids = []; - //if it's a generic customer, don't update the vehicle owners. - - if (socket.selectedCustomerId === socket.JobData.bodyshop.cdk_configuration.generic_customer_number) { - ids = socket.DMSVeh && socket.DMSVeh.owners && socket.DMSVeh.owners; + // If it's a generic customer, don't update the vehicle owners. + if (selectedCustomerId === JobData.bodyshop.cdk_configuration.generic_customer_number) { + ids = DMSVeh && DMSVeh.owners; } else { - const existingOwnerinVeh = - socket.DMSVeh && - socket.DMSVeh.owners && - socket.DMSVeh.owners.find((o) => o.id.value === socket.DMSCust.id.value); + const existingOwnerinVeh = DMSVeh && DMSVeh.owners && DMSVeh.owners.find((o) => o.id.value === DMSCust.id.value); if (existingOwnerinVeh) { - ids = socket.DMSVeh.owners.map((o) => { + ids = DMSVeh.owners.map((o) => { return { id: { - assigningPartyId: o.id.value === socket.DMSCust.id.value ? "CURRENT" : "PREVIOUS", + assigningPartyId: o.id.value === DMSCust.id.value ? "CURRENT" : "PREVIOUS", value: o.id.value } }; }); } else { - const oldOwner = - socket.DMSVeh && - socket.DMSVeh.owners && - socket.DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT"); + const oldOwner = DMSVeh && DMSVeh.owners && DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT"); ids = [ { id: { assigningPartyId: "CURRENT", - value: socket.DMSCust.id.value + value: DMSCust.id.value } }, ...(oldOwner @@ -572,144 +603,168 @@ async function UpdateDmsVehicle(socket) { const soapResponseVehicleInsertUpdate = await soapClientVehicleInsertUpdate.updateAsync({ arg0: CDK_CREDENTIALS, - arg1: { id: socket.JobData.bodyshop.cdk_dealerid }, + arg1: { id: JobData.bodyshop.cdk_dealerid }, arg2: { - ...socket.DMSVeh, + ...DMSVeh, dealer: { - ...socket.DMSVeh.dealer, - ...((socket.txEnvelope.inservicedate || socket.DMSVeh.dealer.inServiceDate) && { + ...DMSVeh.dealer, + ...((txEnvelope.inservicedate || DMSVeh.dealer.inServiceDate) && { inServiceDate: - socket.txEnvelope.dms_unsold === true + txEnvelope.dms_unsold === true ? "" - : moment(socket.DMSVeh.dealer.inServiceDate || socket.txEnvelope.inservicedate) - // .tz(socket.JobData.bodyshop.timezone) + : moment(DMSVeh.dealer.inServiceDate || txEnvelope.inservicedate) + // .tz(JobData.bodyshop.timezone) .toISOString() }) }, vehicle: { - ...socket.DMSVeh.vehicle, - ...(socket.txEnvelope.dms_model_override + ...DMSVeh.vehicle, + ...(txEnvelope.dms_model_override ? { - make: socket.txEnvelope.dms_make, - modelAbrev: socket.txEnvelope.dms_model + make: txEnvelope.dms_make, + modelAbrev: txEnvelope.dms_model } : {}), deliveryDate: - socket.txEnvelope.dms_unsold === true + txEnvelope.dms_unsold === true ? "" - : moment(socket.DMSVeh.vehicle.deliveryDate) - //.tz(socket.JobData.bodyshop.timezone) + : moment(DMSVeh.vehicle.deliveryDate) + // .tz(JobData.bodyshop.timezone) .toISOString() }, owners: ids }, arg3: "VEHICLES" }); + const [result, rawResponse, , rawRequest] = soapResponseVehicleInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.updateAsync request.`); + await CdkBase.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.updateAsync request.`); - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "TRACE", `soapClientVehicleInsertUpdate.updateAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.updateAsync response.`); - CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); - const VehicleFromDMS = result && result.return && result.return.vehicle; - return VehicleFromDMS; + + await CdkBase.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.updateAsync response.`); + + await CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); + + return result && result.return && result.return.vehicle; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in UpdateDmsVehicle - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in UpdateDmsVehicle - ${error}`); throw new Error(error); } } async function InsertServiceVehicleHistory(socket) { try { + const JobData = await getSessionData(socket.id, "JobData"); + const DMSVid = await getSessionData(socket.id, "DMSVid"); + const txEnvelope = await getSessionData(socket.id, "txEnvelope"); + const soapClientServiceHistoryInsert = await soap.createClientAsync(CdkWsdl.ServiceHistoryInsert); const soapResponseServiceHistoryInsert = await soapClientServiceHistoryInsert.serviceHistoryHeaderInsertAsync({ authToken: CDK_CREDENTIALS, - dealerId: { dealerId: socket.JobData.bodyshop.cdk_dealerid }, + dealerId: { dealerId: JobData.bodyshop.cdk_dealerid }, serviceHistoryHeader: { - vehID: socket.DMSVid.vehiclesVehId, - roNumber: socket.JobData.ro_number.match(/\d+/g), - mileage: socket.txEnvelope.kmout, - openDate: moment(socket.JobData.actual_in).tz(socket.JobData.bodyshop.timezone).format("YYYY-MM-DD"), - openTime: moment(socket.JobData.actual_in).tz(socket.JobData.bodyshop.timezone).format("HH:mm:ss"), - closeDate: moment(socket.JobData.invoice_date).tz(socket.JobData.bodyshop.timezone).format("YYYY-MM-DD"), - closeTime: moment(socket.JobData.invoice_date).tz(socket.JobData.bodyshop.timezone).format("HH:mm:ss"), - comments: socket.txEnvelope.story, - cashierID: socket.JobData.bodyshop.cdk_configuration.cashierid + vehID: DMSVid.vehiclesVehId, + roNumber: JobData.ro_number.match(/\d+/g), + mileage: txEnvelope.kmout, + openDate: moment(JobData.actual_in).tz(JobData.bodyshop.timezone).format("YYYY-MM-DD"), + openTime: moment(JobData.actual_in).tz(JobData.bodyshop.timezone).format("HH:mm:ss"), + closeDate: moment(JobData.invoice_date).tz(JobData.bodyshop.timezone).format("YYYY-MM-DD"), + closeTime: moment(JobData.invoice_date).tz(JobData.bodyshop.timezone).format("HH:mm:ss"), + comments: txEnvelope.story, + cashierID: JobData.bodyshop.cdk_configuration.cashierid } }); const [result, rawResponse, , rawRequest] = soapResponseServiceHistoryInsert; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientServiceHistoryInsert.serviceHistoryHeaderInsert request.`); + await CdkBase.createXmlEvent( + socket, + rawRequest, + `soapClientServiceHistoryInsert.serviceHistoryHeaderInsert request.` + ); - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "TRACE", `soapClientServiceHistoryInsert.serviceHistoryHeaderInsert Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientServiceHistoryInsert.serviceHistoryHeaderInsert response.`); - CheckCdkResponseForError(socket, soapResponseServiceHistoryInsert); + + await CdkBase.createXmlEvent( + socket, + rawResponse, + `soapClientServiceHistoryInsert.serviceHistoryHeaderInsert response.` + ); + + await CheckCdkResponseForError(socket, soapResponseServiceHistoryInsert); + return result && result.return; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in InsertServiceVehicleHistory - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in InsertServiceVehicleHistory - ${error}`); throw new Error(error); } } async function InsertDmsStartWip(socket) { try { + const JobData = await getSessionData(socket.id, "JobData"); + const txEnvelope = await getSessionData(socket.id, "txEnvelope"); + const soapClientAccountingGLInsertUpdate = await soap.createClientAsync(CdkWsdl.AccountingGLInsertUpdate); const soapResponseAccountingGLInsertUpdate = await soapClientAccountingGLInsertUpdate.doStartWIPAsync({ arg0: CDK_CREDENTIALS, - arg1: { dealerId: socket.JobData.bodyshop.cdk_dealerid }, + arg1: { dealerId: JobData.bodyshop.cdk_dealerid }, arg2: { - acctgDate: moment().tz(socket.JobData.bodyshop.timezone).format("YYYY-MM-DD"), - //socket.JobData.invoice_date - desc: socket.txEnvelope.story && socket.txEnvelope.story.replace(replaceSpecialRegex, ""), - docType: 10 || 7, //Need to check what this usually would be? Apparently it is almost always 10 or 7. - //1 Cash Receipt , 2 Check, 3 Journal Voucher, 4 Parts invoice, 5 Payable Invoice, 6 Recurring Entry, 7 Repair Order Invoice, 8 Vehicle Purchase Invoice, 9 Vehicle Sale Invoice, 10 Other, 11 Payroll, 12 Finance Charge, 13 FMLR Invoice, 14 Parts Credit Memo, 15 Manufacturer Document, 16 FMLR Credit Memo + acctgDate: moment().tz(JobData.bodyshop.timezone).format("YYYY-MM-DD"), + desc: txEnvelope.story && txEnvelope.story.replace(replaceSpecialRegex, ""), + docType: 10 || 7, // Need to check what this usually would be? Apparently it is almost always 10 or 7. + // 1 Cash Receipt , 2 Check, 3 Journal Voucher, 4 Parts invoice, 5 Payable Invoice, 6 Recurring Entry, + // 7 Repair Order Invoice, 8 Vehicle Purchase Invoice, 9 Vehicle Sale Invoice, 10 Other, + // 11 Payroll, 12 Finance Charge, 13 FMLR Invoice, 14 Parts Credit Memo, 15 Manufacturer Document, + // 16 FMLR Credit Memo m13Flag: 0, - refer: socket.JobData.ro_number, - srcCo: socket.JobData.bodyshop.cdk_configuration.srcco, - srcJrnl: socket.txEnvelope.journal, - userID: socket.JobData.bodyshop.cdk_configuration.cashierid //Where is this coming from? - //userName: "IMEX", + refer: JobData.ro_number, + srcCo: JobData.bodyshop.cdk_configuration.srcco, + srcJrnl: txEnvelope.journal, + userID: JobData.bodyshop.cdk_configuration.cashierid // Where is this coming from? + // userName: "IMEX", } }); const [result, rawResponse, , rawRequest] = soapResponseAccountingGLInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doStartWIPAsync request.`); + await CdkBase.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doStartWIPAsync request.`); - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "TRACE", `soapClientAccountingGLInsertUpdate.doStartWIPAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doStartWIPAsync response.`); - CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); - const TransactionHeader = result && result.return; - return TransactionHeader; + await CdkBase.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doStartWIPAsync response.`); + await CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); + return result && result.return; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in InsertDmsStartWip - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in InsertDmsStartWip - ${error}`); throw new Error(error); } } async function InsertDmsBatchWip(socket) { try { + const JobData = await getSessionData(socket.id, "JobData"); + const soapClientAccountingGLInsertUpdate = await soap.createClientAsync(CdkWsdl.AccountingGLInsertUpdate); const soapResponseAccountingGLInsertUpdate = await soapClientAccountingGLInsertUpdate.doTransBatchWIPAsync({ arg0: CDK_CREDENTIALS, - arg1: { dealerId: socket.JobData.bodyshop.cdk_dealerid }, + arg1: { dealerId: JobData.bodyshop.cdk_dealerid }, arg2: { transWIPs: await GenerateTransWips(socket) } @@ -717,28 +772,42 @@ async function InsertDmsBatchWip(socket) { const [result, rawResponse, , rawRequest] = soapResponseAccountingGLInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doTransBatchWIPAsync request.`); + await CdkBase.createXmlEvent( + socket, + rawRequest, + `soapClientAccountingGLInsertUpdate.doTransBatchWIPAsync request.` + ); - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "TRACE", `soapClientAccountingGLInsertUpdate.doTransBatchWIPAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doTransBatchWIPAsync response.`); - CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); - const BatchWipResult = result && result.return; - return BatchWipResult; + + await CdkBase.createXmlEvent( + socket, + rawResponse, + `soapClientAccountingGLInsertUpdate.doTransBatchWIPAsync response.` + ); + await CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); + + return result && result.return; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in InsertDmsBatchWip - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in InsertDmsBatchWip - ${error}`); throw new Error(error); } } async function GenerateTransWips(socket) { - const allocations = await CalcualteAllocations(socket, socket.JobData.id); + const JobData = await getSessionData(socket.id, "JobData"); + const DMSTransHeader = await getSessionData(socket.id, "DMSTransHeader"); + const txEnvelope = await getSessionData(socket.id, "txEnvelope"); + + const allocations = await CalcualteAllocations(socket, JobData.id); const wips = []; + allocations.forEach((alloc) => { - //Add the sale item from each allocation. + // Add the sale item from each allocation. if (alloc.sale.getAmount() > 0 && !alloc.tax) { const item = { acct: alloc.profitCenter.dms_acctnumber, @@ -748,20 +817,20 @@ async function GenerateTransWips(socket) { alloc.profitCenter.dms_control_override !== undefined && alloc.profitCenter.dms_control_override?.trim() !== "" ? alloc.profitCenter.dms_control_override - : socket.JobData.ro_number, + : JobData.ro_number, cntl2: null, credtMemoNo: null, postAmt: alloc.sale.multiply(-1).getAmount(), postDesc: null, prod: null, statCnt: 1, - transID: socket.DMSTransHeader.transID, - trgtCoID: socket.JobData.bodyshop.cdk_configuration.srcco + transID: DMSTransHeader.transID, + trgtCoID: JobData.bodyshop.cdk_configuration.srcco }; wips.push(item); } - //Add the cost Item. + // Add the cost item. if (alloc.cost.getAmount() > 0 && !alloc.tax) { const item = { acct: alloc.costCenter.dms_acctnumber, @@ -771,15 +840,15 @@ async function GenerateTransWips(socket) { alloc.costCenter.dms_control_override !== undefined && alloc.costCenter.dms_control_override?.trim() !== "" ? alloc.costCenter.dms_control_override - : socket.JobData.ro_number, + : JobData.ro_number, cntl2: null, credtMemoNo: null, postAmt: alloc.cost.getAmount(), postDesc: null, prod: null, statCnt: 1, - transID: socket.DMSTransHeader.transID, - trgtCoID: socket.JobData.bodyshop.cdk_configuration.srcco + transID: DMSTransHeader.transID, + trgtCoID: JobData.bodyshop.cdk_configuration.srcco }; wips.push(item); @@ -791,63 +860,45 @@ async function GenerateTransWips(socket) { alloc.costCenter.dms_control_override !== undefined && alloc.costCenter.dms_control_override?.trim() !== "" ? alloc.costCenter.dms_control_override - : socket.JobData.ro_number, + : JobData.ro_number, cntl2: null, credtMemoNo: null, postAmt: alloc.cost.multiply(-1).getAmount(), postDesc: null, prod: null, statCnt: 1, - transID: socket.DMSTransHeader.transID, - trgtCoID: socket.JobData.bodyshop.cdk_configuration.srcco + transID: DMSTransHeader.transID, + trgtCoID: JobData.bodyshop.cdk_configuration.srcco }; wips.push(itemWip); - //Add to the WIP account. } - if (alloc.tax) { - // if (alloc.cost.getAmount() > 0) { - // const item = { - // acct: alloc.costCenter.dms_acctnumber, - // cntl: socket.JobData.ro_number, - // cntl2: null, - // credtMemoNo: null, - // postAmt: alloc.cost.getAmount(), - // postDesc: null, - // prod: null, - // statCnt: 1, - // transID: socket.DMSTransHeader.transID, - // trgtCoID: socket.JobData.bodyshop.cdk_configuration.srcco, - // }; - - // wips.push(item); - // } - - if (alloc.sale.getAmount() > 0) { - const item2 = { - acct: alloc.profitCenter.dms_acctnumber, - cntl: - alloc.profitCenter.dms_control_override && - alloc.profitCenter.dms_control_override !== null && - alloc.profitCenter.dms_control_override !== undefined && - alloc.profitCenter.dms_control_override?.trim() !== "" - ? alloc.profitCenter.dms_control_override - : socket.JobData.ro_number, - cntl2: null, - credtMemoNo: null, - postAmt: alloc.sale.multiply(-1).getAmount(), - postDesc: null, - prod: null, - statCnt: 1, - transID: socket.DMSTransHeader.transID, - trgtCoID: socket.JobData.bodyshop.cdk_configuration.srcco - }; - wips.push(item2); - } + // Handle tax allocations + if (alloc.tax && alloc.sale.getAmount() > 0) { + const item2 = { + acct: alloc.profitCenter.dms_acctnumber, + cntl: + alloc.profitCenter.dms_control_override && + alloc.profitCenter.dms_control_override !== null && + alloc.profitCenter.dms_control_override !== undefined && + alloc.profitCenter.dms_control_override?.trim() !== "" + ? alloc.profitCenter.dms_control_override + : JobData.ro_number, + cntl2: null, + credtMemoNo: null, + postAmt: alloc.sale.multiply(-1).getAmount(), + postDesc: null, + prod: null, + statCnt: 1, + transID: DMSTransHeader.transID, + trgtCoID: JobData.bodyshop.cdk_configuration.srcco + }; + wips.push(item2); } }); - socket.txEnvelope.payers.forEach((payer) => { + // Add payers to the WIP + txEnvelope.payers.forEach((payer) => { const item = { acct: payer.dms_acctnumber, cntl: payer.controlnumber, @@ -857,147 +908,171 @@ async function GenerateTransWips(socket) { postDesc: null, prod: null, statCnt: 1, - transID: socket.DMSTransHeader.transID, - trgtCoID: socket.JobData.bodyshop.cdk_configuration.srcco + transID: DMSTransHeader.transID, + trgtCoID: JobData.bodyshop.cdk_configuration.srcco }; wips.push(item); }); - socket.transWips = wips; + + await setSessionData(socket.id, "transWips", wips); return wips; } async function PostDmsBatchWip(socket) { try { + const JobData = await getSessionData(socket.id, "JobData"); + const DMSTransHeader = await getSessionData(socket.id, "DMSTransHeader"); + const soapClientAccountingGLInsertUpdate = await soap.createClientAsync(CdkWsdl.AccountingGLInsertUpdate); const soapResponseAccountingGLInsertUpdate = await soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync({ arg0: CDK_CREDENTIALS, - arg1: { dealerId: socket.JobData.bodyshop.cdk_dealerid }, + arg1: { dealerId: JobData.bodyshop.cdk_dealerid }, arg2: { - postWIP: { opCode: "P", transID: socket.DMSTransHeader.transID } + postWIP: { opCode: "P", transID: DMSTransHeader.transID } } }); const [result, rawResponse, , rawRequest] = soapResponseAccountingGLInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync request.`); + await CdkBase.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync request.`); - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "TRACE", `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync response.`); - // CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); - const PostResult = result && result.return; - return PostResult; + + await CdkBase.createXmlEvent( + socket, + rawResponse, + `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync response.` + ); + + return result && result.return; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in PostDmsBatchWip - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in PostDmsBatchWip - ${error}`); throw new Error(error); } } async function QueryDmsErrWip(socket) { try { + const JobData = await getSessionData(socket.id, "JobData"); + const DMSTransHeader = await getSessionData(socket.id, "DMSTransHeader"); + const soapClientAccountingGLInsertUpdate = await soap.createClientAsync(CdkWsdl.AccountingGLInsertUpdate); const soapResponseAccountingGLInsertUpdate = await soapClientAccountingGLInsertUpdate.doErrWIPAsync({ arg0: CDK_CREDENTIALS, - arg1: { dealerId: socket.JobData.bodyshop.cdk_dealerid }, - arg2: socket.DMSTransHeader.transID + arg1: { dealerId: JobData.bodyshop.cdk_dealerid }, + arg2: DMSTransHeader.transID }); const [result, rawResponse, , rawRequest] = soapResponseAccountingGLInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doErrWIPAsync request.`); + await CdkBase.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doErrWIPAsync request.`); - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "TRACE", `soapClientAccountingGLInsertUpdate.doErrWIPAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doErrWIPAsync response.`); - CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); - const PostResult = result && result.return; - return PostResult; + + await CdkBase.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doErrWIPAsync response.`); + + await CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); + + return result && result.return; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in QueryDmsErrWip - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in QueryDmsErrWip - ${error}`); throw new Error(error); } } async function DeleteDmsWip(socket) { try { + const JobData = await getSessionData(socket.id, "JobData"); + const DMSTransHeader = await getSessionData(socket.id, "DMSTransHeader"); + const soapClientAccountingGLInsertUpdate = await soap.createClientAsync(CdkWsdl.AccountingGLInsertUpdate); const soapResponseAccountingGLInsertUpdate = await soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync({ arg0: CDK_CREDENTIALS, - arg1: { dealerId: socket.JobData.bodyshop.cdk_dealerid }, + arg1: { dealerId: JobData.bodyshop.cdk_dealerid }, arg2: { - postWIP: { opCode: "D", transID: socket.DMSTransHeader.transID } + postWIP: { opCode: "D", transID: DMSTransHeader.transID } } }); const [result, rawResponse, , rawRequest] = soapResponseAccountingGLInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync request.`); + await CdkBase.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync request.`); - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "TRACE", `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync response.`); - CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); - const PostResult = result && result.return; - return PostResult; + + await CdkBase.createXmlEvent( + socket, + rawResponse, + `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync response.` + ); + await CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); + return result && result.return; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in PostDmsBatchWip - ${error}`); + await CdkBase.createLogEvent(socket, "ERROR", `Error in PostDmsBatchWip - ${error}`); throw new Error(error); } } async function MarkJobExported(socket, jobid) { - CdkBase.createLogEvent(socket, "DEBUG", `Marking job as exported for id ${jobid}`); + await CdkBase.createLogEvent(socket, "DEBUG", `Marking job as exported for id ${jobid}`); + + const JobData = await getSessionData(socket.id, "JobData"); + const transWips = (await getSessionData(socket.id, "transWips")) || []; + const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); - const result = await client + + return await client .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .request(queries.MARK_JOB_EXPORTED, { jobId: jobid, job: { - status: socket.JobData.bodyshop.md_ro_statuses.default_exported || "Exported*", + status: JobData.bodyshop.md_ro_statuses.default_exported || "Exported*", date_exported: new Date() }, log: { - bodyshopid: socket.JobData.bodyshop.id, + bodyshopid: JobData.bodyshop.id, jobid: jobid, successful: true, useremail: socket.user.email, - metadata: socket.transWips + metadata: transWips }, bill: { exported: true, exported_at: new Date() } }); - - return result; } async function InsertFailedExportLog(socket, error) { + const JobData = await getSessionData(socket.id, "JobData"); + const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); - const result = await client + + return await client .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .request(queries.INSERT_EXPORT_LOG, { log: { - bodyshopid: socket.JobData.bodyshop.id, - jobid: socket.JobData.id, + bodyshopid: JobData.bodyshop.id, + jobid: JobData.id, successful: false, message: [error], useremail: socket.user.email } }); - - return result; } diff --git a/server/cdk/cdk-wsdl.js b/server/cdk/cdk-wsdl.js index 032d780c2..d2e07ea85 100644 --- a/server/cdk/cdk-wsdl.js +++ b/server/cdk/cdk-wsdl.js @@ -15,10 +15,10 @@ exports.CDK_CREDENTIALS = CDK_CREDENTIALS; const cdkDomain = process.env.NODE_ENV === "production" ? "https://3pa.dmotorworks.com" : "https://uat-3pa.dmotorworks.com"; -function CheckCdkResponseForError(socket, soapResponse) { +async function CheckCdkResponseForError(socket, soapResponse) { if (!soapResponse[0]) { //The response was null, this might be ok, it might not. - CdkBase.createLogEvent( + await CdkBase.createLogEvent( socket, "WARNING", `Warning detected in CDK Response - it appears to be null. Stack: ${new Error().stack}` @@ -31,23 +31,22 @@ function CheckCdkResponseForError(socket, soapResponse) { if (Array.isArray(ResultToCheck)) { ResultToCheck.forEach((result) => checkIndividualResult(socket, result)); } else { - checkIndividualResult(socket, ResultToCheck); + await checkIndividualResult(socket, ResultToCheck); } } exports.CheckCdkResponseForError = CheckCdkResponseForError; -function checkIndividualResult(socket, ResultToCheck) { +async function checkIndividualResult(socket, ResultToCheck) { if ( ResultToCheck.errorLevel === 0 || ResultToCheck.errorLevel === "0" || ResultToCheck.code === "success" || (!ResultToCheck.code && !ResultToCheck.errorLevel) - ) + ) { //TODO: Verify that this is the best way to detect errors. - return; - else { - CdkBase.createLogEvent( + } else { + await CdkBase.createLogEvent( socket, "ERROR", `Error detected in CDK Response - ${JSON.stringify(ResultToCheck, null, 2)}` diff --git a/server/web-sockets/web-socket.js b/server/web-sockets/web-socket.js index c27e96374..c2dd7c073 100644 --- a/server/web-sockets/web-socket.js +++ b/server/web-sockets/web-socket.js @@ -3,9 +3,8 @@ require("dotenv").config({ path: path.resolve(process.cwd(), `.env.${process.env.NODE_ENV || "development"}`) }); -const { io } = require("../../server"); +const { io, setSessionData, clearSessionData, getSessionData } = require("../../server"); const { admin } = require("../firebase/firebase-handler"); -const { isArray } = require("lodash"); const logger = require("../utils/logger"); const { default: CdkJobExport, CdkSelectedCustomer } = require("../cdk/cdk-job-export"); const CdkGetMakes = require("../cdk/cdk-get-makes").default; @@ -32,9 +31,9 @@ function socketAuthMiddleware(socket, next) { } // Register all socket events for a given socket connection -function registerSocketEvents(socket) { - socket.log_level = "TRACE"; - createLogEvent(socket, "DEBUG", `Connected and Authenticated.`); +async function registerSocketEvents(socket) { + await setSessionData(socket.id, "log_level", "TRACE"); + await createLogEvent(socket, "DEBUG", `Connected and Authenticated.`); // Register CDK-related socket events registerCdkEvents(socket); @@ -48,18 +47,24 @@ function registerSocketEvents(socket) { // Register room and broadcasting events registerRoomAndBroadcastEvents(socket); + // Register event to clear DMS session + registerDmsClearSessionEvent(socket); + // Handle socket disconnection - socket.on("disconnect", () => { - createLogEvent(socket, "DEBUG", `User disconnected.`); + socket.on("disconnect", async () => { + await createLogEvent(socket, "DEBUG", `User disconnected.`); }); } // CDK-specific socket events function registerCdkEvents(socket) { socket.on("cdk-export-job", (jobid) => CdkJobExport(socket, jobid)); - socket.on("cdk-selected-customer", (selectedCustomerId) => { - createLogEvent(socket, "DEBUG", `User selected customer ID ${selectedCustomerId}`); - CdkSelectedCustomer(socket, selectedCustomerId); + socket.on("cdk-selected-customer", async (selectedCustomerId) => { + await createLogEvent(socket, "DEBUG", `User selected customer ID ${selectedCustomerId}`); + CdkSelectedCustomer(socket, selectedCustomerId).catch((err) => + console.error(`Error in cdk-selected-customer: ${err}`) + ); + await setSessionData(socket.id, "selectedCustomer", selectedCustomerId); }); socket.on("cdk-get-makes", async (cdk_dealerid, callback) => { @@ -67,15 +72,16 @@ function registerCdkEvents(socket) { const makes = await CdkGetMakes(socket, cdk_dealerid); callback(makes); } catch (error) { - createLogEvent(socket, "ERROR", `Error in cdk-get-makes WS call. ${JSON.stringify(error)}`); + await createLogEvent(socket, "ERROR", `Error in cdk-get-makes WS call. ${JSON.stringify(error)}`); } }); socket.on("cdk-calculate-allocations", async (jobid, callback) => { const allocations = await CdkCalculateAllocations(socket, jobid); - createLogEvent(socket, "DEBUG", `Allocations calculated.`); - createLogEvent(socket, "TRACE", `Allocations details: ${JSON.stringify(allocations)}`); + await createLogEvent(socket, "DEBUG", `Allocations calculated.`); + await createLogEvent(socket, "TRACE", `Allocations details: ${JSON.stringify(allocations)}`); callback(allocations); + await setSessionData(socket.id, "cdk_allocations", allocations); }); } @@ -83,15 +89,19 @@ function registerCdkEvents(socket) { function registerPbsArEvents(socket) { socket.on("pbs-calculate-allocations", async (jobid, callback) => { const allocations = await CdkCalculateAllocations(socket, jobid); - createLogEvent(socket, "DEBUG", `PBS AR allocations calculated.`); - createLogEvent(socket, "TRACE", `Allocations details: ${JSON.stringify(allocations)}`); + await createLogEvent(socket, "DEBUG", `PBS AR allocations calculated.`); + await createLogEvent(socket, "TRACE", `Allocations details: ${JSON.stringify(allocations)}`); callback(allocations); + await setSessionData(socket.id, "pbs_allocations", allocations); }); socket.on("pbs-export-job", (jobid) => PbsExportJob(socket, jobid)); - socket.on("pbs-selected-customer", (selectedCustomerId) => { - createLogEvent(socket, "DEBUG", `PBS AR selected customer ID ${selectedCustomerId}`); - PbsSelectedCustomer(socket, selectedCustomerId); + socket.on("pbs-selected-customer", async (selectedCustomerId) => { + await createLogEvent(socket, "DEBUG", `PBS AR selected customer ID ${selectedCustomerId}`); + PbsSelectedCustomer(socket, selectedCustomerId).catch((err) => + console.error(`Error in pbs-selected-customer: ${err}`) + ); + await setSessionData(socket.id, "selectedCustomer", selectedCustomerId); }); } @@ -99,62 +109,92 @@ function registerPbsArEvents(socket) { function registerPbsApEvents(socket) { socket.on("pbs-calculate-allocations-ap", async (billids, callback) => { const allocations = await PbsCalculateAllocationsAp(socket, billids); - createLogEvent(socket, "DEBUG", `PBS AP allocations calculated.`); - createLogEvent(socket, "TRACE", `Allocations details: ${JSON.stringify(allocations)}`); - socket.apAllocations = allocations; + await createLogEvent(socket, "DEBUG", `PBS AP allocations calculated.`); + await createLogEvent(socket, "TRACE", `Allocations details: ${JSON.stringify(allocations)}`); callback(allocations); + await setSessionData(socket.id, "pbs_ap_allocations", allocations); }); - socket.on("pbs-export-ap", ({ billids, txEnvelope }) => { - socket.txEnvelope = txEnvelope; - PbsExportAp(socket, { billids, txEnvelope }); + socket.on("pbs-export-ap", async ({ billids, txEnvelope }) => { + await setSessionData(socket.id, "pbs_txEnvelope", txEnvelope); + PbsExportAp(socket, { billids, txEnvelope }).catch((err) => console.error(`Error in pbs-export-ap: ${err}`)); }); } // Room management and broadcasting events function registerRoomAndBroadcastEvents(socket) { - socket.on("join-bodyshop-room", (bodyshopUUID) => { + socket.on("join-bodyshop-room", async (bodyshopUUID) => { socket.join(bodyshopUUID); - createLogEvent(socket, "DEBUG", `Client joined bodyshop room: ${bodyshopUUID}`); + await createLogEvent(socket, "DEBUG", `Client joined bodyshop room: ${bodyshopUUID}`); }); - socket.on("leave-bodyshop-room", (bodyshopUUID) => { + socket.on("leave-bodyshop-room", async (bodyshopUUID) => { socket.leave(bodyshopUUID); - createLogEvent(socket, "DEBUG", `Client left bodyshop room: ${bodyshopUUID}`); + await createLogEvent(socket, "DEBUG", `Client left bodyshop room: ${bodyshopUUID}`); }); - socket.on("broadcast-to-bodyshop", (bodyshopUUID, message) => { + socket.on("broadcast-to-bodyshop", async (bodyshopUUID, message) => { io.to(bodyshopUUID).emit("bodyshop-message", message); - createLogEvent(socket, "INFO", `Broadcasted message to bodyshop ${bodyshopUUID}`); + await createLogEvent(socket, "INFO", `Broadcast message to bodyshop ${bodyshopUUID}`); + }); +} + +// DMS session clearing event +function registerDmsClearSessionEvent(socket) { + socket.on("clear-dms-session", async () => { + await clearSessionData(socket.id); // Clear all session data in Redis + await createLogEvent(socket, "INFO", `DMS session data cleared for socket ${socket.id}`); }); } // Logging helper functions -function createLogEvent(socket, level, message) { - if (LogLevelHierarchy(socket.log_level) >= LogLevelHierarchy(level)) { +async function createLogEvent(socket, level, message) { + const logLevel = await getSessionData(socket.id, "log_level"); + const recordid = await getSessionData(socket.id, "recordid"); + const logEvents = await getSessionData(socket.id, "logEvents"); + + if (LogLevelHierarchy(logLevel) >= LogLevelHierarchy(level)) { console.log(`[WS LOG EVENT] ${level} - ${new Date()} - ${socket.user.email} - ${socket.id} - ${message}`); socket.emit("log-event", { timestamp: new Date(), level, message }); - logger.log("ws-log-event", level, socket.user.email, socket.recordid, { wsmessage: message }); + logger.log("ws-log-event", level, socket.user.email, recordid, { wsmessage: message }); - if (socket.logEvents && isArray(socket.logEvents)) { - socket.logEvents.push({ timestamp: new Date(), level, message }); + if (logEvents && Array.isArray(logEvents)) { + logEvents.push({ timestamp: new Date(), level, message }); + setSessionData(socket.id, "logEvents", logEvents).catch((err) => + console.error(`Error setting logEvents in Redis: ${err}`) + ); } } } -function createJsonEvent(socket, level, message, json) { - if (LogLevelHierarchy(socket.log_level) >= LogLevelHierarchy(level)) { +async function createJsonEvent(socket, level, message, json) { + const logEvents = await getSessionData(socket.id, "logEvents"); + const logLevel = await getSessionData(socket.id, "log_level"); + const recordid = await getSessionData(socket.id, "recordid"); + + if (LogLevelHierarchy(logLevel) >= LogLevelHierarchy(level)) { socket.emit("log-event", { timestamp: new Date(), level, message }); } - logger.log("ws-log-event-json", level, socket.user.email, socket.recordid, { wsmessage: message, json }); - if (socket.logEvents && isArray(socket.logEvents)) { - socket.logEvents.push({ timestamp: new Date(), level, message }); + logger.log("ws-log-event-json", level, socket.user.email, recordid, { + wsmessage: message, + json + }); + + if (logEvents && Array.isArray(logEvents)) { + logEvents.push({ timestamp: new Date(), level, message }); + setSessionData(socket.id, "logEvents", logEvents).catch((err) => + console.error(`Error setting logEvents in Redis: ${err}`) + ); } } -function createXmlEvent(socket, xml, message, isError = false) { - if (LogLevelHierarchy(socket.log_level) >= LogLevelHierarchy("TRACE")) { +async function createXmlEvent(socket, xml, message, isError = false) { + const logLevel = await getSessionData(socket.id, "log_level"); + const recordid = await getSessionData(socket.id, "recordid"); + const logEvents = await getSessionData(socket.id, "logEvents"); + + if (LogLevelHierarchy(logLevel) >= LogLevelHierarchy("TRACE")) { socket.emit("log-event", { timestamp: new Date(), level: isError ? "ERROR" : "TRACE", @@ -166,12 +206,19 @@ function createXmlEvent(socket, xml, message, isError = false) { isError ? "ws-log-event-xml-error" : "ws-log-event-xml", isError ? "ERROR" : "TRACE", socket.user.email, - socket.recordid, + recordid, { wsmessage: message, xml } ); - if (socket.logEvents && isArray(socket.logEvents)) { - socket.logEvents.push({ timestamp: new Date(), level: isError ? "ERROR" : "TRACE", message, xml }); + if (logEvents && Array.isArray(logEvents)) { + logEvents.push({ + timestamp: new Date(), + level: isError ? "ERROR" : "TRACE", + message, + xml + }); + + await setSessionData(socket.id, "logEvents", logEvents); } }