feature/IO-2776-cdk-fortellis - Cleanup + Auth Socket stuff

This commit is contained in:
Dave
2025-09-24 18:12:57 -04:00
parent 57baa3d9fd
commit f7799ffd03
6 changed files with 492 additions and 387 deletions

View File

@@ -1,7 +1,7 @@
const GraphQLClient = require("graphql-request").GraphQLClient; const GraphQLClient = require("graphql-request").GraphQLClient;
const queries = require("../../graphql-client/queries"); const queries = require("../../graphql-client/queries");
const WsLogger = require("../../web-sockets/createLogEvent") const WsLogger = require("../../web-sockets/createLogEvent");
const moment = require("moment"); const moment = require("moment");
const Dinero = require("dinero.js"); const Dinero = require("dinero.js");
const AxiosLib = require("axios").default; const AxiosLib = require("axios").default;
@@ -18,8 +18,9 @@ axios.interceptors.request.use((x) => {
...x.headers ...x.headers
}; };
const printable = `${new Date()} | Request: ${x.method.toUpperCase()} | ${x.url const printable = `${new Date()} | Request: ${x.method.toUpperCase()} | ${
} | ${JSON.stringify(x.data)} | ${JSON.stringify(headers)}`; x.url
} | ${JSON.stringify(x.data)} | ${JSON.stringify(headers)}`;
//console.log(printable); //console.log(printable);
WsLogger.createJsonEvent(socket, "SILLY", `Raw Request: ${printable}`, x.data); WsLogger.createJsonEvent(socket, "SILLY", `Raw Request: ${printable}`, x.data);
@@ -146,7 +147,9 @@ async function PbsCalculateAllocationsAp(socket, billids) {
...billHash[key], ...billHash[key],
Amount: billHash[key].Amount.toFormat("0.00") 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) { async function QueryBillData(socket, billids) {
WsLogger.createLogEvent(socket, "DEBUG", `Querying bill data for id(s) ${billids}`); WsLogger.createLogEvent(socket, "DEBUG", `Querying bill data for id(s) ${billids}`);
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); 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 const result = await client
.setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .setHeaders({ Authorization: `Bearer ${currentToken}` })
.request(queries.GET_PBS_AP_ALLOCATIONS, { billids: billids }); .request(queries.GET_PBS_AP_ALLOCATIONS, { billids: billids });
WsLogger.createLogEvent(socket, "SILLY", `Bill data query result ${JSON.stringify(result, null, 2)}`); WsLogger.createLogEvent(socket, "SILLY", `Bill data query result ${JSON.stringify(result, null, 2)}`);
return result; return result;
@@ -191,7 +198,32 @@ function getCostAccount(billline, respcenters) {
return respcenters.costs.find((c) => c.name === acctName); 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.`); WsLogger.createLogEvent(socket, "DEBUG", `Exporting selected AP.`);
//apAllocations has the same shap as the lines key for the accounting posting to PBS. //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"); socket.emit("ap-export-complete");
}; };
async function MarkApExported(socket, billids) { exports.PbsExportAp = defaultHandler;
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;
}

View File

@@ -2,7 +2,7 @@ const GraphQLClient = require("graphql-request").GraphQLClient;
const AxiosLib = require("axios").default; const AxiosLib = require("axios").default;
const queries = require("../../graphql-client/queries"); const queries = require("../../graphql-client/queries");
const { PBS_ENDPOINTS, PBS_CREDENTIALS } = require("./pbs-constants"); 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 { CDK_CREDENTIALS, CheckCdkResponseForError } = require("./cdk-wsdl");
const CalculateAllocations = require("../../cdk/cdk-calculate-allocations").default; const CalculateAllocations = require("../../cdk/cdk-calculate-allocations").default;
@@ -19,8 +19,9 @@ axios.interceptors.request.use((x) => {
...x.headers[x.method], ...x.headers[x.method],
...x.headers ...x.headers
}; };
const printable = `${new Date()} | Request: ${x.method.toUpperCase()} | ${x.url const printable = `${new Date()} | Request: ${x.method.toUpperCase()} | ${
} | ${JSON.stringify(x.data)} | ${JSON.stringify(headers)}`; x.url
} | ${JSON.stringify(x.data)} | ${JSON.stringify(headers)}`;
//console.log(printable); //console.log(printable);
WsLogger.createJsonEvent(socket, "SILLY", `Raw Request: ${printable}`, x.data); WsLogger.createJsonEvent(socket, "SILLY", `Raw Request: ${printable}`, x.data);
@@ -38,7 +39,7 @@ axios.interceptors.response.use((x) => {
return x; return x;
}); });
exports.default = async function (socket, { txEnvelope, jobid }) { const defaultHandler = async (socket, { txEnvelope, jobid }) => {
socket.logEvents = []; socket.logEvents = [];
socket.recordid = jobid; socket.recordid = jobid;
socket.txEnvelope = txEnvelope; socket.txEnvelope = txEnvelope;
@@ -51,7 +52,7 @@ exports.default = async function (socket, { txEnvelope, jobid }) {
//Query for the Vehicle record to get the associated customer. //Query for the Vehicle record to get the associated customer.
socket.DmsVeh = await QueryVehicleFromDms(socket); socket.DmsVeh = await QueryVehicleFromDms(socket);
//Todo: Need to validate the lines and methods below. //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. //Get the associated customer from the Vehicle Record.
socket.DMSVehCustomer = await QueryCustomerBycodeFromDms(socket, socket.DmsVeh.CustomerRef); 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) { exports.PbsSelectedCustomer = async function PbsSelectedCustomer(socket, selectedCustomerId) {
try { try {
if (socket.JobData.bodyshop.pbs_configuration.disablecontactvehicle === false) { if (socket.JobData.bodyshop.pbs_configuration.disablecontactvehicle === false) {
@@ -75,7 +78,8 @@ exports.PbsSelectedCustomer = async function PbsSelectedCustomer(socket, selecte
WsLogger.createLogEvent( WsLogger.createLogEvent(
socket, socket,
"DEBUG", "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 || ""}` } ${socket.JobData.ownr_ln || ""} ${socket.JobData.ownr_co_nm || ""}`
); );
const ownerRef = await UpsertContactData(socket, selectedCustomerId); const ownerRef = await UpsertContactData(socket, selectedCustomerId);
@@ -122,9 +126,13 @@ exports.CheckForErrors = CheckForErrors;
async function QueryJobData(socket, jobid) { async function QueryJobData(socket, jobid) {
WsLogger.createLogEvent(socket, "DEBUG", `Querying job data for id ${jobid}`); WsLogger.createLogEvent(socket, "DEBUG", `Querying job data for id ${jobid}`);
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); 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 const result = await client
.setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .setHeaders({ Authorization: `Bearer ${currentToken}` })
.request(queries.QUERY_JOBS_FOR_PBS_EXPORT, { id: jobid }); .request(queries.QUERY_JOBS_FOR_PBS_EXPORT, { id: jobid });
WsLogger.createLogEvent(socket, "SILLY", `Job data query result ${JSON.stringify(result, null, 2)}`); WsLogger.createLogEvent(socket, "SILLY", `Job data query result ${JSON.stringify(result, null, 2)}`);
return result.jobs_by_pk; return result.jobs_by_pk;
} }
@@ -193,7 +201,7 @@ async function QueryCustomersFromDms(socket) {
{ auth: PBS_CREDENTIALS, socket } { auth: PBS_CREDENTIALS, socket }
); );
CheckForErrors(socket, CustomerGetResponse); CheckForErrors(socket, CustomerGetResponse);
return CustomerGetResponse && CustomerGetResponse.Contacts; return CustomerGetResponse?.Contacts;
} catch (error) { } catch (error) {
WsLogger.createLogEvent(socket, "ERROR", `Error in QueryCustomersFromDms - ${error}`); WsLogger.createLogEvent(socket, "ERROR", `Error in QueryCustomersFromDms - ${error}`);
throw new Error(error); throw new Error(error);
@@ -226,7 +234,7 @@ async function QueryCustomerBycodeFromDms(socket, CustomerRef) {
{ auth: PBS_CREDENTIALS, socket } { auth: PBS_CREDENTIALS, socket }
); );
CheckForErrors(socket, CustomerGetResponse); CheckForErrors(socket, CustomerGetResponse);
return CustomerGetResponse && CustomerGetResponse.Contacts; return CustomerGetResponse?.Contacts;
} catch (error) { } catch (error) {
WsLogger.createLogEvent(socket, "ERROR", `Error in QueryCustomersFromDms - ${error}`); WsLogger.createLogEvent(socket, "ERROR", `Error in QueryCustomersFromDms - ${error}`);
throw new Error(error); throw new Error(error);
@@ -245,15 +253,15 @@ async function UpsertContactData(socket, selectedCustomerId) {
Code: socket.JobData.owner.accountingid, Code: socket.JobData.owner.accountingid,
...(socket.JobData.ownr_co_nm ...(socket.JobData.ownr_co_nm
? { ? {
//LastName: socket.JobData.ownr_ln, //LastName: socket.JobData.ownr_ln,
FirstName: socket.JobData.ownr_co_nm, FirstName: socket.JobData.ownr_co_nm,
IsBusiness: true IsBusiness: true
} }
: { : {
LastName: socket.JobData.ownr_ln, LastName: socket.JobData.ownr_ln,
FirstName: socket.JobData.ownr_fn, FirstName: socket.JobData.ownr_fn,
IsBusiness: false IsBusiness: false
}), }),
//Salutation: "String", //Salutation: "String",
//MiddleName: "String", //MiddleName: "String",
@@ -330,10 +338,10 @@ async function UpsertVehicleData(socket, ownerRef) {
//FleetNumber: "String", //FleetNumber: "String",
//Status: "String", //Status: "String",
OwnerRef: ownerRef, // "00000000000000000000000000000000", OwnerRef: ownerRef, // "00000000000000000000000000000000",
ModelNumber: socket.JobData.vehicle && socket.JobData.vehicle.v_makecode, ModelNumber: socket.JobData.vehicle?.v_makecode,
Make: socket.JobData.v_make_desc, Make: socket.JobData.v_make_desc,
Model: socket.JobData.v_model_desc, Model: socket.JobData.v_model_desc,
Trim: socket.JobData.vehicle && socket.JobData.vehicle.v_trimcode, Trim: socket.JobData.vehicle?.v_trimcode,
//VehicleType: "String", //VehicleType: "String",
Year: socket.JobData.v_model_yr, Year: socket.JobData.v_model_yr,
Odometer: socket.JobData.kmout, Odometer: socket.JobData.kmout,
@@ -551,7 +559,8 @@ async function InsertAccountPostingData(socket) {
Posting: { Posting: {
Reference: socket.JobData.ro_number, Reference: socket.JobData.ro_number,
JournalCode: socket.txEnvelope.journal, 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, Description: socket.txEnvelope.story,
//AdditionalInfo: "String", //AdditionalInfo: "String",
Source: InstanceManager({ imex: "ImEX Online", rome: "Rome Online" }), Source: InstanceManager({ imex: "ImEX Online", rome: "Rome Online" }),
@@ -572,8 +581,11 @@ async function InsertAccountPostingData(socket) {
async function MarkJobExported(socket, jobid) { async function MarkJobExported(socket, jobid) {
WsLogger.createLogEvent(socket, "DEBUG", `Marking job as exported for id ${jobid}`); WsLogger.createLogEvent(socket, "DEBUG", `Marking job as exported for id ${jobid}`);
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); 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 const result = await client
.setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .setHeaders({ Authorization: `Bearer ${currentToken}` })
.request(queries.MARK_JOB_EXPORTED, { .request(queries.MARK_JOB_EXPORTED, {
jobId: jobid, jobId: jobid,
job: { job: {
@@ -599,8 +611,11 @@ async function MarkJobExported(socket, jobid) {
async function InsertFailedExportLog(socket, error) { async function InsertFailedExportLog(socket, error) {
try { try {
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); 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 const result = await client
.setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .setHeaders({ Authorization: `Bearer ${currentToken}` })
.request(queries.INSERT_EXPORT_LOG, { .request(queries.INSERT_EXPORT_LOG, {
log: { log: {
bodyshopid: socket.JobData.bodyshop.id, bodyshopid: socket.JobData.bodyshop.id,

View File

@@ -5,13 +5,13 @@ const CdkWsdl = require("./cdk-wsdl").default;
const { CDK_CREDENTIALS, CheckCdkResponseForError } = require("./cdk-wsdl"); const { CDK_CREDENTIALS, CheckCdkResponseForError } = require("./cdk-wsdl");
const CalcualteAllocations = require("./cdk-calculate-allocations").default; const CalcualteAllocations = require("./cdk-calculate-allocations").default;
const InstanceMgr = require("../utils/instanceMgr").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 moment = require("moment-timezone");
const replaceSpecialRegex = /[^a-zA-Z0-9 .,\n #]+/g; 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. ////Store the following information into the redis store for this transaction.
socket.logEvents = []; socket.logEvents = [];
socket.recordid = jobid; socket.recordid = jobid;
@@ -38,9 +38,9 @@ exports.default = async function (socket, { txEnvelope, jobid }) {
socket.DMSVeh = await QueryDmsVehicleById(socket, JobData, socket.DMSVid); socket.DMSVeh = await QueryDmsVehicleById(socket, JobData, socket.DMSVid);
const DMSVehCustomer = 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( WsLogger.createLogEvent(
socket, socket,
"DEBUG", "DEBUG",
@@ -62,6 +62,7 @@ exports.default = async function (socket, { txEnvelope, jobid }) {
WsLogger.createLogEvent(socket, "ERROR", `Error encountered in CdkJobExport. ${error}`); WsLogger.createLogEvent(socket, "ERROR", `Error encountered in CdkJobExport. ${error}`);
} }
}; };
exports.default = defaultHandler;
async function CdkSelectedCustomer(socket, selectedCustomerId) { async function CdkSelectedCustomer(socket, selectedCustomerId) {
try { try {
@@ -77,7 +78,11 @@ async function CdkSelectedCustomer(socket, selectedCustomerId) {
} }
if (socket.DMSVid.newId === "Y") { 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); socket.DMSVeh = await InsertDmsVehicle(socket);
} else { } else {
WsLogger.createLogEvent( WsLogger.createLogEvent(
@@ -147,9 +152,13 @@ exports.CdkSelectedCustomer = CdkSelectedCustomer;
async function QueryJobData(socket, jobid) { async function QueryJobData(socket, jobid) {
WsLogger.createLogEvent(socket, "DEBUG", `Querying job data for id ${jobid}`); WsLogger.createLogEvent(socket, "DEBUG", `Querying job data for id ${jobid}`);
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); 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 const result = await client
.setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .setHeaders({ Authorization: `Bearer ${currentToken}` })
.request(queries.QUERY_JOBS_FOR_CDK_EXPORT, { id: jobid }); .request(queries.QUERY_JOBS_FOR_CDK_EXPORT, { id: jobid });
WsLogger.createLogEvent(socket, "SILLY", `Job data query result ${JSON.stringify(result, null, 2)}`); WsLogger.createLogEvent(socket, "SILLY", `Job data query result ${JSON.stringify(result, null, 2)}`);
return result.jobs_by_pk; return result.jobs_by_pk;
} }
@@ -185,7 +194,7 @@ async function CalculateDmsVid(socket, JobData) {
WsLogger.createXmlEvent( WsLogger.createXmlEvent(
socket, socket,
error.response && error.response.data, error.response?.data,
`soapClientVehicleInsertUpdate.getVehIdsAsync response.`, `soapClientVehicleInsertUpdate.getVehIdsAsync response.`,
true true
); );
@@ -218,7 +227,7 @@ async function QueryDmsVehicleById(socket, JobData, DMSVid) {
); );
WsLogger.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.readAsync response.`); WsLogger.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.readAsync response.`);
CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate);
const VehicleFromDMS = result && result.return && result.return.vehicle; const VehicleFromDMS = result?.return && result.return.vehicle;
return VehicleFromDMS; return VehicleFromDMS;
} catch (error) { } catch (error) {
WsLogger.createLogEvent(socket, "ERROR", `Error in QueryDmsVehicleById - ${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)}` `soapClientCustomerInsertUpdate.readAsync Result ${JSON.stringify(result, null, 2)}`
); );
CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate); CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate);
const CustomersFromDms = result && result.return && result.return.customerParty; const CustomersFromDms = result?.return && result.return.customerParty;
return CustomersFromDms; return CustomersFromDms;
} catch (error) { } catch (error) {
WsLogger.createXmlEvent(socket, error.request, `soapClientCustomerInsertUpdate.readAsync request.`, true); WsLogger.createXmlEvent(socket, error.request, `soapClientCustomerInsertUpdate.readAsync request.`, true);
WsLogger.createXmlEvent( WsLogger.createXmlEvent(socket, error.response?.data, `soapClientCustomerInsertUpdate.readAsync response.`, true);
socket,
error.response && error.response.data,
`soapClientCustomerInsertUpdate.readAsync response.`,
true
);
WsLogger.createLogEvent(socket, "ERROR", `Error in QueryDmsCustomerById - ${error}`); WsLogger.createLogEvent(socket, "ERROR", `Error in QueryDmsCustomerById - ${error}`);
throw new Error(error); throw new Error(error);
@@ -298,14 +302,14 @@ async function QueryDmsCustomerByName(socket, JobData) {
`soapClientCustomerSearch.executeSearchBulkAsync Result ${JSON.stringify(result, null, 2)}` `soapClientCustomerSearch.executeSearchBulkAsync Result ${JSON.stringify(result, null, 2)}`
); );
CheckCdkResponseForError(socket, soapResponseCustomerSearch); CheckCdkResponseForError(socket, soapResponseCustomerSearch);
const CustomersFromDms = (result && result.return) || []; const CustomersFromDms = result?.return || [];
return CustomersFromDms; return CustomersFromDms;
} catch (error) { } catch (error) {
WsLogger.createXmlEvent(socket, error.request, `soapClientCustomerSearch.executeSearchBulkAsync request.`, true); WsLogger.createXmlEvent(socket, error.request, `soapClientCustomerSearch.executeSearchBulkAsync request.`, true);
WsLogger.createXmlEvent( WsLogger.createXmlEvent(
socket, socket,
error.response && error.response.data, error.response?.data,
`soapClientCustomerSearch.executeSearchBulkAsync response.`, `soapClientCustomerSearch.executeSearchBulkAsync response.`,
true true
); );
@@ -321,7 +325,8 @@ async function GenerateDmsCustomerNumber(socket) {
const soapResponseCustomerInsertUpdate = await soapClientCustomerInsertUpdate.getCustomerNumberAsync( const soapResponseCustomerInsertUpdate = await soapClientCustomerInsertUpdate.getCustomerNumberAsync(
{ {
arg0: CDK_CREDENTIALS, 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 } arg2: { userId: null }
}, },
@@ -340,7 +345,7 @@ async function GenerateDmsCustomerNumber(socket) {
`soapClientCustomerInsertUpdate.getCustomerNumberAsync Result ${JSON.stringify(result, null, 2)}` `soapClientCustomerInsertUpdate.getCustomerNumberAsync Result ${JSON.stringify(result, null, 2)}`
); );
CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate); CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate);
const customerNumber = result && result.return && result.return.customerNumber; const customerNumber = result?.return && result.return.customerNumber;
return customerNumber; return customerNumber;
} catch (error) { } catch (error) {
WsLogger.createXmlEvent( WsLogger.createXmlEvent(
@@ -352,7 +357,7 @@ async function GenerateDmsCustomerNumber(socket) {
WsLogger.createXmlEvent( WsLogger.createXmlEvent(
socket, socket,
error.response && error.response.data, error.response?.data,
`soapClientCustomerInsertUpdate.getCustomerNumberAsync response.`, `soapClientCustomerInsertUpdate.getCustomerNumberAsync response.`,
true true
); );
@@ -428,17 +433,12 @@ async function InsertDmsCustomer(socket, newCustomerNumber) {
`soapClientCustomerInsertUpdate.insertAsync Result ${JSON.stringify(result, null, 2)}` `soapClientCustomerInsertUpdate.insertAsync Result ${JSON.stringify(result, null, 2)}`
); );
CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate); CheckCdkResponseForError(socket, soapResponseCustomerInsertUpdate);
const customer = result && result.return && result.return.customerParty; const customer = result?.return && result.return.customerParty;
return customer; return customer;
} catch (error) { } catch (error) {
WsLogger.createXmlEvent(socket, error.request, `soapClientCustomerInsertUpdate.insertAsync request.`, true); WsLogger.createXmlEvent(socket, error.request, `soapClientCustomerInsertUpdate.insertAsync request.`, true);
WsLogger.createXmlEvent( WsLogger.createXmlEvent(socket, error.response?.data, `soapClientCustomerInsertUpdate.insertAsync response.`, true);
socket,
error.response && error.response.data,
`soapClientCustomerInsertUpdate.insertAsync response.`,
true
);
WsLogger.createLogEvent(socket, "ERROR", `Error in InsertDmsCustomer - ${error}`); WsLogger.createLogEvent(socket, "ERROR", `Error in InsertDmsCustomer - ${error}`);
throw new Error(error); throw new Error(error);
} }
@@ -459,9 +459,9 @@ async function InsertDmsVehicle(socket) {
socket.txEnvelope.dms_unsold === true socket.txEnvelope.dms_unsold === true
? "" ? ""
: moment(socket.txEnvelope.inservicedate) : moment(socket.txEnvelope.inservicedate)
//.tz(socket.JobData.bodyshop.timezone) //.tz(socket.JobData.bodyshop.timezone)
.startOf("day") .startOf("day")
.toISOString() .toISOString()
}), }),
vehicleId: socket.DMSVid.vehiclesVehId vehicleId: socket.DMSVid.vehiclesVehId
}, },
@@ -471,16 +471,16 @@ async function InsertDmsVehicle(socket) {
socket.txEnvelope.dms_unsold === true socket.txEnvelope.dms_unsold === true
? "" ? ""
: moment() : moment()
// .tz(socket.JobData.bodyshop.timezone) // .tz(socket.JobData.bodyshop.timezone)
.format("YYYYMMDD"), .format("YYYYMMDD"),
licensePlateNo: licensePlateNo:
socket.JobData.plate_no === null socket.JobData.plate_no === null
? null ? null
: String(socket.JobData.plate_no).replace(/([^\w]|_)/g, "").length === 0 : String(socket.JobData.plate_no).replace(/([^\w]|_)/g, "").length === 0
? null ? null
: String(socket.JobData.plate_no) : String(socket.JobData.plate_no)
.replace(/([^\w]|_)/g, "") .replace(/([^\w]|_)/g, "")
.toUpperCase(), .toUpperCase(),
make: socket.txEnvelope.dms_make, make: socket.txEnvelope.dms_make,
modelAbrev: socket.txEnvelope.dms_model, modelAbrev: socket.txEnvelope.dms_model,
modelYear: socket.JobData.v_model_yr, modelYear: socket.JobData.v_model_yr,
@@ -509,7 +509,7 @@ async function InsertDmsVehicle(socket) {
); );
WsLogger.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.insertAsync response.`); WsLogger.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.insertAsync response.`);
CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate);
const VehicleFromDMS = result && result.return && result.return.vehicle; const VehicleFromDMS = result?.return && result.return.vehicle;
return VehicleFromDMS; return VehicleFromDMS;
} catch (error) { } catch (error) {
WsLogger.createLogEvent(socket, "ERROR", `Error in InsertDmsVehicle - ${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 it's a generic customer, don't update the vehicle owners.
if (socket.selectedCustomerId === socket.JobData.bodyshop.cdk_configuration.generic_customer_number) { 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 { } else {
const existingOwnerinVeh = 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) { if (existingOwnerinVeh) {
ids = socket.DMSVeh.owners.map((o) => { ids = socket.DMSVeh.owners.map((o) => {
@@ -543,10 +541,7 @@ async function UpdateDmsVehicle(socket) {
}; };
}); });
} else { } else {
const oldOwner = const oldOwner = socket.DMSVeh?.owners && socket.DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT");
socket.DMSVeh &&
socket.DMSVeh.owners &&
socket.DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT");
ids = [ ids = [
{ {
@@ -557,13 +552,13 @@ async function UpdateDmsVehicle(socket) {
}, },
...(oldOwner ...(oldOwner
? [ ? [
{ {
id: { id: {
assigningPartyId: "PREVIOUS", assigningPartyId: "PREVIOUS",
value: oldOwner.id.value value: oldOwner.id.value
}
} }
} ]
]
: []) : [])
]; ];
} }
@@ -581,24 +576,24 @@ async function UpdateDmsVehicle(socket) {
socket.txEnvelope.dms_unsold === true socket.txEnvelope.dms_unsold === true
? "" ? ""
: moment(socket.DMSVeh.dealer.inServiceDate || socket.txEnvelope.inservicedate) : moment(socket.DMSVeh.dealer.inServiceDate || socket.txEnvelope.inservicedate)
// .tz(socket.JobData.bodyshop.timezone) // .tz(socket.JobData.bodyshop.timezone)
.toISOString() .toISOString()
}) })
}, },
vehicle: { vehicle: {
...socket.DMSVeh.vehicle, ...socket.DMSVeh.vehicle,
...(socket.txEnvelope.dms_model_override ...(socket.txEnvelope.dms_model_override
? { ? {
make: socket.txEnvelope.dms_make, make: socket.txEnvelope.dms_make,
modelAbrev: socket.txEnvelope.dms_model modelAbrev: socket.txEnvelope.dms_model
} }
: {}), : {}),
deliveryDate: deliveryDate:
socket.txEnvelope.dms_unsold === true socket.txEnvelope.dms_unsold === true
? "" ? ""
: moment(socket.DMSVeh.vehicle.deliveryDate) : moment(socket.DMSVeh.vehicle.deliveryDate)
//.tz(socket.JobData.bodyshop.timezone) //.tz(socket.JobData.bodyshop.timezone)
.toISOString() .toISOString()
}, },
owners: ids owners: ids
}, },
@@ -615,7 +610,7 @@ async function UpdateDmsVehicle(socket) {
); );
WsLogger.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.updateAsync response.`); WsLogger.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.updateAsync response.`);
CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate);
const VehicleFromDMS = result && result.return && result.return.vehicle; const VehicleFromDMS = result?.return && result.return.vehicle;
return VehicleFromDMS; return VehicleFromDMS;
} catch (error) { } catch (error) {
WsLogger.createLogEvent(socket, "ERROR", `Error in UpdateDmsVehicle - ${error}`); WsLogger.createLogEvent(socket, "ERROR", `Error in UpdateDmsVehicle - ${error}`);
@@ -654,7 +649,7 @@ async function InsertServiceVehicleHistory(socket) {
); );
WsLogger.createXmlEvent(socket, rawResponse, `soapClientServiceHistoryInsert.serviceHistoryHeaderInsert response.`); WsLogger.createXmlEvent(socket, rawResponse, `soapClientServiceHistoryInsert.serviceHistoryHeaderInsert response.`);
CheckCdkResponseForError(socket, soapResponseServiceHistoryInsert); CheckCdkResponseForError(socket, soapResponseServiceHistoryInsert);
return result && result.return; return result?.return;
} catch (error) { } catch (error) {
WsLogger.createLogEvent(socket, "ERROR", `Error in InsertServiceVehicleHistory - ${error}`); WsLogger.createLogEvent(socket, "ERROR", `Error in InsertServiceVehicleHistory - ${error}`);
throw new Error(error); throw new Error(error);
@@ -672,8 +667,10 @@ async function InsertDmsStartWip(socket) {
acctgDate: moment().tz(socket.JobData.bodyshop.timezone).format("YYYY-MM-DD"), acctgDate: moment().tz(socket.JobData.bodyshop.timezone).format("YYYY-MM-DD"),
//socket.JobData.invoice_date //socket.JobData.invoice_date
desc: socket.txEnvelope.story && socket.txEnvelope.story.replace(replaceSpecialRegex, ""), 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. 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 //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, m13Flag: 0,
refer: socket.JobData.ro_number, refer: socket.JobData.ro_number,
srcCo: socket.JobData.bodyshop.cdk_configuration.srcco, srcCo: socket.JobData.bodyshop.cdk_configuration.srcco,
@@ -694,7 +691,7 @@ async function InsertDmsStartWip(socket) {
); );
WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doStartWIPAsync response.`); WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doStartWIPAsync response.`);
CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate);
const TransactionHeader = result && result.return; const TransactionHeader = result?.return;
return TransactionHeader; return TransactionHeader;
} catch (error) { } catch (error) {
WsLogger.createLogEvent(socket, "ERROR", `Error in InsertDmsStartWip - ${error}`); WsLogger.createLogEvent(socket, "ERROR", `Error in InsertDmsStartWip - ${error}`);
@@ -725,7 +722,7 @@ async function InsertDmsBatchWip(socket) {
); );
WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doTransBatchWIPAsync response.`); WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doTransBatchWIPAsync response.`);
CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate);
const BatchWipResult = result && result.return; const BatchWipResult = result?.return;
return BatchWipResult; return BatchWipResult;
} catch (error) { } catch (error) {
WsLogger.createLogEvent(socket, "ERROR", `Error in InsertDmsBatchWip - ${error}`); WsLogger.createLogEvent(socket, "ERROR", `Error in InsertDmsBatchWip - ${error}`);
@@ -743,9 +740,9 @@ async function GenerateTransWips(socket) {
acct: alloc.profitCenter.dms_acctnumber, acct: alloc.profitCenter.dms_acctnumber,
cntl: cntl:
alloc.profitCenter.dms_control_override && alloc.profitCenter.dms_control_override &&
alloc.profitCenter.dms_control_override !== null && alloc.profitCenter.dms_control_override !== null &&
alloc.profitCenter.dms_control_override !== undefined && alloc.profitCenter.dms_control_override !== undefined &&
alloc.profitCenter.dms_control_override?.trim() !== "" alloc.profitCenter.dms_control_override?.trim() !== ""
? alloc.profitCenter.dms_control_override ? alloc.profitCenter.dms_control_override
: socket.JobData.ro_number, : socket.JobData.ro_number,
cntl2: null, cntl2: null,
@@ -766,9 +763,9 @@ async function GenerateTransWips(socket) {
acct: alloc.costCenter.dms_acctnumber, acct: alloc.costCenter.dms_acctnumber,
cntl: cntl:
alloc.costCenter.dms_control_override && alloc.costCenter.dms_control_override &&
alloc.costCenter.dms_control_override !== null && alloc.costCenter.dms_control_override !== null &&
alloc.costCenter.dms_control_override !== undefined && alloc.costCenter.dms_control_override !== undefined &&
alloc.costCenter.dms_control_override?.trim() !== "" alloc.costCenter.dms_control_override?.trim() !== ""
? alloc.costCenter.dms_control_override ? alloc.costCenter.dms_control_override
: socket.JobData.ro_number, : socket.JobData.ro_number,
cntl2: null, cntl2: null,
@@ -786,9 +783,9 @@ async function GenerateTransWips(socket) {
acct: alloc.costCenter.dms_wip_acctnumber, acct: alloc.costCenter.dms_wip_acctnumber,
cntl: cntl:
alloc.costCenter.dms_control_override && alloc.costCenter.dms_control_override &&
alloc.costCenter.dms_control_override !== null && alloc.costCenter.dms_control_override !== null &&
alloc.costCenter.dms_control_override !== undefined && alloc.costCenter.dms_control_override !== undefined &&
alloc.costCenter.dms_control_override?.trim() !== "" alloc.costCenter.dms_control_override?.trim() !== ""
? alloc.costCenter.dms_control_override ? alloc.costCenter.dms_control_override
: socket.JobData.ro_number, : socket.JobData.ro_number,
cntl2: null, cntl2: null,
@@ -827,9 +824,9 @@ async function GenerateTransWips(socket) {
acct: alloc.profitCenter.dms_acctnumber, acct: alloc.profitCenter.dms_acctnumber,
cntl: cntl:
alloc.profitCenter.dms_control_override && alloc.profitCenter.dms_control_override &&
alloc.profitCenter.dms_control_override !== null && alloc.profitCenter.dms_control_override !== null &&
alloc.profitCenter.dms_control_override !== undefined && alloc.profitCenter.dms_control_override !== undefined &&
alloc.profitCenter.dms_control_override?.trim() !== "" alloc.profitCenter.dms_control_override?.trim() !== ""
? alloc.profitCenter.dms_control_override ? alloc.profitCenter.dms_control_override
: socket.JobData.ro_number, : socket.JobData.ro_number,
cntl2: null, cntl2: null,
@@ -889,7 +886,7 @@ async function PostDmsBatchWip(socket) {
); );
WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync response.`); WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync response.`);
// CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); // CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate);
const PostResult = result && result.return; const PostResult = result?.return;
return PostResult; return PostResult;
} catch (error) { } catch (error) {
WsLogger.createLogEvent(socket, "ERROR", `Error in PostDmsBatchWip - ${error}`); WsLogger.createLogEvent(socket, "ERROR", `Error in PostDmsBatchWip - ${error}`);
@@ -918,7 +915,7 @@ async function QueryDmsErrWip(socket) {
); );
WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doErrWIPAsync response.`); WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doErrWIPAsync response.`);
CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate);
const PostResult = result && result.return; const PostResult = result?.return;
return PostResult; return PostResult;
} catch (error) { } catch (error) {
WsLogger.createLogEvent(socket, "ERROR", `Error in QueryDmsErrWip - ${error}`); WsLogger.createLogEvent(socket, "ERROR", `Error in QueryDmsErrWip - ${error}`);
@@ -949,7 +946,7 @@ async function DeleteDmsWip(socket) {
); );
WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync response.`); WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync response.`);
CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate);
const PostResult = result && result.return; const PostResult = result?.return;
return PostResult; return PostResult;
} catch (error) { } catch (error) {
WsLogger.createLogEvent(socket, "ERROR", `Error in PostDmsBatchWip - ${error}`); WsLogger.createLogEvent(socket, "ERROR", `Error in PostDmsBatchWip - ${error}`);
@@ -960,8 +957,11 @@ async function DeleteDmsWip(socket) {
async function MarkJobExported(socket, jobid) { async function MarkJobExported(socket, jobid) {
WsLogger.createLogEvent(socket, "DEBUG", `Marking job as exported for id ${jobid}`); WsLogger.createLogEvent(socket, "DEBUG", `Marking job as exported for id ${jobid}`);
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); 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 const result = await client
.setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .setHeaders({ Authorization: `Bearer ${currentToken}` })
.request(queries.MARK_JOB_EXPORTED, { .request(queries.MARK_JOB_EXPORTED, {
jobId: jobid, jobId: jobid,
job: { job: {
@@ -987,8 +987,11 @@ async function MarkJobExported(socket, jobid) {
async function InsertFailedExportLog(socket, error) { async function InsertFailedExportLog(socket, error) {
try { try {
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); 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 const result = await client
.setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .setHeaders({ Authorization: `Bearer ${currentToken}` })
.request(queries.INSERT_EXPORT_LOG, { .request(queries.INSERT_EXPORT_LOG, {
log: { log: {
bodyshopid: socket.JobData.bodyshop.id, bodyshopid: socket.JobData.bodyshop.id,

View File

@@ -29,17 +29,20 @@ function handleFortellisApiError(socket, error, functionName, additionalDetails
functionName, functionName,
...additionalDetails ...additionalDetails
}); });
CreateFortellisLogEvent(socket, "DEBUG", `${functionName} failed. , ${JSON.stringify({ CreateFortellisLogEvent(
reqId: error.reqId, socket,
url: error.url, "DEBUG",
apiName: error.apiName, `${functionName} failed. , ${JSON.stringify({
errorData: error.errorData, reqId: error.reqId,
errorStatus: error.errorStatus, url: error.url,
errorStatusText: error.errorStatusText, apiName: error.apiName,
functionName, errorData: error.errorData,
...additionalDetails errorStatus: error.errorStatus,
})}`); errorStatusText: error.errorStatusText,
functionName,
...additionalDetails
})}`
);
} else { } else {
CreateFortellisLogEvent(socket, "ERROR", `Error in ${functionName} - ${error.message}`, { CreateFortellisLogEvent(socket, "ERROR", `Error in ${functionName} - ${error.message}`, {
error: error.message, error: error.message,
@@ -50,13 +53,7 @@ function handleFortellisApiError(socket, error, functionName, additionalDetails
} }
} }
async function FortellisJobExport({ async function FortellisJobExport({ socket, redisHelpers, txEnvelope, jobid }) {
socket,
redisHelpers,
ioHelpers: { getBodyshopRoom, getBodyshopConversationRoom },
txEnvelope,
jobid
}) {
const { const {
// setSessionData, // setSessionData,
// getSessionData, // getSessionData,
@@ -64,7 +61,7 @@ async function FortellisJobExport({
// removeUserSocketMapping, // removeUserSocketMapping,
// refreshUserSocketTTL, // refreshUserSocketTTL,
// getUserSocketMappingByBodyshop, // getUserSocketMappingByBodyshop,
setSessionTransactionData, setSessionTransactionData
// getSessionTransactionData, // getSessionTransactionData,
// clearSessionTransactionData // clearSessionTransactionData
} = redisHelpers; } = redisHelpers;
@@ -78,47 +75,78 @@ async function FortellisJobExport({
defaultFortellisTTL defaultFortellisTTL
); );
const JobData = await QueryJobData({ socket, jobid }); //TODO: Need to remove unnecessary stuff here to reduce the payload. //TODO: Need to remove unnecessary stuff here to reduce the payload.
await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.JobData, JobData, defaultFortellisTTL); 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}`); CreateFortellisLogEvent(socket, "DEBUG", `{1} Begin Calculate DMS Vehicle ID using VIN: ${JobData.v_vin}`);
const DMSVid = (await CalculateDmsVid({ socket, JobData, redisHelpers }))[0]; 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; let DMSVehCustomer;
if (!DMSVid.newId) { if (!DMSVid.newId) {
CreateFortellisLogEvent( CreateFortellisLogEvent(socket, "DEBUG", `{2.1} Querying the Vehicle using the DMSVid: ${DMSVid.vehiclesVehId}`);
socket,
"DEBUG",
`{2.1} Querying the Vehicle using the DMSVid: ${DMSVid.vehiclesVehId}`
);
const DMSVeh = await QueryDmsVehicleById({ socket, redisHelpers, JobData, DMSVid }); 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 = 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( CreateFortellisLogEvent(
socket, socket,
"DEBUG", "DEBUG",
`{2.2} Querying the Customer using the ID from DMSVeh: ${DMSVehCustomerFromVehicle.id.value}` `{2.2} Querying the Customer using the ID from DMSVeh: ${DMSVehCustomerFromVehicle.id.value}`
); );
DMSVehCustomer = await QueryDmsCustomerById({ socket, redisHelpers, JobData, CustomerId: DMSVehCustomerFromVehicle.id.value }); DMSVehCustomer = await QueryDmsCustomerById({
await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSVehCustomer, DMSVehCustomer, defaultFortellisTTL); 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.`); CreateFortellisLogEvent(socket, "DEBUG", `{2.3} Querying the Customer using the name.`);
const DMSCustList = await QueryDmsCustomerByName({ socket, redisHelpers, JobData }); 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", [ socket.emit("fortellis-select-customer", [
...(DMSVehCustomer ? [{ ...DMSVehCustomer, vinOwner: true }] : []), ...(DMSVehCustomer ? [{ ...DMSVehCustomer, vinOwner: true }] : []),
...DMSCustList ...DMSCustList
]); ]);
} catch (error) { } catch (error) {
CreateFortellisLogEvent(socket, "ERROR", `Error in FortellisJobExport - ${error} `, { CreateFortellisLogEvent(socket, "ERROR", `Error in FortellisJobExport - ${error} `, {
error: error.message, error: error.message,
@@ -127,10 +155,7 @@ async function FortellisJobExport({
} }
} }
async function FortellisSelectedCustomer({ socket, redisHelpers, selectedCustomerId, jobid }) {
async function FortellisSelectedCustomer({ socket, redisHelpers, ioHelpers, selectedCustomerId, jobid }) {
const { const {
// setSessionData, // setSessionData,
// getSessionData, // getSessionData,
@@ -139,93 +164,117 @@ async function FortellisSelectedCustomer({ socket, redisHelpers, ioHelpers, sele
// refreshUserSocketTTL, // refreshUserSocketTTL,
// getUserSocketMappingByBodyshop, // getUserSocketMappingByBodyshop,
setSessionTransactionData, setSessionTransactionData,
getSessionTransactionData, getSessionTransactionData
//clearSessionTransactionData //clearSessionTransactionData
} = redisHelpers; } = 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 JobData = await getSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.JobData);
const txEnvelope = await getSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.txEnvelope); const txEnvelope = await getSessionTransactionData(
const DMSVid = await redisHelpers.getSessionTransactionData(socket.id, getTransactionType(JobData.id), FortellisCacheEnums.DMSVid); socket.id,
getTransactionType(jobid),
FortellisCacheEnums.txEnvelope
);
const DMSVid = await redisHelpers.getSessionTransactionData(
socket.id,
getTransactionType(JobData.id),
FortellisCacheEnums.DMSVid
);
try { try {
let DMSCust; let DMSCust;
if (selectedCustomerId) { if (selectedCustomerId) {
CreateFortellisLogEvent( CreateFortellisLogEvent(socket, "DEBUG", `{3.1} Querying the Customer using Customer ID: ${selectedCustomerId}`);
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. 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); await setSessionTransactionData(
} else { socket.id,
CreateFortellisLogEvent( getTransactionType(jobid),
socket, FortellisCacheEnums.DMSCust,
"DEBUG", DMSCust,
`{3.2} Creating new customer.` defaultFortellisTTL
); );
} else {
CreateFortellisLogEvent(socket, "DEBUG", `{3.2} Creating new customer.`);
const DMSCustomerInsertResponse = await InsertDmsCustomer({ socket, redisHelpers, JobData }); const DMSCustomerInsertResponse = await InsertDmsCustomer({ socket, redisHelpers, JobData });
DMSCust = { customerId: DMSCustomerInsertResponse.data } DMSCust = { customerId: DMSCustomerInsertResponse.data };
await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSCust, DMSCust, defaultFortellisTTL); await setSessionTransactionData(
socket.id,
getTransactionType(jobid),
FortellisCacheEnums.DMSCust,
DMSCust,
defaultFortellisTTL
);
} }
let DMSVeh; let DMSVeh;
if (DMSVid.newId) { if (DMSVid.newId) {
CreateFortellisLogEvent( CreateFortellisLogEvent(socket, "DEBUG", `{4.1} Inserting new vehicle with ID: ID ${DMSVid.vehiclesVehId}`);
socket,
"DEBUG",
`{4.1} Inserting new vehicle with ID: ID ${DMSVid.vehiclesVehId}`
);
DMSVeh = await InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMSVid, DMSCust }); DMSVeh = await InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMSVid, DMSCust });
} else { } else {
CreateFortellisLogEvent( CreateFortellisLogEvent(socket, "DEBUG", `{4.2} Querying Existing Vehicle using ID ${DMSVid.vehiclesVehId}`);
socket,
"DEBUG",
`{4.2} Querying Existing Vehicle using ID ${DMSVid.vehiclesVehId}`
);
DMSVeh = await QueryDmsVehicleById({ socket, redisHelpers, JobData, DMSVid }); DMSVeh = await QueryDmsVehicleById({ socket, redisHelpers, JobData, DMSVid });
CreateFortellisLogEvent( CreateFortellisLogEvent(socket, "DEBUG", `{4.3} Updating Existing Vehicle to associate to owner.`);
DMSVeh = await UpdateDmsVehicle({
socket, socket,
"DEBUG", redisHelpers,
`{4.3} Updating Existing Vehicle to associate to owner.` JobData,
); DMSVeh,
DMSVeh = await UpdateDmsVehicle({ socket, redisHelpers, JobData, DMSVeh, DMSCust, selectedCustomerId, txEnvelope }); DMSCust,
await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSVeh, DMSVeh, defaultFortellisTTL);//TODO: This should be immutable probably.F 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 }); // 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);
CreateFortellisLogEvent( CreateFortellisLogEvent(socket, "DEBUG", `{5} Creating Transaction header with Dms Start WIP`);
socket,
"DEBUG",
`{5} Creating Transaction header with Dms Start WIP`
);
const DMSTransHeader = await InsertDmsStartWip({ socket, redisHelpers, JobData }); const DMSTransHeader = await InsertDmsStartWip({ socket, redisHelpers, JobData });
await setSessionTransactionData(socket.id, getTransactionType(jobid), FortellisCacheEnums.DMSTransHeader, DMSTransHeader, defaultFortellisTTL); await setSessionTransactionData(
socket.id,
CreateFortellisLogEvent( getTransactionType(jobid),
socket, FortellisCacheEnums.DMSTransHeader,
"DEBUG", DMSTransHeader,
`{5.1} Creating Transaction with ID ${DMSTransHeader.transID}` defaultFortellisTTL
); );
CreateFortellisLogEvent(socket, "DEBUG", `{5.1} Creating Transaction with ID ${DMSTransHeader.transID}`);
const DMSBatchTxn = await InsertDmsBatchWip({ socket, redisHelpers, JobData }); 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") { if (DMSBatchTxn.rtnCode === "0") {
CreateFortellisLogEvent( CreateFortellisLogEvent(socket, "DEBUG", `{6} Attempting to post Transaction with ID ${DMSTransHeader.transID}`);
socket,
"DEBUG",
`{6} Attempting to post Transaction with ID ${DMSTransHeader.transID}`
);
const DmsBatchTxnPost = await PostDmsBatchWip({ socket, redisHelpers, JobData }); 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 //something
CreateFortellisLogEvent(socket, "DEBUG", `{6} Successfully posted transaction to DMS.`); 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.`); CreateFortellisLogEvent(socket, "DEBUG", `{5} Updating Service Vehicle History.`);
const DMSVehHistory = await InsertServiceVehicleHistory({ socket, redisHelpers, JobData }); 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); socket.emit("export-success", JobData.id);
} else { } else {
//Get the error code //Get the error code
CreateFortellisLogEvent( CreateFortellisLogEvent(socket, "DEBUG", `{6.1} Getting errors for Transaction ID ${DMSTransHeader.transID}`);
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); // socket.DmsError = await QueryDmsErrWip(socket);
// //Delete the transaction // //Delete the transaction
// CdkBase.createLogEvent(socket, "DEBUG", `{ 6.2 } Deleting Transaction ID ${ socket.DMSTransHeader.transID } `); // CdkBase.createLogEvent(socket, "DEBUG", `{ 6.2 } Deleting Transaction ID ${ socket.DMSTransHeader.transID } `);
@@ -265,7 +318,6 @@ async function FortellisSelectedCustomer({ socket, redisHelpers, ioHelpers, sele
"ERROR", "ERROR",
`DMS Batch Return code was not successful: ${DMSBatchTxn.rtnCode} - ${DMSBatchTxn.sendline}` `DMS Batch Return code was not successful: ${DMSBatchTxn.rtnCode} - ${DMSBatchTxn.sendline}`
); );
} }
} catch (error) { } catch (error) {
// CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkSelectedCustomer.${ error } `); // CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkSelectedCustomer.${ error } `);
@@ -277,7 +329,6 @@ async function FortellisSelectedCustomer({ socket, redisHelpers, ioHelpers, sele
} finally { } finally {
//Ensure we always insert logEvents //Ensure we always insert logEvents
//GQL to insert logevents. //GQL to insert logevents.
//CdkBase.createLogEvent(socket, "DEBUG", `Capturing log events to database.`); //CdkBase.createLogEvent(socket, "DEBUG", `Capturing log events to database.`);
} }
} }
@@ -301,8 +352,7 @@ async function CalculateDmsVid({ socket, JobData, redisHelpers }) {
redisHelpers, redisHelpers,
socket, socket,
jobid: JobData.id, jobid: JobData.id,
body: {}, body: {}
}); });
return result; return result;
} catch (error) { } catch (error) {
@@ -323,7 +373,7 @@ async function QueryDmsVehicleById({ socket, redisHelpers, JobData, DMSVid }) {
redisHelpers, redisHelpers,
socket, socket,
jobid: JobData.id, jobid: JobData.id,
body: {}, body: {}
}); });
return result; return result;
} catch (error) { } catch (error) {
@@ -344,8 +394,7 @@ async function QueryDmsCustomerById({ socket, redisHelpers, JobData, CustomerId
redisHelpers, redisHelpers,
socket, socket,
jobid: JobData.id, jobid: JobData.id,
body: {}, body: {}
}); });
return result.data; return result.data;
} catch (error) { } catch (error) {
@@ -361,14 +410,12 @@ async function QueryDmsCustomerByName({ socket, redisHelpers, JobData }) {
const ownerName = const ownerName =
JobData.ownr_co_nm && JobData.ownr_co_nm.trim() !== "" JobData.ownr_co_nm && JobData.ownr_co_nm.trim() !== ""
? [["lastName", JobData.ownr_co_nm.replace(replaceSpecialRegex, "")]] ? [["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( CreateFortellisLogEvent(socket, "DEBUG", `Begin query DMS Customer by Name using ${JSON.stringify(ownerName)} `);
socket,
"DEBUG",
`Begin query DMS Customer by Name using ${JSON.stringify(ownerName)
} `
);
try { try {
const result = await MakeFortellisCall({ const result = await MakeFortellisCall({
@@ -378,8 +425,7 @@ async function QueryDmsCustomerByName({ socket, redisHelpers, JobData }) {
redisHelpers, redisHelpers,
socket, socket,
jobid: JobData.id, jobid: JobData.id,
body: {}, body: {}
}); });
return result.data; return result.data;
} catch (error) { } catch (error) {
@@ -400,33 +446,28 @@ async function InsertDmsCustomer({ socket, redisHelpers, JobData }) {
socket, socket,
jobid: JobData.id, jobid: JobData.id,
body: { body: {
"customerType": "INDIVIDUAL", customerType: "INDIVIDUAL",
"customerName": { customerName: {
//"suffix": "Mr.", //"suffix": "Mr.",
"firstName": JobData.ownr_fn && JobData.ownr_fn.replace(replaceSpecialRegex, "").toUpperCase(), firstName: JobData.ownr_fn && JobData.ownr_fn.replace(replaceSpecialRegex, "").toUpperCase(),
//"middleName": "", //"middleName": "",
"lastName": JobData.ownr_ln && JobData.ownr_ln.replace(replaceSpecialRegex, "").toUpperCase(), lastName: JobData.ownr_ln && JobData.ownr_ln.replace(replaceSpecialRegex, "").toUpperCase()
//"title": "", //"title": "",
//"nickName": "" //"nickName": ""
}, },
"companyName": JobData.ownr_co_nm && JobData.ownr_co_nm.replace(replaceSpecialRegex, "").toUpperCase(), companyName: JobData.ownr_co_nm && JobData.ownr_co_nm.replace(replaceSpecialRegex, "").toUpperCase(),
"postalAddress": { postalAddress: {
"addressLine1": JobData.ownr_addr1?.replace(replaceSpecialRegex, "").trim(), addressLine1: JobData.ownr_addr1?.replace(replaceSpecialRegex, "").trim(),
"addressLine2": JobData.ownr_addr2?.replace(replaceSpecialRegex, "").trim(), addressLine2: JobData.ownr_addr2?.replace(replaceSpecialRegex, "").trim(),
"city": JobData.ownr_city?.replace(replaceSpecialRegex, "").trim(), city: JobData.ownr_city?.replace(replaceSpecialRegex, "").trim(),
"state": JobData.ownr_state?.replace(replaceSpecialRegex, "").trim(), state: JobData.ownr_state?.replace(replaceSpecialRegex, "").trim(),
"postalCode": InstanceMgr({ postalCode: InstanceMgr({
imex: imex: JobData.ownr_zip && JobData.ownr_zip.toUpperCase().replace(/\W/g, "").replace(/(...)/, "$1 "),
JobData.ownr_zip &&
JobData.ownr_zip
.toUpperCase()
.replace(/\W/g, "")
.replace(/(...)/, "$1 "),
rome: JobData.ownr_zip rome: JobData.ownr_zip
}), }),
//"county": JobData.ownr_county?.trim(), //"county": JobData.ownr_county?.trim(),
"country": JobData.ownr_ctry?.replace(replaceSpecialRegex, "").trim(), country: JobData.ownr_ctry?.replace(replaceSpecialRegex, "").trim(),
"province": JobData.ownr_st?.replace(replaceSpecialRegex, "").trim(), province: JobData.ownr_st?.replace(replaceSpecialRegex, "").trim()
//"territory": "" //"territory": ""
}, },
// "birthDate": { // "birthDate": {
@@ -436,12 +477,12 @@ async function InsertDmsCustomer({ socket, redisHelpers, JobData }) {
// }, // },
//"gender": "M", //"gender": "M",
//"language": "English", //"language": "English",
"contactMethods": { contactMethods: {
"phones": [ phones: [
{ {
//"uuid": "", //"uuid": "",
"number": JobData.ownr_ph1?.replace(replaceSpecialRegex, ""), number: JobData.ownr_ph1?.replace(replaceSpecialRegex, ""),
"type": "HOME", type: "HOME"
// "doNotCallIndicator": true, // "doNotCallIndicator": true,
// "doNotCallIndicatorDate": `null, // "doNotCallIndicatorDate": `null,
// "doNotCallRegistrySource": "", // "doNotCallRegistrySource": "",
@@ -454,7 +495,7 @@ async function InsertDmsCustomer({ socket, redisHelpers, JobData }) {
// "optInRequestedDate": null, // "optInRequestedDate": null,
// "preferredDay": "", // "preferredDay": "",
// "preferredTime": "" // "preferredTime": ""
}, }
// { // {
// "uuid": "", // "uuid": "",
// "number": "6666666666", // "number": "6666666666",
@@ -473,20 +514,22 @@ async function InsertDmsCustomer({ socket, redisHelpers, JobData }) {
// "preferredTime": "" // "preferredTime": ""
// } // }
], ],
"emailAddresses": [ emailAddresses: [
...(!_.isEmpty(JobData.ownr_ea)
...!_.isEmpty(JobData.ownr_ea) ? ? [
[{ {
//"uuid": "", //"uuid": "",
"address": JobData.ownr_ea, address: JobData.ownr_ea,
"type": "PERSONAL", type: "PERSONAL"
// "doNotEmailSource": "", // "doNotEmailSource": "",
// "doNotEmail": false, // "doNotEmail": false,
// "isPreferred": true, // "isPreferred": true,
// "transactionEmailNotificationOptIn": false, // "transactionEmailNotificationOptIn": false,
// "optInRequestDate": null, // "optInRequestDate": null,
// "optInDate": null // "optInDate": null
}] : [], }
]
: [])
// { // {
// "uuid": "", // "uuid": "",
// "address": "jilldoe@test.com", // "address": "jilldoe@test.com",
@@ -499,7 +542,7 @@ async function InsertDmsCustomer({ socket, redisHelpers, JobData }) {
// "optInDate": null // "optInDate": null
// } // }
] ]
}, }
// // "doNotContact": false, // // "doNotContact": false,
// // "optOutDate": "", // // "optOutDate": "",
// // "optOutTime": "", // // "optOutTime": "",
@@ -581,8 +624,7 @@ async function InsertDmsCustomer({ socket, redisHelpers, JobData }) {
// "dealerField": "Custom dealer field value 3" // "dealerField": "Custom dealer field value 3"
// } // }
// ] // ]
}, }
}); });
return result; return result;
} catch (error) { } catch (error) {
@@ -600,7 +642,6 @@ async function InsertDmsCustomer({ socket, redisHelpers, JobData }) {
async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMSVid, DMSCust }) { async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMSVid, DMSCust }) {
try { try {
const result = await MakeFortellisCall({ const result = await MakeFortellisCall({
...FortellisActions.InsertVehicle, ...FortellisActions.InsertVehicle,
requestSearchParams: {}, requestSearchParams: {},
@@ -609,8 +650,8 @@ async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMS
socket, socket,
jobid: JobData.id, jobid: JobData.id,
body: { body: {
"dealer": { dealer: {
"company": JobData.bodyshop.cdk_configuration.srcco || "77", company: JobData.bodyshop.cdk_configuration.srcco || "77",
// "dealNumber": "", // "dealNumber": "",
// "dealerAssignedNumber": "82268", // "dealerAssignedNumber": "82268",
// "dealerDefined1": "2WDSP", // "dealerDefined1": "2WDSP",
@@ -627,12 +668,12 @@ async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMS
txEnvelope.dms_unsold === true txEnvelope.dms_unsold === true
? "" ? ""
: moment(txEnvelope.inservicedate) : moment(txEnvelope.inservicedate)
//.tz(JobData.bodyshop.timezone) //.tz(JobData.bodyshop.timezone)
.startOf("day") .startOf("day")
.toISOString() .toISOString()
}), }),
//"lastServiceDate": "2011-11-23", //"lastServiceDate": "2011-11-23",
"vehicleId": DMSVid.vehiclesVehId, vehicleId: DMSVid.vehiclesVehId
// "vehicleLocation": "", // "vehicleLocation": "",
// "vehicleSoldDate": "2021-04-06", // "vehicleSoldDate": "2021-04-06",
// "wholesaleVehicleInd": false // "wholesaleVehicleInd": false
@@ -656,7 +697,7 @@ async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMS
// "vehicleOrderPriority": "", // "vehicleOrderPriority": "",
// "vehicleOrderType": "TRE RETAIL - STOCK" // "vehicleOrderType": "TRE RETAIL - STOCK"
// }, // },
"vehicle": { vehicle: {
// "axleCode": "GU6/3.42 REAR AXLE RATIO", // "axleCode": "GU6/3.42 REAR AXLE RATIO",
// "axleCount": 2, // "axleCount": 2,
// "bodyStyle": "PU", // "bodyStyle": "PU",
@@ -671,8 +712,8 @@ async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMS
txEnvelope.dms_unsold === true txEnvelope.dms_unsold === true
? "" ? ""
: moment() : moment()
// .tz(JobData.bodyshop.timezone) // .tz(JobData.bodyshop.timezone)
.format("YYYY-MM-DD"), .format("YYYY-MM-DD"),
// "deliveryMileage": 4, // "deliveryMileage": 4,
// "doorsQuantity": 4, // "doorsQuantity": 4,
// "engineNumber": "", // "engineNumber": "",
@@ -689,8 +730,8 @@ async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMS
: String(JobData.plate_no).replace(/([^\w]|_)/g, "").length === 0 : String(JobData.plate_no).replace(/([^\w]|_)/g, "").length === 0
? null ? null
: String(JobData.plate_no) : String(JobData.plate_no)
.replace(/([^\w]|_)/g, "") .replace(/([^\w]|_)/g, "")
.toUpperCase(), .toUpperCase(),
make: txEnvelope.dms_make, make: txEnvelope.dms_make,
// "model": "CC10753", // "model": "CC10753",
modelAbrev: txEnvelope.dms_model, modelAbrev: txEnvelope.dms_model,
@@ -781,18 +822,16 @@ async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMS
// "warrantyExpDate": "2015-01-12", // "warrantyExpDate": "2015-01-12",
// "wheelbase": "" // "wheelbase": ""
}, },
"owners": [ owners: [
{ {
"id": { id: {
assigningPartyId: "CURRENT", assigningPartyId: "CURRENT",
value: DMSCust.customerId value: DMSCust.customerId
}, }
} }
], ]
//"inventoryAccount": "237" //"inventoryAccount": "237"
}, }
}); });
return result.data; return result.data;
} catch (error) { } catch (error) {
@@ -808,18 +847,14 @@ async function InsertDmsVehicle({ socket, redisHelpers, JobData, txEnvelope, DMS
async function UpdateDmsVehicle({ socket, redisHelpers, JobData, DMSVeh, DMSCust, selectedCustomerId, txEnvelope }) { async function UpdateDmsVehicle({ socket, redisHelpers, JobData, DMSVeh, DMSCust, selectedCustomerId, txEnvelope }) {
try { try {
let ids = []; let ids = [];
//if it's a generic customer, don't update the vehicle owners. //if it's a generic customer, don't update the vehicle owners.
if (selectedCustomerId === JobData.bodyshop.cdk_configuration.generic_customer_number) { if (selectedCustomerId === JobData.bodyshop.cdk_configuration.generic_customer_number) {
ids = DMSVeh && DMSVeh.owners && DMSVeh.owners; ids = DMSVeh?.owners && DMSVeh.owners;
} else { } else {
const existingOwnerinVeh = const existingOwnerinVeh = DMSVeh?.owners && DMSVeh.owners.find((o) => o.id.value === DMSCust.customerId);
DMSVeh &&
DMSVeh.owners &&
DMSVeh.owners.find((o) => o.id.value === DMSCust.customerId);
if (existingOwnerinVeh) { if (existingOwnerinVeh) {
ids = DMSVeh.owners.map((o) => { ids = DMSVeh.owners.map((o) => {
@@ -831,10 +866,7 @@ async function UpdateDmsVehicle({ socket, redisHelpers, JobData, DMSVeh, DMSCust
}; };
}); });
} else { } else {
const oldOwner = const oldOwner = DMSVeh?.owners && DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT");
DMSVeh &&
DMSVeh.owners &&
DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT");
ids = [ ids = [
{ {
@@ -845,13 +877,13 @@ async function UpdateDmsVehicle({ socket, redisHelpers, JobData, DMSVeh, DMSCust
}, },
...(oldOwner ...(oldOwner
? [ ? [
{ {
id: { id: {
assigningPartyId: "PREVIOUS", assigningPartyId: "PREVIOUS",
value: oldOwner.id value: oldOwner.id
}
} }
} ]
]
: []) : [])
]; ];
} }
@@ -864,7 +896,6 @@ async function UpdateDmsVehicle({ socket, redisHelpers, JobData, DMSVeh, DMSCust
delete DMSVehToSend.invoice; delete DMSVehToSend.invoice;
delete DMSVehToSend.inventoryAccount; delete DMSVehToSend.inventoryAccount;
const result = await MakeFortellisCall({ const result = await MakeFortellisCall({
...FortellisActions.UpdateVehicle, ...FortellisActions.UpdateVehicle,
requestSearchParams: {}, requestSearchParams: {},
@@ -882,28 +913,27 @@ async function UpdateDmsVehicle({ socket, redisHelpers, JobData, DMSVeh, DMSCust
txEnvelope.dms_unsold === true txEnvelope.dms_unsold === true
? "" ? ""
: moment(DMSVehToSend.dealer.inServiceDate || txEnvelope.inservicedate) : moment(DMSVehToSend.dealer.inServiceDate || txEnvelope.inservicedate)
// .tz(JobData.bodyshop.timezone) // .tz(JobData.bodyshop.timezone)
.toISOString() .toISOString()
}) })
}, },
vehicle: { vehicle: {
...DMSVehToSend.vehicle, ...DMSVehToSend.vehicle,
...(txEnvelope.dms_model_override ...(txEnvelope.dms_model_override
? { ? {
make: txEnvelope.dms_make, make: txEnvelope.dms_make,
modelAbrev: txEnvelope.dms_model modelAbrev: txEnvelope.dms_model
} }
: {}), : {}),
deliveryDate: deliveryDate:
txEnvelope.dms_unsold === true txEnvelope.dms_unsold === true
? "" ? ""
: moment(DMSVehToSend.vehicle.deliveryDate) : moment(DMSVehToSend.vehicle.deliveryDate)
//.tz(JobData.bodyshop.timezone) //.tz(JobData.bodyshop.timezone)
.toISOString() .toISOString()
}, },
owners: ids owners: ids
}, }
}); });
return result; return result;
} catch (error) { } 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 { try {
const txEnvelope = await redisHelpers.getSessionTransactionData(socket.id, getTransactionType(JobData.id), FortellisCacheEnums.txEnvelope); const txEnvelope = await redisHelpers.getSessionTransactionData(
const DMSVid = await redisHelpers.getSessionTransactionData(socket.id, getTransactionType(JobData.id), FortellisCacheEnums.DMSVid); socket.id,
getTransactionType(JobData.id),
FortellisCacheEnums.txEnvelope
);
const DMSVid = await redisHelpers.getSessionTransactionData(
socket.id,
getTransactionType(JobData.id),
FortellisCacheEnums.DMSVid
);
const result = await MakeFortellisCall({ const result = await MakeFortellisCall({
...FortellisActions.ServiceHistoryInsert, ...FortellisActions.ServiceHistoryInsert,
@@ -944,8 +980,7 @@ async function InsertServiceVehicleHistory({ socket, redisHelpers, JobData, }) {
cashierId: JobData.bodyshop.cdk_configuration.cashierid, cashierId: JobData.bodyshop.cdk_configuration.cashierid,
referenceNumber: JobData.bodyshop.cdk_configuration.cashierid referenceNumber: JobData.bodyshop.cdk_configuration.cashierid
} }
}, }
}); });
return result; return result;
} catch (error) { } catch (error) {
@@ -957,10 +992,13 @@ async function InsertServiceVehicleHistory({ socket, redisHelpers, JobData, }) {
} }
} }
async function InsertDmsStartWip({ socket, redisHelpers, JobData }) { async function InsertDmsStartWip({ socket, redisHelpers, JobData }) {
try { 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({ const result = await MakeFortellisCall({
...FortellisActions.StartWip, ...FortellisActions.StartWip,
@@ -969,21 +1007,20 @@ async function InsertDmsStartWip({ socket, redisHelpers, JobData }) {
socket, socket,
jobid: JobData.id, jobid: JobData.id,
body: { body: {
"acctgDate": moment().tz(JobData.bodyshop.timezone).format("YYYY-MM-DD"), acctgDate: moment().tz(JobData.bodyshop.timezone).format("YYYY-MM-DD"),
"desc": txEnvelope.story && txEnvelope.story.replace(replaceSpecialRegex, ""), desc: txEnvelope.story && txEnvelope.story.replace(replaceSpecialRegex, ""),
"docType": "10", docType: "10",
"m13Flag": "0", m13Flag: "0",
"refer": JobData.ro_number, refer: JobData.ro_number,
// "rtnCode": "", // "rtnCode": "",
// "sendline": "", // "sendline": "",
// "groupName": "", // "groupName": "",
"srcCo": JobData.bodyshop.cdk_configuration.srcco, srcCo: JobData.bodyshop.cdk_configuration.srcco,
"srcJrnl": txEnvelope.journal, srcJrnl: txEnvelope.journal,
"transID": "", transID: "",
"userID": JobData.bodyshop.cdk_configuration.cashierid, userID: JobData.bodyshop.cdk_configuration.cashierid,
"userName": "BSMS" userName: "BSMS"
}, }
}); });
return result; return result;
} catch (error) { } catch (error) {
@@ -1016,9 +1053,15 @@ async function InsertDmsBatchWip({ socket, redisHelpers, JobData }) {
} }
async function GenerateTransWips({ 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 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) => { allocations.forEach((alloc) => {
//Add the sale item from each allocation. //Add the sale item from each allocation.
@@ -1027,9 +1070,9 @@ async function GenerateTransWips({ socket, redisHelpers, JobData }) {
acct: alloc.profitCenter.dms_acctnumber, acct: alloc.profitCenter.dms_acctnumber,
cntl: cntl:
alloc.profitCenter.dms_control_override && alloc.profitCenter.dms_control_override &&
alloc.profitCenter.dms_control_override !== null && alloc.profitCenter.dms_control_override !== null &&
alloc.profitCenter.dms_control_override !== undefined && alloc.profitCenter.dms_control_override !== undefined &&
alloc.profitCenter.dms_control_override?.trim() !== "" alloc.profitCenter.dms_control_override?.trim() !== ""
? alloc.profitCenter.dms_control_override ? alloc.profitCenter.dms_control_override
: JobData.ro_number, : JobData.ro_number,
cntl2: null, cntl2: null,
@@ -1050,9 +1093,9 @@ async function GenerateTransWips({ socket, redisHelpers, JobData }) {
acct: alloc.costCenter.dms_acctnumber, acct: alloc.costCenter.dms_acctnumber,
cntl: cntl:
alloc.costCenter.dms_control_override && alloc.costCenter.dms_control_override &&
alloc.costCenter.dms_control_override !== null && alloc.costCenter.dms_control_override !== null &&
alloc.costCenter.dms_control_override !== undefined && alloc.costCenter.dms_control_override !== undefined &&
alloc.costCenter.dms_control_override?.trim() !== "" alloc.costCenter.dms_control_override?.trim() !== ""
? alloc.costCenter.dms_control_override ? alloc.costCenter.dms_control_override
: JobData.ro_number, : JobData.ro_number,
cntl2: null, cntl2: null,
@@ -1070,9 +1113,9 @@ async function GenerateTransWips({ socket, redisHelpers, JobData }) {
acct: alloc.costCenter.dms_wip_acctnumber, acct: alloc.costCenter.dms_wip_acctnumber,
cntl: cntl:
alloc.costCenter.dms_control_override && alloc.costCenter.dms_control_override &&
alloc.costCenter.dms_control_override !== null && alloc.costCenter.dms_control_override !== null &&
alloc.costCenter.dms_control_override !== undefined && alloc.costCenter.dms_control_override !== undefined &&
alloc.costCenter.dms_control_override?.trim() !== "" alloc.costCenter.dms_control_override?.trim() !== ""
? alloc.costCenter.dms_control_override ? alloc.costCenter.dms_control_override
: JobData.ro_number, : JobData.ro_number,
cntl2: null, cntl2: null,
@@ -1089,15 +1132,14 @@ async function GenerateTransWips({ socket, redisHelpers, JobData }) {
} }
if (alloc.tax) { if (alloc.tax) {
if (alloc.sale.getAmount() > 0) { if (alloc.sale.getAmount() > 0) {
const item2 = { const item2 = {
acct: alloc.profitCenter.dms_acctnumber, acct: alloc.profitCenter.dms_acctnumber,
cntl: cntl:
alloc.profitCenter.dms_control_override && alloc.profitCenter.dms_control_override &&
alloc.profitCenter.dms_control_override !== null && alloc.profitCenter.dms_control_override !== null &&
alloc.profitCenter.dms_control_override !== undefined && alloc.profitCenter.dms_control_override !== undefined &&
alloc.profitCenter.dms_control_override?.trim() !== "" alloc.profitCenter.dms_control_override?.trim() !== ""
? alloc.profitCenter.dms_control_override ? alloc.profitCenter.dms_control_override
: JobData.ro_number, : JobData.ro_number,
cntl2: null, 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) => { txEnvelope.payers.forEach((payer) => {
const item = { const item = {
@@ -1131,7 +1177,13 @@ async function GenerateTransWips({ socket, redisHelpers, JobData }) {
wips.push(item); 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; return wips;
} }
@@ -1139,8 +1191,11 @@ async function GenerateTransWips({ socket, redisHelpers, JobData }) {
async function PostDmsBatchWip({ socket, redisHelpers, JobData }) { async function PostDmsBatchWip({ socket, redisHelpers, JobData }) {
let DMSTransHeader; let DMSTransHeader;
try { 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({ const result = await MakeFortellisCall({
...FortellisActions.PostBatchWip, ...FortellisActions.PostBatchWip,
@@ -1149,8 +1204,8 @@ async function PostDmsBatchWip({ socket, redisHelpers, JobData }) {
socket, socket,
jobid: JobData.id, jobid: JobData.id,
body: { body: {
"opCode": "P", opCode: "P",
"transID": DMSTransHeader.transID transID: DMSTransHeader.transID
} }
}); });
return result; return result;
@@ -1166,8 +1221,11 @@ async function PostDmsBatchWip({ socket, redisHelpers, JobData }) {
async function QueryDmsErrWip({ socket, redisHelpers, JobData }) { async function QueryDmsErrWip({ socket, redisHelpers, JobData }) {
let DMSTransHeader; let DMSTransHeader;
try { 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({ const result = await MakeFortellisCall({
...FortellisActions.QueryErrorWip, ...FortellisActions.QueryErrorWip,
@@ -1176,9 +1234,7 @@ async function QueryDmsErrWip({ socket, redisHelpers, JobData }) {
socket, socket,
jobid: JobData.id, jobid: JobData.id,
requestPathParams: DMSTransHeader.transID, requestPathParams: DMSTransHeader.transID,
body: { body: {}
}
}); });
return result; return result;
} catch (error) { } catch (error) {
@@ -1222,11 +1278,14 @@ async function QueryDmsErrWip({ socket, redisHelpers, JobData }) {
// } // }
async function MarkJobExported({ socket, jobid }) { async function MarkJobExported({ socket, jobid }) {
CreateFortellisLogEvent(socket, "ERROR", `Marking job as exported for id ${jobid}`); CreateFortellisLogEvent(socket, "ERROR", `Marking job as exported for id ${jobid}`);
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); 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 const result = await client
.setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .setHeaders({ Authorization: `Bearer ${currentToken}` })
.request(queries.MARK_JOB_EXPORTED, { .request(queries.MARK_JOB_EXPORTED, {
jobId: jobid, jobId: jobid,
job: { job: {
@@ -1252,8 +1311,11 @@ async function MarkJobExported({ socket, jobid }) {
async function InsertFailedExportLog({ socket, JobData, error }) { async function InsertFailedExportLog({ socket, JobData, error }) {
try { try {
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); 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 const result = await client
.setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .setHeaders({ Authorization: `Bearer ${currentToken}` })
.request(queries.INSERT_EXPORT_LOG, { .request(queries.INSERT_EXPORT_LOG, {
log: { log: {
bodyshopid: JobData.bodyshop.id, bodyshopid: JobData.bodyshop.id,
@@ -1266,7 +1328,10 @@ async function InsertFailedExportLog({ socket, JobData, error }) {
return result; return result;
} catch (error2) { } 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
});
} }
} }

View File

@@ -36,9 +36,11 @@ const redisSocketEvents = ({
} }
try { try {
const user = await admin.auth().verifyIdToken(token); const user = await admin.auth().verifyIdToken(token, true);
socket.user = user; socket.user = user;
socket.bodyshopId = bodyshopId; socket.bodyshopId = bodyshopId;
socket.data = socket.data || {};
socket.data.authToken = token;
await addUserSocketMapping(user.email, socket.id, bodyshopId); await addUserSocketMapping(user.email, socket.id, bodyshopId);
next(); next();
} catch (error) { } catch (error) {
@@ -69,6 +71,15 @@ const redisSocketEvents = ({
} }
socket.user = user; socket.user = user;
socket.bodyshopId = bodyshopId; 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); await refreshUserSocketTTL(user.email, bodyshopId);
socket.emit("token-updated", { success: true }); socket.emit("token-updated", { success: true });
} catch (error) { } catch (error) {

View File

@@ -9,7 +9,6 @@ const { PbsCalculateAllocationsAp, PbsExportAp } = require("../accounting/pbs/pb
const { createLogEvent } = require("./createLogEvent"); const { createLogEvent } = require("./createLogEvent");
function SetLegacyWebsocketHandlers(io) { function SetLegacyWebsocketHandlers(io) {
io.use(function (socket, next) { io.use(function (socket, next) {
try { try {
if (socket.handshake.auth.token) { if (socket.handshake.auth.token) {
@@ -53,6 +52,7 @@ function SetLegacyWebsocketHandlers(io) {
socket.on("cdk-export-job", (jobid) => { socket.on("cdk-export-job", (jobid) => {
CdkJobExport(socket, jobid); CdkJobExport(socket, jobid);
}); });
socket.on("cdk-selected-customer", (selectedCustomerId) => { socket.on("cdk-selected-customer", (selectedCustomerId) => {
createLogEvent(socket, "DEBUG", `User selected customer ID ${selectedCustomerId}`); createLogEvent(socket, "DEBUG", `User selected customer ID ${selectedCustomerId}`);
socket.selectedCustomerId = selectedCustomerId; socket.selectedCustomerId = selectedCustomerId;
@@ -116,7 +116,6 @@ function SetLegacyWebsocketHandlers(io) {
createLogEvent(socket, "DEBUG", `User disconnected.`); createLogEvent(socket, "DEBUG", `User disconnected.`);
}); });
}); });
} }
exports.SetLegacyWebsocketHandlers = SetLegacyWebsocketHandlers; exports.SetLegacyWebsocketHandlers = SetLegacyWebsocketHandlers;