From f7799ffd038c72187a6e13ba53af63fbbbe3ba0d Mon Sep 17 00:00:00 2001 From: Dave Date: Wed, 24 Sep 2025 18:12:57 -0400 Subject: [PATCH] feature/IO-2776-cdk-fortellis - Cleanup + Auth Socket stuff --- server/accounting/pbs/pbs-ap-allocations.js | 66 ++- server/accounting/pbs/pbs-job-export.js | 59 +- server/cdk/cdk-job-export.js | 161 +++--- server/fortellis/fortellis.js | 575 +++++++++++--------- server/web-sockets/redisSocketEvents.js | 13 +- server/web-sockets/web-socket.js | 5 +- 6 files changed, 492 insertions(+), 387 deletions(-) diff --git a/server/accounting/pbs/pbs-ap-allocations.js b/server/accounting/pbs/pbs-ap-allocations.js index f417d0d15..0fc2d0c4d 100644 --- a/server/accounting/pbs/pbs-ap-allocations.js +++ b/server/accounting/pbs/pbs-ap-allocations.js @@ -1,7 +1,7 @@ const GraphQLClient = require("graphql-request").GraphQLClient; const queries = require("../../graphql-client/queries"); -const WsLogger = require("../../web-sockets/createLogEvent") +const WsLogger = require("../../web-sockets/createLogEvent"); const moment = require("moment"); const Dinero = require("dinero.js"); const AxiosLib = require("axios").default; @@ -18,8 +18,9 @@ axios.interceptors.request.use((x) => { ...x.headers }; - const printable = `${new Date()} | Request: ${x.method.toUpperCase()} | ${x.url - } | ${JSON.stringify(x.data)} | ${JSON.stringify(headers)}`; + const printable = `${new Date()} | Request: ${x.method.toUpperCase()} | ${ + x.url + } | ${JSON.stringify(x.data)} | ${JSON.stringify(headers)}`; //console.log(printable); WsLogger.createJsonEvent(socket, "SILLY", `Raw Request: ${printable}`, x.data); @@ -146,7 +147,9 @@ async function PbsCalculateAllocationsAp(socket, billids) { ...billHash[key], Amount: billHash[key].Amount.toFormat("0.00") }); - APAmount = APAmount.add(billHash[key].Amount); //Calculate the total expense for the bill iteratively to create the corresponding credit to AP. + //Calculate the total expense for the bill iteratively to + // create the corresponding credit to AP. + APAmount = APAmount.add(billHash[key].Amount); } }); @@ -174,9 +177,13 @@ exports.PbsCalculateAllocationsAp = PbsCalculateAllocationsAp; async function QueryBillData(socket, billids) { WsLogger.createLogEvent(socket, "DEBUG", `Querying bill data for id(s) ${billids}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); + const currentToken = + (socket?.data && socket.data.authToken) || (socket?.handshake?.auth && socket.handshake.auth.token); + const result = await client - .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) + .setHeaders({ Authorization: `Bearer ${currentToken}` }) .request(queries.GET_PBS_AP_ALLOCATIONS, { billids: billids }); + WsLogger.createLogEvent(socket, "SILLY", `Bill data query result ${JSON.stringify(result, null, 2)}`); return result; @@ -191,7 +198,32 @@ function getCostAccount(billline, respcenters) { return respcenters.costs.find((c) => c.name === acctName); } -exports.PbsExportAp = async function (socket, { billids, txEnvelope }) { +async function MarkApExported(socket, billids) { + WsLogger.createLogEvent(socket, "DEBUG", `Marking bills as exported for id ${billids}`); + const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); + const currentToken = + (socket?.data && socket.data.authToken) || (socket?.handshake?.auth && socket.handshake.auth.token); + + const result = await client + .setHeaders({ Authorization: `Bearer ${currentToken}` }) + .request(queries.MARK_BILLS_EXPORTED, { + billids, + bill: { + exported: true, + exported_at: new Date() + }, + logs: socket.bills.map((bill) => ({ + bodyshopid: socket.bodyshop.id, + billid: bill.id, + successful: true, + useremail: socket.user.email + })) + }); + + return result; +} + +const defaultHandler = async (socket, { billids, txEnvelope }) => { WsLogger.createLogEvent(socket, "DEBUG", `Exporting selected AP.`); //apAllocations has the same shap as the lines key for the accounting posting to PBS. @@ -222,24 +254,4 @@ exports.PbsExportAp = async function (socket, { billids, txEnvelope }) { socket.emit("ap-export-complete"); }; -async function MarkApExported(socket, billids) { - WsLogger.createLogEvent(socket, "DEBUG", `Marking bills as exported for id ${billids}`); - const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); - const result = await client - .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) - .request(queries.MARK_BILLS_EXPORTED, { - billids, - bill: { - exported: true, - exported_at: new Date() - }, - logs: socket.bills.map((bill) => ({ - bodyshopid: socket.bodyshop.id, - billid: bill.id, - successful: true, - useremail: socket.user.email - })) - }); - - return result; -} +exports.PbsExportAp = defaultHandler; diff --git a/server/accounting/pbs/pbs-job-export.js b/server/accounting/pbs/pbs-job-export.js index 61f449e84..04ee907d0 100644 --- a/server/accounting/pbs/pbs-job-export.js +++ b/server/accounting/pbs/pbs-job-export.js @@ -2,7 +2,7 @@ const GraphQLClient = require("graphql-request").GraphQLClient; const AxiosLib = require("axios").default; const queries = require("../../graphql-client/queries"); const { PBS_ENDPOINTS, PBS_CREDENTIALS } = require("./pbs-constants"); -const WsLogger = require("../../web-sockets/createLogEvent") +const WsLogger = require("../../web-sockets/createLogEvent"); //const { CDK_CREDENTIALS, CheckCdkResponseForError } = require("./cdk-wsdl"); const CalculateAllocations = require("../../cdk/cdk-calculate-allocations").default; @@ -19,8 +19,9 @@ axios.interceptors.request.use((x) => { ...x.headers[x.method], ...x.headers }; - const printable = `${new Date()} | Request: ${x.method.toUpperCase()} | ${x.url - } | ${JSON.stringify(x.data)} | ${JSON.stringify(headers)}`; + const printable = `${new Date()} | Request: ${x.method.toUpperCase()} | ${ + x.url + } | ${JSON.stringify(x.data)} | ${JSON.stringify(headers)}`; //console.log(printable); WsLogger.createJsonEvent(socket, "SILLY", `Raw Request: ${printable}`, x.data); @@ -38,7 +39,7 @@ axios.interceptors.response.use((x) => { return x; }); -exports.default = async function (socket, { txEnvelope, jobid }) { +const defaultHandler = async (socket, { txEnvelope, jobid }) => { socket.logEvents = []; socket.recordid = jobid; socket.txEnvelope = txEnvelope; @@ -51,7 +52,7 @@ exports.default = async function (socket, { txEnvelope, jobid }) { //Query for the Vehicle record to get the associated customer. socket.DmsVeh = await QueryVehicleFromDms(socket); //Todo: Need to validate the lines and methods below. - if (socket.DmsVeh && socket.DmsVeh.CustomerRef) { + if (socket.DmsVeh?.CustomerRef) { //Get the associated customer from the Vehicle Record. socket.DMSVehCustomer = await QueryCustomerBycodeFromDms(socket, socket.DmsVeh.CustomerRef); } @@ -66,6 +67,8 @@ exports.default = async function (socket, { txEnvelope, jobid }) { } }; +exports.default = defaultHandler; + exports.PbsSelectedCustomer = async function PbsSelectedCustomer(socket, selectedCustomerId) { try { if (socket.JobData.bodyshop.pbs_configuration.disablecontactvehicle === false) { @@ -75,7 +78,8 @@ exports.PbsSelectedCustomer = async function PbsSelectedCustomer(socket, selecte WsLogger.createLogEvent( socket, "DEBUG", - `Upserting contact information to DMS for ${socket.JobData.ownr_fn || "" + `Upserting contact information to DMS for ${ + socket.JobData.ownr_fn || "" } ${socket.JobData.ownr_ln || ""} ${socket.JobData.ownr_co_nm || ""}` ); const ownerRef = await UpsertContactData(socket, selectedCustomerId); @@ -122,9 +126,13 @@ exports.CheckForErrors = CheckForErrors; async function QueryJobData(socket, jobid) { WsLogger.createLogEvent(socket, "DEBUG", `Querying job data for id ${jobid}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); + const currentToken = + (socket?.data && socket.data.authToken) || (socket?.handshake?.auth && socket.handshake.auth.token); + const result = await client - .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) + .setHeaders({ Authorization: `Bearer ${currentToken}` }) .request(queries.QUERY_JOBS_FOR_PBS_EXPORT, { id: jobid }); + WsLogger.createLogEvent(socket, "SILLY", `Job data query result ${JSON.stringify(result, null, 2)}`); return result.jobs_by_pk; } @@ -193,7 +201,7 @@ async function QueryCustomersFromDms(socket) { { auth: PBS_CREDENTIALS, socket } ); CheckForErrors(socket, CustomerGetResponse); - return CustomerGetResponse && CustomerGetResponse.Contacts; + return CustomerGetResponse?.Contacts; } catch (error) { WsLogger.createLogEvent(socket, "ERROR", `Error in QueryCustomersFromDms - ${error}`); throw new Error(error); @@ -226,7 +234,7 @@ async function QueryCustomerBycodeFromDms(socket, CustomerRef) { { auth: PBS_CREDENTIALS, socket } ); CheckForErrors(socket, CustomerGetResponse); - return CustomerGetResponse && CustomerGetResponse.Contacts; + return CustomerGetResponse?.Contacts; } catch (error) { WsLogger.createLogEvent(socket, "ERROR", `Error in QueryCustomersFromDms - ${error}`); throw new Error(error); @@ -245,15 +253,15 @@ async function UpsertContactData(socket, selectedCustomerId) { Code: socket.JobData.owner.accountingid, ...(socket.JobData.ownr_co_nm ? { - //LastName: socket.JobData.ownr_ln, - FirstName: socket.JobData.ownr_co_nm, - IsBusiness: true - } + //LastName: socket.JobData.ownr_ln, + FirstName: socket.JobData.ownr_co_nm, + IsBusiness: true + } : { - LastName: socket.JobData.ownr_ln, - FirstName: socket.JobData.ownr_fn, - IsBusiness: false - }), + LastName: socket.JobData.ownr_ln, + FirstName: socket.JobData.ownr_fn, + IsBusiness: false + }), //Salutation: "String", //MiddleName: "String", @@ -330,10 +338,10 @@ async function UpsertVehicleData(socket, ownerRef) { //FleetNumber: "String", //Status: "String", OwnerRef: ownerRef, // "00000000000000000000000000000000", - ModelNumber: socket.JobData.vehicle && socket.JobData.vehicle.v_makecode, + ModelNumber: 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, + Trim: socket.JobData.vehicle?.v_trimcode, //VehicleType: "String", Year: socket.JobData.v_model_yr, Odometer: socket.JobData.kmout, @@ -551,7 +559,8 @@ async function InsertAccountPostingData(socket) { 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", + //Sample TransactionDate: "0001-01-01T00:00:00.0000000Z", + TransactionDate: moment(socket.JobData.date_invoiced).tz(socket.JobData.bodyshop.timezone).toISOString(), Description: socket.txEnvelope.story, //AdditionalInfo: "String", Source: InstanceManager({ imex: "ImEX Online", rome: "Rome Online" }), @@ -572,8 +581,11 @@ async function InsertAccountPostingData(socket) { async function MarkJobExported(socket, jobid) { WsLogger.createLogEvent(socket, "DEBUG", `Marking job as exported for id ${jobid}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); + const currentToken = + (socket?.data && socket.data.authToken) || (socket?.handshake?.auth && socket.handshake.auth.token); + const result = await client - .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) + .setHeaders({ Authorization: `Bearer ${currentToken}` }) .request(queries.MARK_JOB_EXPORTED, { jobId: jobid, job: { @@ -599,8 +611,11 @@ async function MarkJobExported(socket, jobid) { async function InsertFailedExportLog(socket, error) { try { const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); + const currentToken = + (socket?.data && socket.data.authToken) || (socket?.handshake?.auth && socket.handshake.auth.token); + const result = await client - .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) + .setHeaders({ Authorization: `Bearer ${currentToken}` }) .request(queries.INSERT_EXPORT_LOG, { log: { bodyshopid: socket.JobData.bodyshop.id, diff --git a/server/cdk/cdk-job-export.js b/server/cdk/cdk-job-export.js index 619313c7b..13a8553ec 100644 --- a/server/cdk/cdk-job-export.js +++ b/server/cdk/cdk-job-export.js @@ -5,13 +5,13 @@ const CdkWsdl = require("./cdk-wsdl").default; const { CDK_CREDENTIALS, CheckCdkResponseForError } = require("./cdk-wsdl"); const CalcualteAllocations = require("./cdk-calculate-allocations").default; const InstanceMgr = require("../utils/instanceMgr").default; -const WsLogger = require("../web-sockets/createLogEvent") +const WsLogger = require("../web-sockets/createLogEvent"); const moment = require("moment-timezone"); const replaceSpecialRegex = /[^a-zA-Z0-9 .,\n #]+/g; -exports.default = async function (socket, { txEnvelope, jobid }) { +const defaultHandler = async (socket, { txEnvelope, jobid }) => { ////Store the following information into the redis store for this transaction. socket.logEvents = []; socket.recordid = jobid; @@ -38,9 +38,9 @@ exports.default = async function (socket, { txEnvelope, jobid }) { socket.DMSVeh = await QueryDmsVehicleById(socket, JobData, socket.DMSVid); const DMSVehCustomer = - socket.DMSVeh && socket.DMSVeh.owners && socket.DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT"); + socket.DMSVeh?.owners && socket.DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT"); - if (DMSVehCustomer && DMSVehCustomer.id && DMSVehCustomer.id.value) { + if (DMSVehCustomer?.id && DMSVehCustomer.id.value) { WsLogger.createLogEvent( socket, "DEBUG", @@ -62,6 +62,7 @@ exports.default = async function (socket, { txEnvelope, jobid }) { WsLogger.createLogEvent(socket, "ERROR", `Error encountered in CdkJobExport. ${error}`); } }; +exports.default = defaultHandler; async function CdkSelectedCustomer(socket, selectedCustomerId) { try { @@ -77,7 +78,11 @@ async function CdkSelectedCustomer(socket, selectedCustomerId) { } if (socket.DMSVid.newId === "Y") { - WsLogger.createLogEvent(socket, "DEBUG", `{4.1} Inserting new vehicle with ID: ID ${socket.DMSVid.vehiclesVehId}`); + WsLogger.createLogEvent( + socket, + "DEBUG", + `{4.1} Inserting new vehicle with ID: ID ${socket.DMSVid.vehiclesVehId}` + ); socket.DMSVeh = await InsertDmsVehicle(socket); } else { WsLogger.createLogEvent( @@ -147,9 +152,13 @@ exports.CdkSelectedCustomer = CdkSelectedCustomer; async function QueryJobData(socket, jobid) { WsLogger.createLogEvent(socket, "DEBUG", `Querying job data for id ${jobid}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); + const currentToken = + (socket?.data && socket.data.authToken) || (socket?.handshake?.auth && socket.handshake.auth.token); + const result = await client - .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) + .setHeaders({ Authorization: `Bearer ${currentToken}` }) .request(queries.QUERY_JOBS_FOR_CDK_EXPORT, { id: jobid }); + WsLogger.createLogEvent(socket, "SILLY", `Job data query result ${JSON.stringify(result, null, 2)}`); return result.jobs_by_pk; } @@ -185,7 +194,7 @@ async function CalculateDmsVid(socket, JobData) { WsLogger.createXmlEvent( socket, - error.response && error.response.data, + error.response?.data, `soapClientVehicleInsertUpdate.getVehIdsAsync response.`, true ); @@ -218,7 +227,7 @@ async function QueryDmsVehicleById(socket, JobData, DMSVid) { ); WsLogger.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.readAsync response.`); CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); - const VehicleFromDMS = result && result.return && result.return.vehicle; + const VehicleFromDMS = result?.return && result.return.vehicle; return VehicleFromDMS; } catch (error) { WsLogger.createLogEvent(socket, "ERROR", `Error in QueryDmsVehicleById - ${error}`); @@ -249,17 +258,12 @@ async function QueryDmsCustomerById(socket, JobData, CustomerId) { `soapClientCustomerInsertUpdate.readAsync Result ${JSON.stringify(result, null, 2)}` ); CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate); - const CustomersFromDms = result && result.return && result.return.customerParty; + const CustomersFromDms = result?.return && result.return.customerParty; return CustomersFromDms; } catch (error) { WsLogger.createXmlEvent(socket, error.request, `soapClientCustomerInsertUpdate.readAsync request.`, true); - WsLogger.createXmlEvent( - socket, - error.response && error.response.data, - `soapClientCustomerInsertUpdate.readAsync response.`, - true - ); + WsLogger.createXmlEvent(socket, error.response?.data, `soapClientCustomerInsertUpdate.readAsync response.`, true); WsLogger.createLogEvent(socket, "ERROR", `Error in QueryDmsCustomerById - ${error}`); throw new Error(error); @@ -298,14 +302,14 @@ async function QueryDmsCustomerByName(socket, JobData) { `soapClientCustomerSearch.executeSearchBulkAsync Result ${JSON.stringify(result, null, 2)}` ); CheckCdkResponseForError(socket, soapResponseCustomerSearch); - const CustomersFromDms = (result && result.return) || []; + const CustomersFromDms = result?.return || []; return CustomersFromDms; } catch (error) { WsLogger.createXmlEvent(socket, error.request, `soapClientCustomerSearch.executeSearchBulkAsync request.`, true); WsLogger.createXmlEvent( socket, - error.response && error.response.data, + error.response?.data, `soapClientCustomerSearch.executeSearchBulkAsync response.`, true ); @@ -321,7 +325,8 @@ async function GenerateDmsCustomerNumber(socket) { 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. + //TODO: Verify why this does not follow the other standards. + arg1: { dealerId: socket.JobData.bodyshop.cdk_dealerid }, arg2: { userId: null } }, @@ -340,7 +345,7 @@ async function GenerateDmsCustomerNumber(socket) { `soapClientCustomerInsertUpdate.getCustomerNumberAsync Result ${JSON.stringify(result, null, 2)}` ); CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate); - const customerNumber = result && result.return && result.return.customerNumber; + const customerNumber = result?.return && result.return.customerNumber; return customerNumber; } catch (error) { WsLogger.createXmlEvent( @@ -352,7 +357,7 @@ async function GenerateDmsCustomerNumber(socket) { WsLogger.createXmlEvent( socket, - error.response && error.response.data, + error.response?.data, `soapClientCustomerInsertUpdate.getCustomerNumberAsync response.`, true ); @@ -428,17 +433,12 @@ async function InsertDmsCustomer(socket, newCustomerNumber) { `soapClientCustomerInsertUpdate.insertAsync Result ${JSON.stringify(result, null, 2)}` ); CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate); - const customer = result && result.return && result.return.customerParty; + const customer = result?.return && result.return.customerParty; return customer; } catch (error) { WsLogger.createXmlEvent(socket, error.request, `soapClientCustomerInsertUpdate.insertAsync request.`, true); - WsLogger.createXmlEvent( - socket, - error.response && error.response.data, - `soapClientCustomerInsertUpdate.insertAsync response.`, - true - ); + WsLogger.createXmlEvent(socket, error.response?.data, `soapClientCustomerInsertUpdate.insertAsync response.`, true); WsLogger.createLogEvent(socket, "ERROR", `Error in InsertDmsCustomer - ${error}`); throw new Error(error); } @@ -459,9 +459,9 @@ async function InsertDmsVehicle(socket) { socket.txEnvelope.dms_unsold === true ? "" : moment(socket.txEnvelope.inservicedate) - //.tz(socket.JobData.bodyshop.timezone) - .startOf("day") - .toISOString() + //.tz(socket.JobData.bodyshop.timezone) + .startOf("day") + .toISOString() }), vehicleId: socket.DMSVid.vehiclesVehId }, @@ -471,16 +471,16 @@ async function InsertDmsVehicle(socket) { socket.txEnvelope.dms_unsold === true ? "" : moment() - // .tz(socket.JobData.bodyshop.timezone) - .format("YYYYMMDD"), + // .tz(socket.JobData.bodyshop.timezone) + .format("YYYYMMDD"), licensePlateNo: socket.JobData.plate_no === null ? null : String(socket.JobData.plate_no).replace(/([^\w]|_)/g, "").length === 0 ? null : String(socket.JobData.plate_no) - .replace(/([^\w]|_)/g, "") - .toUpperCase(), + .replace(/([^\w]|_)/g, "") + .toUpperCase(), make: socket.txEnvelope.dms_make, modelAbrev: socket.txEnvelope.dms_model, modelYear: socket.JobData.v_model_yr, @@ -509,7 +509,7 @@ async function InsertDmsVehicle(socket) { ); WsLogger.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.insertAsync response.`); CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); - const VehicleFromDMS = result && result.return && result.return.vehicle; + const VehicleFromDMS = result?.return && result.return.vehicle; return VehicleFromDMS; } catch (error) { WsLogger.createLogEvent(socket, "ERROR", `Error in InsertDmsVehicle - ${error}`); @@ -526,12 +526,10 @@ async function UpdateDmsVehicle(socket) { //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; + ids = socket.DMSVeh?.owners && socket.DMSVeh.owners; } else { const existingOwnerinVeh = - socket.DMSVeh && - socket.DMSVeh.owners && - socket.DMSVeh.owners.find((o) => o.id.value === socket.DMSCust.id.value); + socket.DMSVeh?.owners && socket.DMSVeh.owners.find((o) => o.id.value === socket.DMSCust.id.value); if (existingOwnerinVeh) { ids = socket.DMSVeh.owners.map((o) => { @@ -543,10 +541,7 @@ async function UpdateDmsVehicle(socket) { }; }); } else { - const oldOwner = - socket.DMSVeh && - socket.DMSVeh.owners && - socket.DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT"); + const oldOwner = socket.DMSVeh?.owners && socket.DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT"); ids = [ { @@ -557,13 +552,13 @@ async function UpdateDmsVehicle(socket) { }, ...(oldOwner ? [ - { - id: { - assigningPartyId: "PREVIOUS", - value: oldOwner.id.value + { + id: { + assigningPartyId: "PREVIOUS", + value: oldOwner.id.value + } } - } - ] + ] : []) ]; } @@ -581,24 +576,24 @@ async function UpdateDmsVehicle(socket) { socket.txEnvelope.dms_unsold === true ? "" : moment(socket.DMSVeh.dealer.inServiceDate || socket.txEnvelope.inservicedate) - // .tz(socket.JobData.bodyshop.timezone) - .toISOString() + // .tz(socket.JobData.bodyshop.timezone) + .toISOString() }) }, vehicle: { ...socket.DMSVeh.vehicle, ...(socket.txEnvelope.dms_model_override ? { - make: socket.txEnvelope.dms_make, - modelAbrev: socket.txEnvelope.dms_model - } + make: socket.txEnvelope.dms_make, + modelAbrev: socket.txEnvelope.dms_model + } : {}), deliveryDate: socket.txEnvelope.dms_unsold === true ? "" : moment(socket.DMSVeh.vehicle.deliveryDate) - //.tz(socket.JobData.bodyshop.timezone) - .toISOString() + //.tz(socket.JobData.bodyshop.timezone) + .toISOString() }, owners: ids }, @@ -615,7 +610,7 @@ async function UpdateDmsVehicle(socket) { ); WsLogger.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.updateAsync response.`); CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); - const VehicleFromDMS = result && result.return && result.return.vehicle; + const VehicleFromDMS = result?.return && result.return.vehicle; return VehicleFromDMS; } catch (error) { WsLogger.createLogEvent(socket, "ERROR", `Error in UpdateDmsVehicle - ${error}`); @@ -654,7 +649,7 @@ async function InsertServiceVehicleHistory(socket) { ); WsLogger.createXmlEvent(socket, rawResponse, `soapClientServiceHistoryInsert.serviceHistoryHeaderInsert response.`); CheckCdkResponseForError(socket, soapResponseServiceHistoryInsert); - return result && result.return; + return result?.return; } catch (error) { WsLogger.createLogEvent(socket, "ERROR", `Error in InsertServiceVehicleHistory - ${error}`); throw new Error(error); @@ -672,8 +667,10 @@ async function InsertDmsStartWip(socket) { 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 + docType: 10, // 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, @@ -694,7 +691,7 @@ async function InsertDmsStartWip(socket) { ); WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doStartWIPAsync response.`); CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); - const TransactionHeader = result && result.return; + const TransactionHeader = result?.return; return TransactionHeader; } catch (error) { WsLogger.createLogEvent(socket, "ERROR", `Error in InsertDmsStartWip - ${error}`); @@ -725,7 +722,7 @@ async function InsertDmsBatchWip(socket) { ); WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doTransBatchWIPAsync response.`); CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); - const BatchWipResult = result && result.return; + const BatchWipResult = result?.return; return BatchWipResult; } catch (error) { WsLogger.createLogEvent(socket, "ERROR", `Error in InsertDmsBatchWip - ${error}`); @@ -743,9 +740,9 @@ async function GenerateTransWips(socket) { 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 !== null && + alloc.profitCenter.dms_control_override !== undefined && + alloc.profitCenter.dms_control_override?.trim() !== "" ? alloc.profitCenter.dms_control_override : socket.JobData.ro_number, cntl2: null, @@ -766,9 +763,9 @@ async function GenerateTransWips(socket) { acct: alloc.costCenter.dms_acctnumber, cntl: alloc.costCenter.dms_control_override && - alloc.costCenter.dms_control_override !== null && - alloc.costCenter.dms_control_override !== undefined && - alloc.costCenter.dms_control_override?.trim() !== "" + alloc.costCenter.dms_control_override !== null && + alloc.costCenter.dms_control_override !== undefined && + alloc.costCenter.dms_control_override?.trim() !== "" ? alloc.costCenter.dms_control_override : socket.JobData.ro_number, cntl2: null, @@ -786,9 +783,9 @@ async function GenerateTransWips(socket) { acct: alloc.costCenter.dms_wip_acctnumber, cntl: alloc.costCenter.dms_control_override && - alloc.costCenter.dms_control_override !== null && - alloc.costCenter.dms_control_override !== undefined && - alloc.costCenter.dms_control_override?.trim() !== "" + alloc.costCenter.dms_control_override !== null && + alloc.costCenter.dms_control_override !== undefined && + alloc.costCenter.dms_control_override?.trim() !== "" ? alloc.costCenter.dms_control_override : socket.JobData.ro_number, cntl2: null, @@ -827,9 +824,9 @@ async function GenerateTransWips(socket) { 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 !== null && + alloc.profitCenter.dms_control_override !== undefined && + alloc.profitCenter.dms_control_override?.trim() !== "" ? alloc.profitCenter.dms_control_override : socket.JobData.ro_number, cntl2: null, @@ -889,7 +886,7 @@ async function PostDmsBatchWip(socket) { ); WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync response.`); // CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); - const PostResult = result && result.return; + const PostResult = result?.return; return PostResult; } catch (error) { WsLogger.createLogEvent(socket, "ERROR", `Error in PostDmsBatchWip - ${error}`); @@ -918,7 +915,7 @@ async function QueryDmsErrWip(socket) { ); WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doErrWIPAsync response.`); CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); - const PostResult = result && result.return; + const PostResult = result?.return; return PostResult; } catch (error) { WsLogger.createLogEvent(socket, "ERROR", `Error in QueryDmsErrWip - ${error}`); @@ -949,7 +946,7 @@ async function DeleteDmsWip(socket) { ); WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync response.`); CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); - const PostResult = result && result.return; + const PostResult = result?.return; return PostResult; } catch (error) { WsLogger.createLogEvent(socket, "ERROR", `Error in PostDmsBatchWip - ${error}`); @@ -960,8 +957,11 @@ async function DeleteDmsWip(socket) { async function MarkJobExported(socket, jobid) { WsLogger.createLogEvent(socket, "DEBUG", `Marking job as exported for id ${jobid}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); + const currentToken = + (socket?.data && socket.data.authToken) || (socket?.handshake?.auth && socket.handshake.auth.token); + const result = await client - .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) + .setHeaders({ Authorization: `Bearer ${currentToken}` }) .request(queries.MARK_JOB_EXPORTED, { jobId: jobid, job: { @@ -987,8 +987,11 @@ async function MarkJobExported(socket, jobid) { async function InsertFailedExportLog(socket, error) { try { const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); + const currentToken = + (socket?.data && socket.data.authToken) || (socket?.handshake?.auth && socket.handshake.auth.token); + const result = await client - .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) + .setHeaders({ Authorization: `Bearer ${currentToken}` }) .request(queries.INSERT_EXPORT_LOG, { log: { bodyshopid: socket.JobData.bodyshop.id, diff --git a/server/fortellis/fortellis.js b/server/fortellis/fortellis.js index 5d7bf3398..341ed1d56 100644 --- a/server/fortellis/fortellis.js +++ b/server/fortellis/fortellis.js @@ -29,17 +29,20 @@ function handleFortellisApiError(socket, error, functionName, additionalDetails functionName, ...additionalDetails }); - CreateFortellisLogEvent(socket, "DEBUG", `${functionName} failed. , ${JSON.stringify({ - reqId: error.reqId, - url: error.url, - apiName: error.apiName, - errorData: error.errorData, - errorStatus: error.errorStatus, - errorStatusText: error.errorStatusText, - functionName, - ...additionalDetails - })}`); - + CreateFortellisLogEvent( + socket, + "DEBUG", + `${functionName} failed. , ${JSON.stringify({ + reqId: error.reqId, + url: error.url, + apiName: error.apiName, + errorData: error.errorData, + errorStatus: error.errorStatus, + errorStatusText: error.errorStatusText, + functionName, + ...additionalDetails + })}` + ); } else { CreateFortellisLogEvent(socket, "ERROR", `Error in ${functionName} - ${error.message}`, { error: error.message, @@ -50,13 +53,7 @@ function handleFortellisApiError(socket, error, functionName, additionalDetails } } -async function FortellisJobExport({ - socket, - redisHelpers, - ioHelpers: { getBodyshopRoom, getBodyshopConversationRoom }, - txEnvelope, - jobid -}) { +async function FortellisJobExport({ socket, redisHelpers, txEnvelope, jobid }) { const { // setSessionData, // getSessionData, @@ -64,7 +61,7 @@ async function FortellisJobExport({ // removeUserSocketMapping, // refreshUserSocketTTL, // getUserSocketMappingByBodyshop, - setSessionTransactionData, + setSessionTransactionData // getSessionTransactionData, // clearSessionTransactionData } = redisHelpers; @@ -78,47 +75,78 @@ async function FortellisJobExport({ defaultFortellisTTL ); - const JobData = await QueryJobData({ socket, jobid }); //TODO: Need to remove unnecessary stuff here to reduce the payload. - await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.JobData, JobData, defaultFortellisTTL); + //TODO: Need to remove unnecessary stuff here to reduce the payload. + const JobData = await QueryJobData({ socket, jobid }); + + await setSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.JobData, + JobData, + defaultFortellisTTL + ); CreateFortellisLogEvent(socket, "DEBUG", `{1} Begin Calculate DMS Vehicle ID using VIN: ${JobData.v_vin}`); const DMSVid = (await CalculateDmsVid({ socket, JobData, redisHelpers }))[0]; - await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSVid, DMSVid, defaultFortellisTTL); + await setSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.DMSVid, + DMSVid, + defaultFortellisTTL + ); let DMSVehCustomer; if (!DMSVid.newId) { - CreateFortellisLogEvent( - socket, - "DEBUG", - `{2.1} Querying the Vehicle using the DMSVid: ${DMSVid.vehiclesVehId}` - ); + CreateFortellisLogEvent(socket, "DEBUG", `{2.1} Querying the Vehicle using the DMSVid: ${DMSVid.vehiclesVehId}`); const DMSVeh = await QueryDmsVehicleById({ socket, redisHelpers, JobData, DMSVid }); - await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSVeh, DMSVeh, defaultFortellisTTL); + await setSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.DMSVeh, + DMSVeh, + defaultFortellisTTL + ); const DMSVehCustomerFromVehicle = - DMSVeh && DMSVeh.owners && DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT"); + DMSVeh?.owners && DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT"); - if (DMSVehCustomerFromVehicle && DMSVehCustomerFromVehicle.id && DMSVehCustomerFromVehicle.id.value) { + if (DMSVehCustomerFromVehicle?.id && DMSVehCustomerFromVehicle.id.value) { CreateFortellisLogEvent( socket, "DEBUG", `{2.2} Querying the Customer using the ID from DMSVeh: ${DMSVehCustomerFromVehicle.id.value}` ); - DMSVehCustomer = await QueryDmsCustomerById({ socket, redisHelpers, JobData, CustomerId: DMSVehCustomerFromVehicle.id.value }); - await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSVehCustomer, DMSVehCustomer, defaultFortellisTTL); + DMSVehCustomer = await QueryDmsCustomerById({ + socket, + redisHelpers, + JobData, + CustomerId: DMSVehCustomerFromVehicle.id.value + }); + await setSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.DMSVehCustomer, + DMSVehCustomer, + defaultFortellisTTL + ); } } CreateFortellisLogEvent(socket, "DEBUG", `{2.3} Querying the Customer using the name.`); const DMSCustList = await QueryDmsCustomerByName({ socket, redisHelpers, JobData }); - await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSCustList, DMSCustList, defaultFortellisTTL); - + await setSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.DMSCustList, + DMSCustList, + defaultFortellisTTL + ); socket.emit("fortellis-select-customer", [ ...(DMSVehCustomer ? [{ ...DMSVehCustomer, vinOwner: true }] : []), ...DMSCustList ]); - } catch (error) { CreateFortellisLogEvent(socket, "ERROR", `Error in FortellisJobExport - ${error} `, { error: error.message, @@ -127,10 +155,7 @@ async function FortellisJobExport({ } } - - -async function FortellisSelectedCustomer({ socket, redisHelpers, ioHelpers, selectedCustomerId, jobid }) { - +async function FortellisSelectedCustomer({ socket, redisHelpers, selectedCustomerId, jobid }) { const { // setSessionData, // getSessionData, @@ -139,93 +164,117 @@ async function FortellisSelectedCustomer({ socket, redisHelpers, ioHelpers, sele // refreshUserSocketTTL, // getUserSocketMappingByBodyshop, setSessionTransactionData, - getSessionTransactionData, + getSessionTransactionData //clearSessionTransactionData } = redisHelpers; - await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.selectedCustomerId, selectedCustomerId, defaultFortellisTTL); + await setSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.selectedCustomerId, + selectedCustomerId, + defaultFortellisTTL + ); const JobData = await getSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.JobData); - const txEnvelope = await getSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.txEnvelope); - const DMSVid = await redisHelpers.getSessionTransactionData(socket.id, getTransactionType(JobData.id), FortellisCacheEnums.DMSVid); + const txEnvelope = await getSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.txEnvelope + ); + const DMSVid = await redisHelpers.getSessionTransactionData( + socket.id, + getTransactionType(JobData.id), + FortellisCacheEnums.DMSVid + ); try { - - let DMSCust; if (selectedCustomerId) { - CreateFortellisLogEvent( - socket, - "DEBUG", - `{3.1} Querying the Customer using Customer ID: ${selectedCustomerId}` - ); + CreateFortellisLogEvent(socket, "DEBUG", `{3.1} Querying the Customer using Customer ID: ${selectedCustomerId}`); DMSCust = await QueryDmsCustomerById({ socket, redisHelpers, JobData, CustomerId: selectedCustomerId }); //TODO: Optimize here - if selected ID, we already have the customer information. Prevent an extra call to Fortellis. - await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSCust, DMSCust, defaultFortellisTTL); - } else { - CreateFortellisLogEvent( - socket, - "DEBUG", - `{3.2} Creating new customer.` + await setSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.DMSCust, + DMSCust, + defaultFortellisTTL ); + } else { + CreateFortellisLogEvent(socket, "DEBUG", `{3.2} Creating new customer.`); const DMSCustomerInsertResponse = await InsertDmsCustomer({ socket, redisHelpers, JobData }); - DMSCust = { customerId: DMSCustomerInsertResponse.data } - await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSCust, DMSCust, defaultFortellisTTL); + DMSCust = { customerId: DMSCustomerInsertResponse.data }; + await setSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.DMSCust, + DMSCust, + defaultFortellisTTL + ); } let DMSVeh; if (DMSVid.newId) { - CreateFortellisLogEvent( - socket, - "DEBUG", - `{4.1} Inserting new vehicle with ID: ID ${DMSVid.vehiclesVehId}` - ); + CreateFortellisLogEvent(socket, "DEBUG", `{4.1} Inserting new vehicle with ID: ID ${DMSVid.vehiclesVehId}`); DMSVeh = await InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMSVid, DMSCust }); } else { - CreateFortellisLogEvent( - socket, - "DEBUG", - `{4.2} Querying Existing Vehicle using ID ${DMSVid.vehiclesVehId}` - ); + CreateFortellisLogEvent(socket, "DEBUG", `{4.2} Querying Existing Vehicle using ID ${DMSVid.vehiclesVehId}`); DMSVeh = await QueryDmsVehicleById({ socket, redisHelpers, JobData, DMSVid }); - CreateFortellisLogEvent( + CreateFortellisLogEvent(socket, "DEBUG", `{4.3} Updating Existing Vehicle to associate to owner.`); + DMSVeh = await UpdateDmsVehicle({ socket, - "DEBUG", - `{4.3} Updating Existing Vehicle to associate to owner.` - ); - DMSVeh = await UpdateDmsVehicle({ socket, redisHelpers, JobData, DMSVeh, DMSCust, selectedCustomerId, txEnvelope }); - await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSVeh, DMSVeh, defaultFortellisTTL);//TODO: This should be immutable probably.F - + redisHelpers, + JobData, + DMSVeh, + DMSCust, + selectedCustomerId, + txEnvelope + }); + await setSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.DMSVeh, + DMSVeh, + defaultFortellisTTL + ); //TODO: This should be immutable probably.F } // const DMSVehHistory = await InsertServiceVehicleHistory({ socket, redisHelpers, JobData }); // await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSVehHistory, DMSVehHistory, defaultFortellisTTL); - CreateFortellisLogEvent( - socket, - "DEBUG", - `{5} Creating Transaction header with Dms Start WIP` - ); + CreateFortellisLogEvent(socket, "DEBUG", `{5} Creating Transaction header with Dms Start WIP`); const DMSTransHeader = await InsertDmsStartWip({ socket, redisHelpers, JobData }); - await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSTransHeader, DMSTransHeader, defaultFortellisTTL); - - CreateFortellisLogEvent( - socket, - "DEBUG", - `{5.1} Creating Transaction with ID ${DMSTransHeader.transID}` + await setSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.DMSTransHeader, + DMSTransHeader, + defaultFortellisTTL ); + CreateFortellisLogEvent(socket, "DEBUG", `{5.1} Creating Transaction with ID ${DMSTransHeader.transID}`); + const DMSBatchTxn = await InsertDmsBatchWip({ socket, redisHelpers, JobData }); - await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSBatchTxn, DMSBatchTxn, defaultFortellisTTL); + await setSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.DMSBatchTxn, + DMSBatchTxn, + defaultFortellisTTL + ); if (DMSBatchTxn.rtnCode === "0") { - CreateFortellisLogEvent( - socket, - "DEBUG", - `{6} Attempting to post Transaction with ID ${DMSTransHeader.transID}` - ); + CreateFortellisLogEvent(socket, "DEBUG", `{6} Attempting to post Transaction with ID ${DMSTransHeader.transID}`); const DmsBatchTxnPost = await PostDmsBatchWip({ socket, redisHelpers, JobData }); - await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DmsBatchTxnPost, DmsBatchTxnPost, defaultFortellisTTL); + await setSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.DmsBatchTxnPost, + DmsBatchTxnPost, + defaultFortellisTTL + ); - if (DmsBatchTxnPost.rtnCode === "0") { //TODO: Validate this is a string and not # + if (DmsBatchTxnPost.rtnCode === "0") { + //TODO: Validate this is a string and not # //something CreateFortellisLogEvent(socket, "DEBUG", `{6} Successfully posted transaction to DMS.`); @@ -233,17 +282,21 @@ async function FortellisSelectedCustomer({ socket, redisHelpers, ioHelpers, sele CreateFortellisLogEvent(socket, "DEBUG", `{5} Updating Service Vehicle History.`); const DMSVehHistory = await InsertServiceVehicleHistory({ socket, redisHelpers, JobData }); - await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSVehHistory, DMSVehHistory, defaultFortellisTTL); + await setSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.DMSVehHistory, + DMSVehHistory, + defaultFortellisTTL + ); socket.emit("export-success", JobData.id); } else { //Get the error code - CreateFortellisLogEvent( - socket, - "DEBUG", - `{6.1} Getting errors for Transaction ID ${DMSTransHeader.transID}` - ); + CreateFortellisLogEvent(socket, "DEBUG", `{6.1} Getting errors for Transaction ID ${DMSTransHeader.transID}`); - const DmsError = await QueryDmsErrWip({ socket, redisHelpers, JobData }); + await QueryDmsErrWip({ socket, redisHelpers, JobData }); + + // const DmsError = await QueryDmsErrWip({ socket, redisHelpers, JobData }); // socket.DmsError = await QueryDmsErrWip(socket); // //Delete the transaction // CdkBase.createLogEvent(socket, "DEBUG", `{ 6.2 } Deleting Transaction ID ${ socket.DMSTransHeader.transID } `); @@ -265,7 +318,6 @@ async function FortellisSelectedCustomer({ socket, redisHelpers, ioHelpers, sele "ERROR", `DMS Batch Return code was not successful: ${DMSBatchTxn.rtnCode} - ${DMSBatchTxn.sendline}` ); - } } catch (error) { // CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkSelectedCustomer.${ error } `); @@ -277,7 +329,6 @@ async function FortellisSelectedCustomer({ socket, redisHelpers, ioHelpers, sele } finally { //Ensure we always insert logEvents //GQL to insert logevents. - //CdkBase.createLogEvent(socket, "DEBUG", `Capturing log events to database.`); } } @@ -301,8 +352,7 @@ async function CalculateDmsVid({ socket, JobData, redisHelpers }) { redisHelpers, socket, jobid: JobData.id, - body: {}, - + body: {} }); return result; } catch (error) { @@ -323,7 +373,7 @@ async function QueryDmsVehicleById({ socket, redisHelpers, JobData, DMSVid }) { redisHelpers, socket, jobid: JobData.id, - body: {}, + body: {} }); return result; } catch (error) { @@ -344,8 +394,7 @@ async function QueryDmsCustomerById({ socket, redisHelpers, JobData, CustomerId redisHelpers, socket, jobid: JobData.id, - body: {}, - + body: {} }); return result.data; } catch (error) { @@ -361,14 +410,12 @@ async function QueryDmsCustomerByName({ socket, redisHelpers, JobData }) { const ownerName = JobData.ownr_co_nm && JobData.ownr_co_nm.trim() !== "" ? [["lastName", JobData.ownr_co_nm.replace(replaceSpecialRegex, "")]] - : [["firstName", JobData.ownr_fn.replace(replaceSpecialRegex, "")], ["lastName", JobData.ownr_ln.replace(replaceSpecialRegex, "")]]; + : [ + ["firstName", JobData.ownr_fn.replace(replaceSpecialRegex, "")], + ["lastName", JobData.ownr_ln.replace(replaceSpecialRegex, "")] + ]; - CreateFortellisLogEvent( - socket, - "DEBUG", - `Begin query DMS Customer by Name using ${JSON.stringify(ownerName) - } ` - ); + CreateFortellisLogEvent(socket, "DEBUG", `Begin query DMS Customer by Name using ${JSON.stringify(ownerName)} `); try { const result = await MakeFortellisCall({ @@ -378,8 +425,7 @@ async function QueryDmsCustomerByName({ socket, redisHelpers, JobData }) { redisHelpers, socket, jobid: JobData.id, - body: {}, - + body: {} }); return result.data; } catch (error) { @@ -400,33 +446,28 @@ async function InsertDmsCustomer({ socket, redisHelpers, JobData }) { socket, jobid: JobData.id, body: { - "customerType": "INDIVIDUAL", - "customerName": { + customerType: "INDIVIDUAL", + customerName: { //"suffix": "Mr.", - "firstName": JobData.ownr_fn && JobData.ownr_fn.replace(replaceSpecialRegex, "").toUpperCase(), + firstName: JobData.ownr_fn && JobData.ownr_fn.replace(replaceSpecialRegex, "").toUpperCase(), //"middleName": "", - "lastName": JobData.ownr_ln && JobData.ownr_ln.replace(replaceSpecialRegex, "").toUpperCase(), + lastName: JobData.ownr_ln && JobData.ownr_ln.replace(replaceSpecialRegex, "").toUpperCase() //"title": "", //"nickName": "" }, - "companyName": JobData.ownr_co_nm && JobData.ownr_co_nm.replace(replaceSpecialRegex, "").toUpperCase(), - "postalAddress": { - "addressLine1": JobData.ownr_addr1?.replace(replaceSpecialRegex, "").trim(), - "addressLine2": JobData.ownr_addr2?.replace(replaceSpecialRegex, "").trim(), - "city": JobData.ownr_city?.replace(replaceSpecialRegex, "").trim(), - "state": JobData.ownr_state?.replace(replaceSpecialRegex, "").trim(), - "postalCode": InstanceMgr({ - imex: - JobData.ownr_zip && - JobData.ownr_zip - .toUpperCase() - .replace(/\W/g, "") - .replace(/(...)/, "$1 "), + companyName: JobData.ownr_co_nm && JobData.ownr_co_nm.replace(replaceSpecialRegex, "").toUpperCase(), + postalAddress: { + addressLine1: JobData.ownr_addr1?.replace(replaceSpecialRegex, "").trim(), + addressLine2: JobData.ownr_addr2?.replace(replaceSpecialRegex, "").trim(), + city: JobData.ownr_city?.replace(replaceSpecialRegex, "").trim(), + state: JobData.ownr_state?.replace(replaceSpecialRegex, "").trim(), + postalCode: InstanceMgr({ + imex: JobData.ownr_zip && JobData.ownr_zip.toUpperCase().replace(/\W/g, "").replace(/(...)/, "$1 "), rome: JobData.ownr_zip }), //"county": JobData.ownr_county?.trim(), - "country": JobData.ownr_ctry?.replace(replaceSpecialRegex, "").trim(), - "province": JobData.ownr_st?.replace(replaceSpecialRegex, "").trim(), + country: JobData.ownr_ctry?.replace(replaceSpecialRegex, "").trim(), + province: JobData.ownr_st?.replace(replaceSpecialRegex, "").trim() //"territory": "" }, // "birthDate": { @@ -436,12 +477,12 @@ async function InsertDmsCustomer({ socket, redisHelpers, JobData }) { // }, //"gender": "M", //"language": "English", - "contactMethods": { - "phones": [ + contactMethods: { + phones: [ { //"uuid": "", - "number": JobData.ownr_ph1?.replace(replaceSpecialRegex, ""), - "type": "HOME", + number: JobData.ownr_ph1?.replace(replaceSpecialRegex, ""), + type: "HOME" // "doNotCallIndicator": true, // "doNotCallIndicatorDate": `null, // "doNotCallRegistrySource": "", @@ -454,7 +495,7 @@ async function InsertDmsCustomer({ socket, redisHelpers, JobData }) { // "optInRequestedDate": null, // "preferredDay": "", // "preferredTime": "" - }, + } // { // "uuid": "", // "number": "6666666666", @@ -473,20 +514,22 @@ async function InsertDmsCustomer({ socket, redisHelpers, JobData }) { // "preferredTime": "" // } ], - "emailAddresses": [ - - ...!_.isEmpty(JobData.ownr_ea) ? - [{ - //"uuid": "", - "address": JobData.ownr_ea, - "type": "PERSONAL", - // "doNotEmailSource": "", - // "doNotEmail": false, - // "isPreferred": true, - // "transactionEmailNotificationOptIn": false, - // "optInRequestDate": null, - // "optInDate": null - }] : [], + emailAddresses: [ + ...(!_.isEmpty(JobData.ownr_ea) + ? [ + { + //"uuid": "", + address: JobData.ownr_ea, + type: "PERSONAL" + // "doNotEmailSource": "", + // "doNotEmail": false, + // "isPreferred": true, + // "transactionEmailNotificationOptIn": false, + // "optInRequestDate": null, + // "optInDate": null + } + ] + : []) // { // "uuid": "", // "address": "jilldoe@test.com", @@ -499,7 +542,7 @@ async function InsertDmsCustomer({ socket, redisHelpers, JobData }) { // "optInDate": null // } ] - }, + } // // "doNotContact": false, // // "optOutDate": "", // // "optOutTime": "", @@ -581,8 +624,7 @@ async function InsertDmsCustomer({ socket, redisHelpers, JobData }) { // "dealerField": "Custom dealer field value 3" // } // ] - }, - + } }); return result; } catch (error) { @@ -600,7 +642,6 @@ async function InsertDmsCustomer({ socket, redisHelpers, JobData }) { async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMSVid, DMSCust }) { try { - const result = await MakeFortellisCall({ ...FortellisActions.InsertVehicle, requestSearchParams: {}, @@ -609,8 +650,8 @@ async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMS socket, jobid: JobData.id, body: { - "dealer": { - "company": JobData.bodyshop.cdk_configuration.srcco || "77", + dealer: { + company: JobData.bodyshop.cdk_configuration.srcco || "77", // "dealNumber": "", // "dealerAssignedNumber": "82268", // "dealerDefined1": "2WDSP", @@ -627,12 +668,12 @@ async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMS txEnvelope.dms_unsold === true ? "" : moment(txEnvelope.inservicedate) - //.tz(JobData.bodyshop.timezone) - .startOf("day") - .toISOString() + //.tz(JobData.bodyshop.timezone) + .startOf("day") + .toISOString() }), //"lastServiceDate": "2011-11-23", - "vehicleId": DMSVid.vehiclesVehId, + vehicleId: DMSVid.vehiclesVehId // "vehicleLocation": "", // "vehicleSoldDate": "2021-04-06", // "wholesaleVehicleInd": false @@ -656,7 +697,7 @@ async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMS // "vehicleOrderPriority": "", // "vehicleOrderType": "TRE RETAIL - STOCK" // }, - "vehicle": { + vehicle: { // "axleCode": "GU6/3.42 REAR AXLE RATIO", // "axleCount": 2, // "bodyStyle": "PU", @@ -671,8 +712,8 @@ async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMS txEnvelope.dms_unsold === true ? "" : moment() - // .tz(JobData.bodyshop.timezone) - .format("YYYY-MM-DD"), + // .tz(JobData.bodyshop.timezone) + .format("YYYY-MM-DD"), // "deliveryMileage": 4, // "doorsQuantity": 4, // "engineNumber": "", @@ -689,8 +730,8 @@ async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMS : String(JobData.plate_no).replace(/([^\w]|_)/g, "").length === 0 ? null : String(JobData.plate_no) - .replace(/([^\w]|_)/g, "") - .toUpperCase(), + .replace(/([^\w]|_)/g, "") + .toUpperCase(), make: txEnvelope.dms_make, // "model": "CC10753", modelAbrev: txEnvelope.dms_model, @@ -781,18 +822,16 @@ async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMS // "warrantyExpDate": "2015-01-12", // "wheelbase": "" }, - "owners": [ + owners: [ { - "id": { + id: { assigningPartyId: "CURRENT", value: DMSCust.customerId - }, - + } } - ], + ] //"inventoryAccount": "237" - }, - + } }); return result.data; } catch (error) { @@ -808,18 +847,14 @@ async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMS async function UpdateDmsVehicle({ socket, redisHelpers, JobData, DMSVeh, DMSCust, selectedCustomerId, txEnvelope }) { try { - let ids = []; //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 && DMSVeh.owners; + ids = DMSVeh?.owners && DMSVeh.owners; } else { - const existingOwnerinVeh = - DMSVeh && - DMSVeh.owners && - DMSVeh.owners.find((o) => o.id.value === DMSCust.customerId); + const existingOwnerinVeh = DMSVeh?.owners && DMSVeh.owners.find((o) => o.id.value === DMSCust.customerId); if (existingOwnerinVeh) { ids = DMSVeh.owners.map((o) => { @@ -831,10 +866,7 @@ async function UpdateDmsVehicle({ socket, redisHelpers, JobData, DMSVeh, DMSCust }; }); } else { - const oldOwner = - DMSVeh && - DMSVeh.owners && - DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT"); + const oldOwner = DMSVeh?.owners && DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT"); ids = [ { @@ -845,13 +877,13 @@ async function UpdateDmsVehicle({ socket, redisHelpers, JobData, DMSVeh, DMSCust }, ...(oldOwner ? [ - { - id: { - assigningPartyId: "PREVIOUS", - value: oldOwner.id + { + id: { + assigningPartyId: "PREVIOUS", + value: oldOwner.id + } } - } - ] + ] : []) ]; } @@ -864,7 +896,6 @@ async function UpdateDmsVehicle({ socket, redisHelpers, JobData, DMSVeh, DMSCust delete DMSVehToSend.invoice; delete DMSVehToSend.inventoryAccount; - const result = await MakeFortellisCall({ ...FortellisActions.UpdateVehicle, requestSearchParams: {}, @@ -882,28 +913,27 @@ async function UpdateDmsVehicle({ socket, redisHelpers, JobData, DMSVeh, DMSCust txEnvelope.dms_unsold === true ? "" : moment(DMSVehToSend.dealer.inServiceDate || txEnvelope.inservicedate) - // .tz(JobData.bodyshop.timezone) - .toISOString() + // .tz(JobData.bodyshop.timezone) + .toISOString() }) }, vehicle: { ...DMSVehToSend.vehicle, ...(txEnvelope.dms_model_override ? { - make: txEnvelope.dms_make, - modelAbrev: txEnvelope.dms_model - } + make: txEnvelope.dms_make, + modelAbrev: txEnvelope.dms_model + } : {}), deliveryDate: txEnvelope.dms_unsold === true ? "" : moment(DMSVehToSend.vehicle.deliveryDate) - //.tz(JobData.bodyshop.timezone) - .toISOString() + //.tz(JobData.bodyshop.timezone) + .toISOString() }, owners: ids - }, - + } }); return result; } catch (error) { @@ -918,12 +948,18 @@ async function UpdateDmsVehicle({ socket, redisHelpers, JobData, DMSVeh, DMSCust } } - -async function InsertServiceVehicleHistory({ socket, redisHelpers, JobData, }) { - +async function InsertServiceVehicleHistory({ socket, redisHelpers, JobData }) { try { - const txEnvelope = await redisHelpers.getSessionTransactionData(socket.id, getTransactionType(JobData.id), FortellisCacheEnums.txEnvelope); - const DMSVid = await redisHelpers.getSessionTransactionData(socket.id, getTransactionType(JobData.id), FortellisCacheEnums.DMSVid); + const txEnvelope = await redisHelpers.getSessionTransactionData( + socket.id, + getTransactionType(JobData.id), + FortellisCacheEnums.txEnvelope + ); + const DMSVid = await redisHelpers.getSessionTransactionData( + socket.id, + getTransactionType(JobData.id), + FortellisCacheEnums.DMSVid + ); const result = await MakeFortellisCall({ ...FortellisActions.ServiceHistoryInsert, @@ -940,12 +976,11 @@ async function InsertServiceVehicleHistory({ socket, redisHelpers, JobData, }) { 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, // has to be between 0 and 40. + comments: txEnvelope.story, // has to be between 0 and 40. cashierId: JobData.bodyshop.cdk_configuration.cashierid, referenceNumber: JobData.bodyshop.cdk_configuration.cashierid } - }, - + } }); return result; } catch (error) { @@ -957,10 +992,13 @@ async function InsertServiceVehicleHistory({ socket, redisHelpers, JobData, }) { } } - async function InsertDmsStartWip({ socket, redisHelpers, JobData }) { try { - const txEnvelope = await redisHelpers.getSessionTransactionData(socket.id, getTransactionType(JobData.id), FortellisCacheEnums.txEnvelope); + const txEnvelope = await redisHelpers.getSessionTransactionData( + socket.id, + getTransactionType(JobData.id), + FortellisCacheEnums.txEnvelope + ); const result = await MakeFortellisCall({ ...FortellisActions.StartWip, @@ -969,21 +1007,20 @@ async function InsertDmsStartWip({ socket, redisHelpers, JobData }) { socket, jobid: JobData.id, body: { - "acctgDate": moment().tz(JobData.bodyshop.timezone).format("YYYY-MM-DD"), - "desc": txEnvelope.story && txEnvelope.story.replace(replaceSpecialRegex, ""), - "docType": "10", - "m13Flag": "0", - "refer": JobData.ro_number, + acctgDate: moment().tz(JobData.bodyshop.timezone).format("YYYY-MM-DD"), + desc: txEnvelope.story && txEnvelope.story.replace(replaceSpecialRegex, ""), + docType: "10", + m13Flag: "0", + refer: JobData.ro_number, // "rtnCode": "", // "sendline": "", // "groupName": "", - "srcCo": JobData.bodyshop.cdk_configuration.srcco, - "srcJrnl": txEnvelope.journal, - "transID": "", - "userID": JobData.bodyshop.cdk_configuration.cashierid, - "userName": "BSMS" - }, - + srcCo: JobData.bodyshop.cdk_configuration.srcco, + srcJrnl: txEnvelope.journal, + transID: "", + userID: JobData.bodyshop.cdk_configuration.cashierid, + userName: "BSMS" + } }); return result; } catch (error) { @@ -1016,9 +1053,15 @@ async function InsertDmsBatchWip({ socket, redisHelpers, JobData }) { } async function GenerateTransWips({ socket, redisHelpers, JobData }) { - const allocations = await CalculateAllocations(socket, JobData.id, true); //3rd prop sets fortellis to true to maintain logging. + //3rd prop sets fortellis to true to maintain logging. + const allocations = await CalculateAllocations(socket, JobData.id, true); + const wips = []; - const DMSTransHeader = await redisHelpers.getSessionTransactionData(socket.id, getTransactionType(JobData.id), FortellisCacheEnums.DMSTransHeader); + const DMSTransHeader = await redisHelpers.getSessionTransactionData( + socket.id, + getTransactionType(JobData.id), + FortellisCacheEnums.DMSTransHeader + ); allocations.forEach((alloc) => { //Add the sale item from each allocation. @@ -1027,9 +1070,9 @@ async function GenerateTransWips({ socket, redisHelpers, JobData }) { 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 !== null && + alloc.profitCenter.dms_control_override !== undefined && + alloc.profitCenter.dms_control_override?.trim() !== "" ? alloc.profitCenter.dms_control_override : JobData.ro_number, cntl2: null, @@ -1050,9 +1093,9 @@ async function GenerateTransWips({ socket, redisHelpers, JobData }) { acct: alloc.costCenter.dms_acctnumber, cntl: alloc.costCenter.dms_control_override && - alloc.costCenter.dms_control_override !== null && - alloc.costCenter.dms_control_override !== undefined && - alloc.costCenter.dms_control_override?.trim() !== "" + alloc.costCenter.dms_control_override !== null && + alloc.costCenter.dms_control_override !== undefined && + alloc.costCenter.dms_control_override?.trim() !== "" ? alloc.costCenter.dms_control_override : JobData.ro_number, cntl2: null, @@ -1070,9 +1113,9 @@ async function GenerateTransWips({ socket, redisHelpers, JobData }) { acct: alloc.costCenter.dms_wip_acctnumber, cntl: alloc.costCenter.dms_control_override && - alloc.costCenter.dms_control_override !== null && - alloc.costCenter.dms_control_override !== undefined && - alloc.costCenter.dms_control_override?.trim() !== "" + alloc.costCenter.dms_control_override !== null && + alloc.costCenter.dms_control_override !== undefined && + alloc.costCenter.dms_control_override?.trim() !== "" ? alloc.costCenter.dms_control_override : JobData.ro_number, cntl2: null, @@ -1089,15 +1132,14 @@ async function GenerateTransWips({ socket, redisHelpers, JobData }) { } if (alloc.tax) { - 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 !== null && + alloc.profitCenter.dms_control_override !== undefined && + alloc.profitCenter.dms_control_override?.trim() !== "" ? alloc.profitCenter.dms_control_override : JobData.ro_number, cntl2: null, @@ -1113,7 +1155,11 @@ async function GenerateTransWips({ socket, redisHelpers, JobData }) { } } }); - const txEnvelope = await redisHelpers.getSessionTransactionData(socket.id, getTransactionType(JobData.id), FortellisCacheEnums.txEnvelope); + const txEnvelope = await redisHelpers.getSessionTransactionData( + socket.id, + getTransactionType(JobData.id), + FortellisCacheEnums.txEnvelope + ); txEnvelope.payers.forEach((payer) => { const item = { @@ -1131,7 +1177,13 @@ async function GenerateTransWips({ socket, redisHelpers, JobData }) { wips.push(item); }); - await redisHelpers.setSessionTransactionData(socket.id, getTransactionType(JobData.id), FortellisCacheEnums.transWips, wips, defaultFortellisTTL); + await redisHelpers.setSessionTransactionData( + socket.id, + getTransactionType(JobData.id), + FortellisCacheEnums.transWips, + wips, + defaultFortellisTTL + ); return wips; } @@ -1139,8 +1191,11 @@ async function GenerateTransWips({ socket, redisHelpers, JobData }) { async function PostDmsBatchWip({ socket, redisHelpers, JobData }) { let DMSTransHeader; try { - DMSTransHeader = await redisHelpers.getSessionTransactionData(socket.id, getTransactionType(JobData.id), FortellisCacheEnums.DMSTransHeader); - + DMSTransHeader = await redisHelpers.getSessionTransactionData( + socket.id, + getTransactionType(JobData.id), + FortellisCacheEnums.DMSTransHeader + ); const result = await MakeFortellisCall({ ...FortellisActions.PostBatchWip, @@ -1149,8 +1204,8 @@ async function PostDmsBatchWip({ socket, redisHelpers, JobData }) { socket, jobid: JobData.id, body: { - "opCode": "P", - "transID": DMSTransHeader.transID + opCode: "P", + transID: DMSTransHeader.transID } }); return result; @@ -1166,8 +1221,11 @@ async function PostDmsBatchWip({ socket, redisHelpers, JobData }) { async function QueryDmsErrWip({ socket, redisHelpers, JobData }) { let DMSTransHeader; try { - DMSTransHeader = await redisHelpers.getSessionTransactionData(socket.id, getTransactionType(JobData.id), FortellisCacheEnums.DMSTransHeader); - + DMSTransHeader = await redisHelpers.getSessionTransactionData( + socket.id, + getTransactionType(JobData.id), + FortellisCacheEnums.DMSTransHeader + ); const result = await MakeFortellisCall({ ...FortellisActions.QueryErrorWip, @@ -1176,9 +1234,7 @@ async function QueryDmsErrWip({ socket, redisHelpers, JobData }) { socket, jobid: JobData.id, requestPathParams: DMSTransHeader.transID, - body: { - - } + body: {} }); return result; } catch (error) { @@ -1222,11 +1278,14 @@ async function QueryDmsErrWip({ socket, redisHelpers, JobData }) { // } async function MarkJobExported({ socket, jobid }) { - CreateFortellisLogEvent(socket, "ERROR", `Marking job as exported for id ${jobid}`); + const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); + const currentToken = + (socket?.data && socket.data.authToken) || (socket?.handshake?.auth && socket.handshake.auth.token); + const result = await client - .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) + .setHeaders({ Authorization: `Bearer ${currentToken}` }) .request(queries.MARK_JOB_EXPORTED, { jobId: jobid, job: { @@ -1252,8 +1311,11 @@ async function MarkJobExported({ socket, jobid }) { async function InsertFailedExportLog({ socket, JobData, error }) { try { const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); + const currentToken = + (socket?.data && socket.data.authToken) || (socket?.handshake?.auth && socket.handshake.auth.token); + const result = await client - .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) + .setHeaders({ Authorization: `Bearer ${currentToken}` }) .request(queries.INSERT_EXPORT_LOG, { log: { bodyshopid: JobData.bodyshop.id, @@ -1266,7 +1328,10 @@ async function InsertFailedExportLog({ socket, JobData, error }) { return result; } catch (error2) { - CreateFortellisLogEvent(socket, "ERROR", `Error in InsertFailedExportLog - ${error}`, { message: error2.message, stack: error2.stack }); + CreateFortellisLogEvent(socket, "ERROR", `Error in InsertFailedExportLog - ${error}`, { + message: error2.message, + stack: error2.stack + }); } } diff --git a/server/web-sockets/redisSocketEvents.js b/server/web-sockets/redisSocketEvents.js index 68a19fd19..10472fba1 100644 --- a/server/web-sockets/redisSocketEvents.js +++ b/server/web-sockets/redisSocketEvents.js @@ -36,9 +36,11 @@ const redisSocketEvents = ({ } try { - const user = await admin.auth().verifyIdToken(token); + const user = await admin.auth().verifyIdToken(token, true); socket.user = user; socket.bodyshopId = bodyshopId; + socket.data = socket.data || {}; + socket.data.authToken = token; await addUserSocketMapping(user.email, socket.id, bodyshopId); next(); } catch (error) { @@ -69,6 +71,15 @@ const redisSocketEvents = ({ } socket.user = user; socket.bodyshopId = bodyshopId; + // 🔑 keep the live token in a mutable place used by downstream code + socket.data = socket.data || {}; + socket.data.authToken = token; + // also keep handshake in sync for any legacy reads + if (socket.handshake?.auth) { + socket.handshake.auth.token = token; + socket.handshake.auth.bodyshopId = bodyshopId; + } + await refreshUserSocketTTL(user.email, bodyshopId); socket.emit("token-updated", { success: true }); } catch (error) { diff --git a/server/web-sockets/web-socket.js b/server/web-sockets/web-socket.js index b2e94909b..fbef1cf65 100644 --- a/server/web-sockets/web-socket.js +++ b/server/web-sockets/web-socket.js @@ -9,7 +9,6 @@ const { PbsCalculateAllocationsAp, PbsExportAp } = require("../accounting/pbs/pb const { createLogEvent } = require("./createLogEvent"); function SetLegacyWebsocketHandlers(io) { - io.use(function (socket, next) { try { if (socket.handshake.auth.token) { @@ -53,6 +52,7 @@ function SetLegacyWebsocketHandlers(io) { socket.on("cdk-export-job", (jobid) => { CdkJobExport(socket, jobid); }); + socket.on("cdk-selected-customer", (selectedCustomerId) => { createLogEvent(socket, "DEBUG", `User selected customer ID ${selectedCustomerId}`); socket.selectedCustomerId = selectedCustomerId; @@ -116,7 +116,6 @@ function SetLegacyWebsocketHandlers(io) { createLogEvent(socket, "DEBUG", `User disconnected.`); }); }); - } -exports.SetLegacyWebsocketHandlers = SetLegacyWebsocketHandlers; \ No newline at end of file +exports.SetLegacyWebsocketHandlers = SetLegacyWebsocketHandlers;