diff --git a/server.js b/server.js index 2bb2bf5a8..1ddf2201a 100644 --- a/server.js +++ b/server.js @@ -38,7 +38,7 @@ const { registerCleanupTask, initializeCleanupManager } = require("./server/util const { loadEmailQueue } = require("./server/notifications/queues/emailQueue"); const { loadAppQueue } = require("./server/notifications/queues/appQueue"); - +const { SetLegacyWebsocketHandlers } = require("./server/web-sockets/web-socket"); const CLUSTER_RETRY_BASE_DELAY = 100; const CLUSTER_RETRY_MAX_DELAY = 5000; const CLUSTER_RETRY_JITTER = 100; @@ -324,6 +324,9 @@ const applySocketIO = async ({ server, app }) => { } }); + // Legacy Socket Events + SetLegacyWebsocketHandlers(io) + const api = { pubClient, io, @@ -387,8 +390,6 @@ const main = async () => { const redisHelpers = applyRedisHelpers({ pubClient, app, logger }); const ioHelpers = applyIOHelpers({ app, redisHelpers, ioRedis, logger }); - // Legacy Socket Events - require("./server/web-sockets/web-socket"); // Initialize Queues await loadQueues({ pubClient: pubClient, logger, redisHelpers, ioRedis }); diff --git a/server/accounting/pbs/pbs-ap-allocations.js b/server/accounting/pbs/pbs-ap-allocations.js index f5092030c..f417d0d15 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 CdkBase = require("../../web-sockets/web-socket"); +const WsLogger = require("../../web-sockets/createLogEvent") const moment = require("moment"); const Dinero = require("dinero.js"); const AxiosLib = require("axios").default; @@ -18,12 +18,11 @@ 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); - CdkBase.createJsonEvent(socket, "SILLY", `Raw Request: ${printable}`, x.data); + WsLogger.createJsonEvent(socket, "SILLY", `Raw Request: ${printable}`, x.data); return x; }); @@ -33,14 +32,14 @@ axios.interceptors.response.use((x) => { const printable = `${new Date()} | Response: ${x.status} | ${JSON.stringify(x.data)}`; //console.log(printable); - CdkBase.createJsonEvent(socket, "SILLY", `Raw Response: ${printable}`, x.data); + WsLogger.createJsonEvent(socket, "SILLY", `Raw Response: ${printable}`, x.data); return x; }); async function PbsCalculateAllocationsAp(socket, billids) { try { - CdkBase.createLogEvent(socket, "DEBUG", `Received request to calculate allocations for ${billids}`); + WsLogger.createLogEvent(socket, "DEBUG", `Received request to calculate allocations for ${billids}`); const { bills, bodyshops } = await QueryBillData(socket, billids); const bodyshop = bodyshops[0]; socket.bodyshop = bodyshop; @@ -50,7 +49,7 @@ async function PbsCalculateAllocationsAp(socket, billids) { const transactionlist = []; if (bills.length === 0) { - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "ERROR", `No bills found for export. Ensure they have not already been exported and try again.` @@ -166,19 +165,19 @@ async function PbsCalculateAllocationsAp(socket, billids) { return transactionlist; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error encountered in PbsCalculateAllocationsAp. ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error encountered in PbsCalculateAllocationsAp. ${error}`); } } exports.PbsCalculateAllocationsAp = PbsCalculateAllocationsAp; async function QueryBillData(socket, billids) { - CdkBase.createLogEvent(socket, "DEBUG", `Querying bill data for id(s) ${billids}`); + WsLogger.createLogEvent(socket, "DEBUG", `Querying bill data for id(s) ${billids}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); const result = await client .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .request(queries.GET_PBS_AP_ALLOCATIONS, { billids: billids }); - CdkBase.createLogEvent(socket, "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; } @@ -193,7 +192,7 @@ function getCostAccount(billline, respcenters) { } exports.PbsExportAp = async function (socket, { billids, txEnvelope }) { - CdkBase.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. socket.apAllocations = await PbsCalculateAllocationsAp(socket, billids); @@ -208,12 +207,12 @@ exports.PbsExportAp = async function (socket, { billids, txEnvelope }) { CheckForErrors(socket, AccountPostingChange); if (AccountPostingChange.WasSuccessful) { - CdkBase.createLogEvent(socket, "DEBUG", `Marking bill as exported.`); + WsLogger.createLogEvent(socket, "DEBUG", `Marking bill as exported.`); await MarkApExported(socket, [billid]); socket.emit("ap-export-success", billid); } else { - CdkBase.createLogEvent(socket, "ERROR", `Export was not successful.`); + WsLogger.createLogEvent(socket, "ERROR", `Export was not successful.`); socket.emit("ap-export-failure", { billid, error: AccountPostingChange.Message @@ -224,7 +223,7 @@ exports.PbsExportAp = async function (socket, { billids, txEnvelope }) { }; async function MarkApExported(socket, billids) { - CdkBase.createLogEvent(socket, "DEBUG", `Marking bills as exported for id ${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}` }) diff --git a/server/accounting/pbs/pbs-job-export.js b/server/accounting/pbs/pbs-job-export.js index 127c9d5e2..61f449e84 100644 --- a/server/accounting/pbs/pbs-job-export.js +++ b/server/accounting/pbs/pbs-job-export.js @@ -2,10 +2,10 @@ 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 { CDK_CREDENTIALS, CheckCdkResponseForError } = require("./cdk-wsdl"); const CalculateAllocations = require("../../cdk/cdk-calculate-allocations").default; -const CdkBase = require("../../web-sockets/web-socket"); const moment = require("moment-timezone"); const Dinero = require("dinero.js"); const InstanceManager = require("../../utils/instanceMgr").default; @@ -19,12 +19,11 @@ 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); - CdkBase.createJsonEvent(socket, "SILLY", `Raw Request: ${printable}`, x.data); + WsLogger.createJsonEvent(socket, "SILLY", `Raw Request: ${printable}`, x.data); return x; }); @@ -34,7 +33,7 @@ axios.interceptors.response.use((x) => { const printable = `${new Date()} | Response: ${x.status} | ${JSON.stringify(x.data)}`; //console.log(printable); - CdkBase.createJsonEvent(socket, "SILLY", `Raw Response: ${printable}`, x.data); + WsLogger.createJsonEvent(socket, "SILLY", `Raw Response: ${printable}`, x.data); return x; }); @@ -44,11 +43,11 @@ exports.default = async function (socket, { txEnvelope, jobid }) { socket.recordid = jobid; socket.txEnvelope = txEnvelope; try { - CdkBase.createLogEvent(socket, "DEBUG", `Received Job export request for id ${jobid}`); + WsLogger.createLogEvent(socket, "DEBUG", `Received Job export request for id ${jobid}`); const JobData = await QueryJobData(socket, jobid); socket.JobData = JobData; - CdkBase.createLogEvent(socket, "DEBUG", `Querying the DMS for the Vehicle Record.`); + WsLogger.createLogEvent(socket, "DEBUG", `Querying the DMS for the Vehicle Record.`); //Query for the Vehicle record to get the associated customer. socket.DmsVeh = await QueryVehicleFromDms(socket); //Todo: Need to validate the lines and methods below. @@ -63,48 +62,47 @@ exports.default = async function (socket, { txEnvelope, jobid }) { ...socket.DMSCustList ]); } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error encountered in PbsJobExport. ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error encountered in PbsJobExport. ${error}`); } }; exports.PbsSelectedCustomer = async function PbsSelectedCustomer(socket, selectedCustomerId) { try { if (socket.JobData.bodyshop.pbs_configuration.disablecontactvehicle === false) { - CdkBase.createLogEvent(socket, "DEBUG", `User selected customer ${selectedCustomerId || "NEW"}`); + WsLogger.createLogEvent(socket, "DEBUG", `User selected customer ${selectedCustomerId || "NEW"}`); //Upsert the contact information as per Wafaa's Email. - CdkBase.createLogEvent( + 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); - CdkBase.createLogEvent(socket, "DEBUG", `Upserting vehicle information to DMS for ${socket.JobData.v_vin}`); + WsLogger.createLogEvent(socket, "DEBUG", `Upserting vehicle information to DMS for ${socket.JobData.v_vin}`); await UpsertVehicleData(socket, ownerRef.ReferenceId); } else { - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "DEBUG", `Contact and Vehicle updates disabled. Skipping to accounting data insert.` ); } - CdkBase.createLogEvent(socket, "DEBUG", `Inserting account data.`); - CdkBase.createLogEvent(socket, "DEBUG", `Inserting accounting posting data..`); + WsLogger.createLogEvent(socket, "DEBUG", `Inserting account data.`); + WsLogger.createLogEvent(socket, "DEBUG", `Inserting accounting posting data..`); const insertResponse = await InsertAccountPostingData(socket); if (insertResponse.WasSuccessful) { - CdkBase.createLogEvent(socket, "DEBUG", `Marking job as exported.`); + WsLogger.createLogEvent(socket, "DEBUG", `Marking job as exported.`); await MarkJobExported(socket, socket.JobData.id); socket.emit("export-success", socket.JobData.id); } else { - CdkBase.createLogEvent(socket, "ERROR", `Export was not successful.`); + WsLogger.createLogEvent(socket, "ERROR", `Export was not successful.`); } } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkSelectedCustomer. ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error encountered in CdkSelectedCustomer. ${error}`); await InsertFailedExportLog(socket, error); } }; @@ -112,22 +110,22 @@ exports.PbsSelectedCustomer = async function PbsSelectedCustomer(socket, selecte // Was Successful async function CheckForErrors(socket, response) { if (response.WasSuccessful === undefined || response.WasSuccessful === true) { - CdkBase.createLogEvent(socket, "DEBUG", `Successful response from DMS. ${response.Message || ""}`); + WsLogger.createLogEvent(socket, "DEBUG", `Successful response from DMS. ${response.Message || ""}`); } else { - CdkBase.createLogEvent(socket, "ERROR", `Error received from DMS: ${response.Message}`); - CdkBase.createLogEvent(socket, "SILLY", `Error received from DMS: ${JSON.stringify(response)}`); + WsLogger.createLogEvent(socket, "ERROR", `Error received from DMS: ${response.Message}`); + WsLogger.createLogEvent(socket, "SILLY", `Error received from DMS: ${JSON.stringify(response)}`); } } exports.CheckForErrors = CheckForErrors; async function QueryJobData(socket, jobid) { - CdkBase.createLogEvent(socket, "DEBUG", `Querying job data for id ${jobid}`); + WsLogger.createLogEvent(socket, "DEBUG", `Querying job data for id ${jobid}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); const result = await client .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .request(queries.QUERY_JOBS_FOR_PBS_EXPORT, { id: jobid }); - CdkBase.createLogEvent(socket, "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; } @@ -166,7 +164,7 @@ async function QueryVehicleFromDms(socket) { CheckForErrors(socket, VehicleGetResponse); return VehicleGetResponse; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in QueryVehicleFromDms - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in QueryVehicleFromDms - ${error}`); throw new Error(error); } } @@ -197,7 +195,7 @@ async function QueryCustomersFromDms(socket) { CheckForErrors(socket, CustomerGetResponse); return CustomerGetResponse && CustomerGetResponse.Contacts; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in QueryCustomersFromDms - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in QueryCustomersFromDms - ${error}`); throw new Error(error); } } @@ -230,7 +228,7 @@ async function QueryCustomerBycodeFromDms(socket, CustomerRef) { CheckForErrors(socket, CustomerGetResponse); return CustomerGetResponse && CustomerGetResponse.Contacts; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in QueryCustomersFromDms - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in QueryCustomersFromDms - ${error}`); throw new Error(error); } } @@ -247,15 +245,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", @@ -312,7 +310,7 @@ async function UpsertContactData(socket, selectedCustomerId) { CheckForErrors(socket, ContactChangeResponse); return ContactChangeResponse; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in UpsertContactData - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in UpsertContactData - ${error}`); throw new Error(error); } } @@ -465,7 +463,7 @@ async function UpsertVehicleData(socket, ownerRef) { CheckForErrors(socket, VehicleChangeResponse); return VehicleChangeResponse; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in UpsertVehicleData - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in UpsertVehicleData - ${error}`); throw new Error(error); } } @@ -566,13 +564,13 @@ async function InsertAccountPostingData(socket) { CheckForErrors(socket, AccountPostingChange); return AccountPostingChange; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in InsertAccountPostingData - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in InsertAccountPostingData - ${error}`); throw new Error(error); } } async function MarkJobExported(socket, jobid) { - CdkBase.createLogEvent(socket, "DEBUG", `Marking job as exported for id ${jobid}`); + WsLogger.createLogEvent(socket, "DEBUG", `Marking job as exported for id ${jobid}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); const result = await client .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) @@ -615,6 +613,6 @@ async function InsertFailedExportLog(socket, error) { return result; } catch (error2) { - CdkBase.createLogEvent(socket, "ERROR", `Error in InsertFailedExportLog - ${error} - ${JSON.stringify(error2)}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in InsertFailedExportLog - ${error} - ${JSON.stringify(error2)}`); } } diff --git a/server/cdk/cdk-calculate-allocations.js b/server/cdk/cdk-calculate-allocations.js index 7c90aef20..c8de282db 100644 --- a/server/cdk/cdk-calculate-allocations.js +++ b/server/cdk/cdk-calculate-allocations.js @@ -1,10 +1,11 @@ const GraphQLClient = require("graphql-request").GraphQLClient; const queries = require("../graphql-client/queries"); -const CdkBase = require("../web-sockets/web-socket"); - +const CreateFortellisLogEvent = require("../fortellis/fortellis-logger"); const Dinero = require("dinero.js"); const _ = require("lodash"); +const WsLogger = require("../web-sockets/createLogEvent") + const InstanceManager = require("../utils/instanceMgr").default; const { DiscountNotAlreadyCounted } = InstanceManager({ imex: require("../job/job-totals"), @@ -13,37 +14,41 @@ const { DiscountNotAlreadyCounted } = InstanceManager({ exports.defaultRoute = async function (req, res) { try { - CdkBase.createLogEvent(req, "DEBUG", `Received request to calculate allocations for ${req.body.jobid}`); + //Fortellis TODO: determine when this is called and whether refactor is required. + WsLogger.createLogEvent(req, "DEBUG", `Received request to calculate allocations for ${req.body.jobid}`); const jobData = await QueryJobData(req, req.BearerToken, req.body.jobid); return res.status(200).json({ data: calculateAllocations(req, jobData) }); } catch (error) { ////console.log(error); - CdkBase.createLogEvent(req, "ERROR", `Error encountered in CdkCalculateAllocations. ${error}`); + WsLogger.createLogEvent(req, "ERROR", `Error encountered in CdkCalculateAllocations. ${error}`); res.status(500).json({ error: `Error encountered in CdkCalculateAllocations. ${error}` }); } }; -exports.default = async function (socket, jobid) { +exports.default = async function (socket, jobid, isFortellis = false) { try { - const jobData = await QueryJobData(socket, "Bearer " + socket.handshake.auth.token, jobid); - return calculateAllocations(socket, jobData); + const jobData = await QueryJobData(socket, "Bearer " + socket.handshake.auth.token, jobid, isFortellis); + return calculateAllocations(socket, jobData, isFortellis); } catch (error) { ////console.log(error); - CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkCalculateAllocations. ${error}`); + const loggingFunction = isFortellis ? CreateFortellisLogEvent : WsLogger.createLogEvent; + loggingFunction(socket, "ERROR", `Error encountered in CdkCalculateAllocations. ${error}`); } }; -async function QueryJobData(connectionData, token, jobid) { - CdkBase.createLogEvent(connectionData, "DEBUG", `Querying job data for id ${jobid}`); +async function QueryJobData(connectionData, token, jobid, isFortellis) { + const loggingFunction = isFortellis ? CreateFortellisLogEvent : WsLogger.createLogEvent; + + loggingFunction(connectionData, "DEBUG", `Querying job data for id ${jobid}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); const result = await client.setHeaders({ Authorization: token }).request(queries.GET_CDK_ALLOCATIONS, { id: jobid }); - CdkBase.createLogEvent(connectionData, "SILLY", `Job data query result ${JSON.stringify(result, null, 2)}`); + loggingFunction(connectionData, "DEBUG", `Job data query result ${JSON.stringify(result, null, 2)}`); return result.jobs_by_pk; } -function calculateAllocations(connectionData, job) { +function calculateAllocations(connectionData, job, isFortellis) { const { bodyshop } = job; - + const loggingFunction = isFortellis ? CreateFortellisLogEvent : WsLogger.createLogEvent; const taxAllocations = InstanceManager({ executeFunction: true, deubg: true, @@ -132,11 +137,11 @@ function calculateAllocations(connectionData, job) { ? val.prt_dsmk_m ? Dinero({ amount: Math.round(val.prt_dsmk_m * 100) }) : Dinero({ - amount: Math.round(val.act_price * 100) - }) - .multiply(val.part_qty || 0) - .percentage(Math.abs(val.prt_dsmk_p || 0)) - .multiply(val.prt_dsmk_p > 0 ? 1 : -1) + amount: Math.round(val.act_price * 100) + }) + .multiply(val.part_qty || 0) + .percentage(Math.abs(val.prt_dsmk_p || 0)) + .multiply(val.prt_dsmk_p > 0 ? 1 : -1) : Dinero() ); @@ -159,7 +164,7 @@ function calculateAllocations(connectionData, job) { const selectedDmsAllocationConfig = bodyshop.md_responsibility_centers.dms_defaults.find( (d) => d.name === job.dms_allocation ); - CdkBase.createLogEvent( + loggingFunction( connectionData, "DEBUG", `Using DMS Allocation ${selectedDmsAllocationConfig && selectedDmsAllocationConfig.name} for cost export.` @@ -194,8 +199,8 @@ function calculateAllocations(connectionData, job) { let TicketTotal = Dinero({ amount: Math.round( ticket.rate * - (ticket.employee && ticket.employee.flat_rate ? ticket.productivehrs || 0 : ticket.actualhrs || 0) * - 100 + (ticket.employee && ticket.employee.flat_rate ? ticket.productivehrs || 0 : ticket.actualhrs || 0) * + 100 ) }); //Add it to the right cost center. @@ -360,10 +365,10 @@ function calculateAllocations(connectionData, job) { Dinero(job.job_totals.parts.adjustments[key]) ); } else { - CdkBase.createLogEvent( + loggingFunction( connectionData, "ERROR", - `Error encountered in CdkCalculateAllocations. Unable to find adjustment account. ${error}` + `Error encountered in CdkCalculateAllocations. Unable to find adjustment account: ${accountName}` ); } }); @@ -383,10 +388,10 @@ function calculateAllocations(connectionData, job) { Dinero(job.job_totals.rates[key].adjustments) ); } else { - CdkBase.createLogEvent( + loggingFunction( connectionData, "ERROR", - `Error encountered in CdkCalculateAllocations. Unable to find adjustment account. ${error}` + `Error encountered in CdkCalculateAllocations. Unable to find adjustment account: ${accountName}` ); } } @@ -427,37 +432,37 @@ function calculateAllocations(connectionData, job) { ...(job.job_totals.totals.ttl_adjustment ? [ - { - center: "SUB ADJ", - sale: Dinero(job.job_totals.totals.ttl_adjustment), - cost: Dinero(), - profitCenter: { - name: "SUB ADJ", - accountdesc: "SUB ADJ", - accountitem: "SUB ADJ", - accountname: "SUB ADJ", - dms_acctnumber: bodyshop.md_responsibility_centers.ttl_adjustment.dms_acctnumber - }, - costCenter: {} - } - ] + { + center: "SUB ADJ", + sale: Dinero(job.job_totals.totals.ttl_adjustment), + cost: Dinero(), + profitCenter: { + name: "SUB ADJ", + accountdesc: "SUB ADJ", + accountitem: "SUB ADJ", + accountname: "SUB ADJ", + dms_acctnumber: bodyshop.md_responsibility_centers.ttl_adjustment.dms_acctnumber + }, + costCenter: {} + } + ] : []), ...(job.job_totals.totals.ttl_tax_adjustment ? [ - { - center: "TAX ADJ", - sale: Dinero(job.job_totals.totals.ttl_tax_adjustment), - cost: Dinero(), - profitCenter: { - name: "TAX ADJ", - accountdesc: "TAX ADJ", - accountitem: "TAX ADJ", - accountname: "TAX ADJ", - dms_acctnumber: bodyshop.md_responsibility_centers.ttl_tax_adjustment.dms_acctnumber - }, - costCenter: {} - } - ] + { + center: "TAX ADJ", + sale: Dinero(job.job_totals.totals.ttl_tax_adjustment), + cost: Dinero(), + profitCenter: { + name: "TAX ADJ", + accountdesc: "TAX ADJ", + accountitem: "TAX ADJ", + accountname: "TAX ADJ", + dms_acctnumber: bodyshop.md_responsibility_centers.ttl_tax_adjustment.dms_acctnumber + }, + costCenter: {} + } + ] : []) ]; } diff --git a/server/cdk/cdk-job-export.js b/server/cdk/cdk-job-export.js index c1ca5873d..619313c7b 100644 --- a/server/cdk/cdk-job-export.js +++ b/server/cdk/cdk-job-export.js @@ -1,11 +1,11 @@ const GraphQLClient = require("graphql-request").GraphQLClient; const soap = require("soap"); const queries = require("../graphql-client/queries"); -const CdkBase = require("../web-sockets/web-socket"); 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 moment = require("moment-timezone"); @@ -19,18 +19,18 @@ exports.default = async function (socket, { txEnvelope, jobid }) { //// try { - CdkBase.createLogEvent(socket, "DEBUG", `Received Job export request for id ${jobid}`); + WsLogger.createLogEvent(socket, "DEBUG", `Received Job export request for id ${jobid}`); const JobData = await QueryJobData(socket, jobid); socket.JobData = JobData; const DealerId = JobData.bodyshop.cdk_dealerid; - CdkBase.createLogEvent(socket, "DEBUG", `Dealer ID detected: ${JSON.stringify(DealerId)}`); + WsLogger.createLogEvent(socket, "DEBUG", `Dealer ID detected: ${JSON.stringify(DealerId)}`); - CdkBase.createLogEvent(socket, "DEBUG", `{1} Begin Calculate DMS Vehicle ID using VIN: ${JobData.v_vin}`); + WsLogger.createLogEvent(socket, "DEBUG", `{1} Begin Calculate DMS Vehicle ID using VIN: ${JobData.v_vin}`); socket.DMSVid = await CalculateDmsVid(socket, JobData); if (socket.DMSVid.newId === "N") { - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "DEBUG", `{2.1} Querying the Vehicle using the DMSVid: ${socket.DMSVid.vehiclesVehId}` @@ -41,7 +41,7 @@ exports.default = async function (socket, { txEnvelope, jobid }) { socket.DMSVeh && socket.DMSVeh.owners && socket.DMSVeh.owners.find((o) => o.id.assigningPartyId === "CURRENT"); if (DMSVehCustomer && DMSVehCustomer.id && DMSVehCustomer.id.value) { - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "DEBUG", `{2.2} Querying the Customer using the ID from DMSVeh: ${DMSVehCustomer.id.value}` @@ -50,7 +50,7 @@ exports.default = async function (socket, { txEnvelope, jobid }) { } } - CdkBase.createLogEvent(socket, "DEBUG", `{2.3} Querying the Customer using the name.`); + WsLogger.createLogEvent(socket, "DEBUG", `{2.3} Querying the Customer using the name.`); socket.DMSCustList = await QueryDmsCustomerByName(socket, JobData); @@ -59,7 +59,7 @@ exports.default = async function (socket, { txEnvelope, jobid }) { ...socket.DMSCustList ]); } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkJobExport. ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error encountered in CdkJobExport. ${error}`); } }; @@ -67,35 +67,35 @@ async function CdkSelectedCustomer(socket, selectedCustomerId) { try { socket.selectedCustomerId = selectedCustomerId; if (selectedCustomerId) { - CdkBase.createLogEvent(socket, "DEBUG", `{3.1} Querying the Customer using Customer ID: ${selectedCustomerId}`); + WsLogger.createLogEvent(socket, "DEBUG", `{3.1} Querying the Customer using Customer ID: ${selectedCustomerId}`); socket.DMSCust = await QueryDmsCustomerById(socket, socket.JobData, selectedCustomerId); } else { - CdkBase.createLogEvent(socket, "DEBUG", `{3.2} Generating a new customer ID.`); + WsLogger.createLogEvent(socket, "DEBUG", `{3.2} Generating a new customer ID.`); const newCustomerId = await GenerateDmsCustomerNumber(socket); - CdkBase.createLogEvent(socket, "DEBUG", `{3.3} Inserting new customer with ID: ${newCustomerId}`); + WsLogger.createLogEvent(socket, "DEBUG", `{3.3} Inserting new customer with ID: ${newCustomerId}`); socket.DMSCust = await InsertDmsCustomer(socket, newCustomerId); } if (socket.DMSVid.newId === "Y") { - CdkBase.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 { - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "DEBUG", `{4.2} Querying Existing Vehicle using ID ${socket.DMSVid.vehiclesVehId}` ); socket.DMSVeh = await QueryDmsVehicleById(socket, socket.JobData, socket.DMSVid); - CdkBase.createLogEvent(socket, "DEBUG", `{4.3} Updating Existing Vehicle to associate to owner.`); + WsLogger.createLogEvent(socket, "DEBUG", `{4.3} Updating Existing Vehicle to associate to owner.`); socket.DMSVeh = await UpdateDmsVehicle(socket); } - CdkBase.createLogEvent(socket, "DEBUG", `{5} Creating Transaction header with Dms Start WIP`); + WsLogger.createLogEvent(socket, "DEBUG", `{5} Creating Transaction header with Dms Start WIP`); socket.DMSTransHeader = await InsertDmsStartWip(socket); - CdkBase.createLogEvent(socket, "DEBUG", `{5.1} Creating Transaction with ID ${socket.DMSTransHeader.transID}`); + WsLogger.createLogEvent(socket, "DEBUG", `{5.1} Creating Transaction with ID ${socket.DMSTransHeader.transID}`); socket.DMSBatchTxn = await InsertDmsBatchWip(socket); - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "DEBUG", `{6} Attempting to post Transaction with ID ${socket.DMSTransHeader.transID}` @@ -103,23 +103,23 @@ async function CdkSelectedCustomer(socket, selectedCustomerId) { socket.DmsBatchTxnPost = await PostDmsBatchWip(socket); if (socket.DmsBatchTxnPost.code === "success") { //something - CdkBase.createLogEvent(socket, "DEBUG", `{6} Successfully posted sransaction to DMS.`); + WsLogger.createLogEvent(socket, "DEBUG", `{6} Successfully posted sransaction to DMS.`); await MarkJobExported(socket, socket.JobData.id); - CdkBase.createLogEvent(socket, "DEBUG", `{5} Updating Service Vehicle History.`); + WsLogger.createLogEvent(socket, "DEBUG", `{5} Updating Service Vehicle History.`); socket.DMSVehHistory = await InsertServiceVehicleHistory(socket); socket.emit("export-success", socket.JobData.id); } else { //Get the error code - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "DEBUG", `{6.1} Getting errors for Transaction ID ${socket.DMSTransHeader.transID}` ); socket.DmsError = await QueryDmsErrWip(socket); //Delete the transaction - CdkBase.createLogEvent(socket, "DEBUG", `{6.2} Deleting Transaction ID ${socket.DMSTransHeader.transID}`); + WsLogger.createLogEvent(socket, "DEBUG", `{6.2} Deleting Transaction ID ${socket.DMSTransHeader.transID}`); socket.DmsBatchTxnPost = await DeleteDmsWip(socket); socket.DmsError.errMsg @@ -128,29 +128,29 @@ async function CdkSelectedCustomer(socket, selectedCustomerId) { (e) => e !== null && e !== "" && - CdkBase.createLogEvent(socket, "ERROR", `Error(s) encountered in posting transaction. ${e}`) + WsLogger.createLogEvent(socket, "ERROR", `Error(s) encountered in posting transaction. ${e}`) ); } } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkSelectedCustomer. ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error encountered in CdkSelectedCustomer. ${error}`); await InsertFailedExportLog(socket, error); } finally { //Ensure we always insert logEvents //GQL to insert logevents. - CdkBase.createLogEvent(socket, "DEBUG", `Capturing log events to database.`); + WsLogger.createLogEvent(socket, "DEBUG", `Capturing log events to database.`); } } exports.CdkSelectedCustomer = CdkSelectedCustomer; async function QueryJobData(socket, jobid) { - CdkBase.createLogEvent(socket, "DEBUG", `Querying job data for id ${jobid}`); + WsLogger.createLogEvent(socket, "DEBUG", `Querying job data for id ${jobid}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); const result = await client .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .request(queries.QUERY_JOBS_FOR_CDK_EXPORT, { id: jobid }); - CdkBase.createLogEvent(socket, "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; } @@ -164,11 +164,11 @@ async function CalculateDmsVid(socket, JobData) { }); const [result, rawResponse, , rawRequest] = soapResponseVehicleInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.getVehIdsAsync request.`); + WsLogger.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.getVehIdsAsync request.`); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.getVehIdsAsync response.`); + WsLogger.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.getVehIdsAsync response.`); - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "SILLY", `soapClientVehicleInsertUpdate.getVehIdsAsync Result ${JSON.stringify(result, null, 2)}` @@ -181,15 +181,15 @@ async function CalculateDmsVid(socket, JobData) { //return result && result.return && result.return[0]; } catch (error) { - CdkBase.createXmlEvent(socket, error.request, `soapClientVehicleInsertUpdate.getVehIdsAsync request.`, true); + WsLogger.createXmlEvent(socket, error.request, `soapClientVehicleInsertUpdate.getVehIdsAsync request.`, true); - CdkBase.createXmlEvent( + WsLogger.createXmlEvent( socket, error.response && error.response.data, `soapClientVehicleInsertUpdate.getVehIdsAsync response.`, true ); - CdkBase.createLogEvent(socket, "ERROR", `{1} Error in CalculateDmsVid - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `{1} Error in CalculateDmsVid - ${error}`); throw new Error(error); } } @@ -209,19 +209,19 @@ async function QueryDmsVehicleById(socket, JobData, DMSVid) { const [result, rawResponse, , rawRequest] = soapResponseVehicleInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.readAsync request.`); + WsLogger.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.readAsync request.`); - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "SILLY", `soapClientVehicleInsertUpdate.readAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.readAsync response.`); + WsLogger.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.readAsync response.`); CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); const VehicleFromDMS = result && result.return && result.return.vehicle; return VehicleFromDMS; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in QueryDmsVehicleById - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in QueryDmsVehicleById - ${error}`); throw new Error(error); } } @@ -240,10 +240,10 @@ async function QueryDmsCustomerById(socket, JobData, CustomerId) { const [result, rawResponse, , rawRequest] = soapResponseCustomerInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientCustomerInsertUpdate.readAsync request.`); + WsLogger.createXmlEvent(socket, rawRequest, `soapClientCustomerInsertUpdate.readAsync request.`); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientCustomerInsertUpdate.readAsync response.`); - CdkBase.createLogEvent( + WsLogger.createXmlEvent(socket, rawResponse, `soapClientCustomerInsertUpdate.readAsync response.`); + WsLogger.createLogEvent( socket, "SILLY", `soapClientCustomerInsertUpdate.readAsync Result ${JSON.stringify(result, null, 2)}` @@ -252,16 +252,16 @@ async function QueryDmsCustomerById(socket, JobData, CustomerId) { const CustomersFromDms = result && result.return && result.return.customerParty; return CustomersFromDms; } catch (error) { - CdkBase.createXmlEvent(socket, error.request, `soapClientCustomerInsertUpdate.readAsync request.`, true); + WsLogger.createXmlEvent(socket, error.request, `soapClientCustomerInsertUpdate.readAsync request.`, true); - CdkBase.createXmlEvent( + WsLogger.createXmlEvent( socket, error.response && error.response.data, `soapClientCustomerInsertUpdate.readAsync response.`, true ); - CdkBase.createLogEvent(socket, "ERROR", `Error in QueryDmsCustomerById - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in QueryDmsCustomerById - ${error}`); throw new Error(error); } } @@ -273,7 +273,7 @@ async function QueryDmsCustomerByName(socket, JobData) { : `${JobData.ownr_ln},${JobData.ownr_fn}` ).replace(replaceSpecialRegex, ""); - CdkBase.createLogEvent(socket, "DEBUG", `Begin Query DMS Customer by Name using: ${ownerName}`); + WsLogger.createLogEvent(socket, "DEBUG", `Begin Query DMS Customer by Name using: ${ownerName}`); try { const soapClientCustomerSearch = await soap.createClientAsync(CdkWsdl.CustomerSearch); @@ -288,11 +288,11 @@ async function QueryDmsCustomerByName(socket, JobData) { const [result, rawResponse, , rawRequest] = soapResponseCustomerSearch; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientCustomerSearch.executeSearchBulkAsync request.`); + WsLogger.createXmlEvent(socket, rawRequest, `soapClientCustomerSearch.executeSearchBulkAsync request.`); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientCustomerSearch.executeSearchBulkAsync response.`); + WsLogger.createXmlEvent(socket, rawResponse, `soapClientCustomerSearch.executeSearchBulkAsync response.`); - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "SILLY", `soapClientCustomerSearch.executeSearchBulkAsync Result ${JSON.stringify(result, null, 2)}` @@ -301,16 +301,16 @@ async function QueryDmsCustomerByName(socket, JobData) { const CustomersFromDms = (result && result.return) || []; return CustomersFromDms; } catch (error) { - CdkBase.createXmlEvent(socket, error.request, `soapClientCustomerSearch.executeSearchBulkAsync request.`, true); + WsLogger.createXmlEvent(socket, error.request, `soapClientCustomerSearch.executeSearchBulkAsync request.`, true); - CdkBase.createXmlEvent( + WsLogger.createXmlEvent( socket, error.response && error.response.data, `soapClientCustomerSearch.executeSearchBulkAsync response.`, true ); - CdkBase.createLogEvent(socket, "ERROR", `Error in QueryDmsCustomerByName - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in QueryDmsCustomerByName - ${error}`); throw new Error(error); } } @@ -330,11 +330,11 @@ async function GenerateDmsCustomerNumber(socket) { const [result, rawResponse, , rawRequest] = soapResponseCustomerInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientCustomerInsertUpdate.getCustomerNumberAsync request.`); + WsLogger.createXmlEvent(socket, rawRequest, `soapClientCustomerInsertUpdate.getCustomerNumberAsync request.`); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientCustomerInsertUpdate.getCustomerNumberAsync response.`); + WsLogger.createXmlEvent(socket, rawResponse, `soapClientCustomerInsertUpdate.getCustomerNumberAsync response.`); - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "SILLY", `soapClientCustomerInsertUpdate.getCustomerNumberAsync Result ${JSON.stringify(result, null, 2)}` @@ -343,20 +343,20 @@ async function GenerateDmsCustomerNumber(socket) { const customerNumber = result && result.return && result.return.customerNumber; return customerNumber; } catch (error) { - CdkBase.createXmlEvent( + WsLogger.createXmlEvent( socket, error.request, `soapClientCustomerInsertUpdate.getCustomerNumberAsync request.`, true ); - CdkBase.createXmlEvent( + WsLogger.createXmlEvent( socket, error.response && error.response.data, `soapClientCustomerInsertUpdate.getCustomerNumberAsync response.`, true ); - CdkBase.createLogEvent(socket, "ERROR", `Error in GenerateDmsCustomerNumber - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in GenerateDmsCustomerNumber - ${error}`); throw new Error(error); } } @@ -419,10 +419,10 @@ async function InsertDmsCustomer(socket, newCustomerNumber) { ); const [result, rawResponse, , rawRequest] = soapResponseCustomerInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientCustomerInsertUpdate.insertAsync request.`); + WsLogger.createXmlEvent(socket, rawRequest, `soapClientCustomerInsertUpdate.insertAsync request.`); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientCustomerInsertUpdate.insertAsync response.`); - CdkBase.createLogEvent( + WsLogger.createXmlEvent(socket, rawResponse, `soapClientCustomerInsertUpdate.insertAsync response.`); + WsLogger.createLogEvent( socket, "SILLY", `soapClientCustomerInsertUpdate.insertAsync Result ${JSON.stringify(result, null, 2)}` @@ -431,15 +431,15 @@ async function InsertDmsCustomer(socket, newCustomerNumber) { const customer = result && result.return && result.return.customerParty; return customer; } catch (error) { - CdkBase.createXmlEvent(socket, error.request, `soapClientCustomerInsertUpdate.insertAsync request.`, true); + WsLogger.createXmlEvent(socket, error.request, `soapClientCustomerInsertUpdate.insertAsync request.`, true); - CdkBase.createXmlEvent( + WsLogger.createXmlEvent( socket, error.response && error.response.data, `soapClientCustomerInsertUpdate.insertAsync response.`, true ); - CdkBase.createLogEvent(socket, "ERROR", `Error in InsertDmsCustomer - ${error}`); + 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, @@ -500,19 +500,19 @@ async function InsertDmsVehicle(socket) { const [result, rawResponse, , rawRequest] = soapResponseVehicleInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.insertAsync request.`); + WsLogger.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.insertAsync request.`); - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "SILLY", `soapClientVehicleInsertUpdate.insertAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.insertAsync response.`); + WsLogger.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.insertAsync response.`); CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); const VehicleFromDMS = result && result.return && result.return.vehicle; return VehicleFromDMS; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in InsertDmsVehicle - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in InsertDmsVehicle - ${error}`); throw new Error(error); } } @@ -557,13 +557,13 @@ async function UpdateDmsVehicle(socket) { }, ...(oldOwner ? [ - { - id: { - assigningPartyId: "PREVIOUS", - value: oldOwner.id.value - } + { + id: { + assigningPartyId: "PREVIOUS", + value: oldOwner.id.value } - ] + } + ] : []) ]; } @@ -581,24 +581,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 }, @@ -606,19 +606,19 @@ async function UpdateDmsVehicle(socket) { }); const [result, rawResponse, , rawRequest] = soapResponseVehicleInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.updateAsync request.`); + WsLogger.createXmlEvent(socket, rawRequest, `soapClientVehicleInsertUpdate.updateAsync request.`); - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "DEBUG", `soapClientVehicleInsertUpdate.updateAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.updateAsync response.`); + WsLogger.createXmlEvent(socket, rawResponse, `soapClientVehicleInsertUpdate.updateAsync response.`); CheckCdkResponseForError(socket, soapResponseVehicleInsertUpdate); const VehicleFromDMS = result && result.return && result.return.vehicle; return VehicleFromDMS; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in UpdateDmsVehicle - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in UpdateDmsVehicle - ${error}`); throw new Error(error); } } @@ -645,18 +645,18 @@ async function InsertServiceVehicleHistory(socket) { const [result, rawResponse, , rawRequest] = soapResponseServiceHistoryInsert; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientServiceHistoryInsert.serviceHistoryHeaderInsert request.`); + WsLogger.createXmlEvent(socket, rawRequest, `soapClientServiceHistoryInsert.serviceHistoryHeaderInsert request.`); - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "SILLY", `soapClientServiceHistoryInsert.serviceHistoryHeaderInsert Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientServiceHistoryInsert.serviceHistoryHeaderInsert response.`); + WsLogger.createXmlEvent(socket, rawResponse, `soapClientServiceHistoryInsert.serviceHistoryHeaderInsert response.`); CheckCdkResponseForError(socket, soapResponseServiceHistoryInsert); return result && result.return; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in InsertServiceVehicleHistory - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in InsertServiceVehicleHistory - ${error}`); throw new Error(error); } } @@ -685,19 +685,19 @@ async function InsertDmsStartWip(socket) { const [result, rawResponse, , rawRequest] = soapResponseAccountingGLInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doStartWIPAsync request.`); + WsLogger.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doStartWIPAsync request.`); - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "SILLY", `soapClientAccountingGLInsertUpdate.doStartWIPAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doStartWIPAsync response.`); + WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doStartWIPAsync response.`); CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); const TransactionHeader = result && result.return; return TransactionHeader; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in InsertDmsStartWip - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in InsertDmsStartWip - ${error}`); throw new Error(error); } } @@ -716,19 +716,19 @@ async function InsertDmsBatchWip(socket) { const [result, rawResponse, , rawRequest] = soapResponseAccountingGLInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doTransBatchWIPAsync request.`); + WsLogger.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doTransBatchWIPAsync request.`); - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "SILLY", `soapClientAccountingGLInsertUpdate.doTransBatchWIPAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doTransBatchWIPAsync response.`); + WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doTransBatchWIPAsync response.`); CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); const BatchWipResult = result && result.return; return BatchWipResult; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in InsertDmsBatchWip - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in InsertDmsBatchWip - ${error}`); throw new Error(error); } } @@ -743,9 +743,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 +766,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 +786,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 +827,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, @@ -880,19 +880,19 @@ async function PostDmsBatchWip(socket) { const [result, rawResponse, , rawRequest] = soapResponseAccountingGLInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync request.`); + WsLogger.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync request.`); - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "SILLY", `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync response.`); + WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync response.`); // CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); const PostResult = result && result.return; return PostResult; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in PostDmsBatchWip - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in PostDmsBatchWip - ${error}`); throw new Error(error); } } @@ -909,19 +909,19 @@ async function QueryDmsErrWip(socket) { const [result, rawResponse, , rawRequest] = soapResponseAccountingGLInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doErrWIPAsync request.`); + WsLogger.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doErrWIPAsync request.`); - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "DEBUG", `soapClientAccountingGLInsertUpdate.doErrWIPAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doErrWIPAsync response.`); + WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doErrWIPAsync response.`); CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); const PostResult = result && result.return; return PostResult; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in QueryDmsErrWip - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in QueryDmsErrWip - ${error}`); throw new Error(error); } } @@ -940,25 +940,25 @@ async function DeleteDmsWip(socket) { const [result, rawResponse, , rawRequest] = soapResponseAccountingGLInsertUpdate; - CdkBase.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync request.`); + WsLogger.createXmlEvent(socket, rawRequest, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync request.`); - CdkBase.createLogEvent( + WsLogger.createLogEvent( socket, "SILLY", `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync Result ${JSON.stringify(result, null, 2)}` ); - CdkBase.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync response.`); + WsLogger.createXmlEvent(socket, rawResponse, `soapClientAccountingGLInsertUpdate.doPostBatchWIPAsync response.`); CheckCdkResponseForError(socket, soapResponseAccountingGLInsertUpdate); const PostResult = result && result.return; return PostResult; } catch (error) { - CdkBase.createLogEvent(socket, "ERROR", `Error in PostDmsBatchWip - ${error}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in PostDmsBatchWip - ${error}`); throw new Error(error); } } async function MarkJobExported(socket, jobid) { - CdkBase.createLogEvent(socket, "DEBUG", `Marking job as exported for id ${jobid}`); + WsLogger.createLogEvent(socket, "DEBUG", `Marking job as exported for id ${jobid}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); const result = await client .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) @@ -1001,6 +1001,6 @@ async function InsertFailedExportLog(socket, error) { return result; } catch (error2) { - CdkBase.createLogEvent(socket, "ERROR", `Error in InsertFailedExportLog - ${error} - ${JSON.stringify(error2)}`); + WsLogger.createLogEvent(socket, "ERROR", `Error in InsertFailedExportLog - ${error} - ${JSON.stringify(error2)}`); } } diff --git a/server/web-sockets/createLogEvent.js b/server/web-sockets/createLogEvent.js new file mode 100644 index 000000000..6f2b24050 --- /dev/null +++ b/server/web-sockets/createLogEvent.js @@ -0,0 +1,116 @@ +const { isArray } = require("lodash"); +const logger = require("../utils/logger"); + + +function createLogEvent(socket, level, message) { + if (LogLevelHierarchy(socket.log_level) >= LogLevelHierarchy(level)) { + // console.log(`[WS LOG EVENT] ${level} - ${new Date()} - ${socket.user.email} - ${socket.id} - ${message}`); + socket.emit("log-event", { + timestamp: new Date(), + level, + message + }); + + logger.log("ws-log-event", level, socket.user.email, socket.recordid, { + wsmessage: message + }); + + if (socket.logEvents && isArray(socket.logEvents)) { + socket.logEvents.push({ + timestamp: new Date(), + level, + message + }); + } + // if (level === "ERROR") { + // throw new Error(message); + // } + } +} + +function createJsonEvent(socket, level, message, json) { + if (LogLevelHierarchy(socket.log_level) >= LogLevelHierarchy(level)) { + //console.log(`[WS LOG EVENT] ${level} - ${new Date()} - ${socket.user.email} - ${socket.id} - ${message}`); + socket.emit("log-event", { + timestamp: new Date(), + level, + message + }); + } + logger.log( + "ws-log-event-json", + level, + socket.user.email, + socket.recordid, + { + wsmessage: message, + json + }, + true + ); + + if (socket.logEvents && isArray(socket.logEvents)) { + socket.logEvents.push({ + timestamp: new Date(), + level, + message + }); + } + // if (level === "ERROR") { + // throw new Error(message); + // } +} + +function createXmlEvent(socket, xml, message, isError = false) { + if (LogLevelHierarchy(socket.log_level) >= LogLevelHierarchy("SILLY")) { + socket.emit("log-event", { + timestamp: new Date(), + level: isError ? "ERROR" : "SILLY", + message: `${message}: ${xml}` + }); + } + + logger.log( + isError ? "ws-log-event-xml-error" : "ws-log-event-xml", + isError ? "ERROR" : "SILLY", + socket.user.email, + socket.recordid, + { + wsmessage: message, + xml + }, + true + ); + + if (socket.logEvents && isArray(socket.logEvents)) { + socket.logEvents.push({ + timestamp: new Date(), + level: isError ? "ERROR" : "SILLY", + message, + xml + }); + } +} + +function LogLevelHierarchy(level) { + switch (level) { + case "XML": + return 5; + case "SILLY": + return 5; + case "DEBUG": + return 4; + case "INFO": + return 3; + case "WARN": + return 2; + case "ERROR": + return 1; + default: + return 3; + } +} + +exports.createLogEvent = createLogEvent; +exports.createXmlEvent = createXmlEvent; +exports.createJsonEvent = createJsonEvent; diff --git a/server/web-sockets/web-socket.js b/server/web-sockets/web-socket.js index c55313a86..b2e94909b 100644 --- a/server/web-sockets/web-socket.js +++ b/server/web-sockets/web-socket.js @@ -1,231 +1,122 @@ -const path = require("path"); - -const { io } = require("../../server"); const { admin } = require("../firebase/firebase-handler"); const { default: CdkJobExport, CdkSelectedCustomer } = require("../cdk/cdk-job-export"); const CdkGetMakes = require("../cdk/cdk-get-makes").default; const CdkCalculateAllocations = require("../cdk/cdk-calculate-allocations").default; -const { isArray } = require("lodash"); const logger = require("../utils/logger"); const { default: PbsExportJob, PbsSelectedCustomer } = require("../accounting/pbs/pbs-job-export"); const { PbsCalculateAllocationsAp, PbsExportAp } = require("../accounting/pbs/pbs-ap-allocations"); +const { createLogEvent } = require("./createLogEvent"); -io.use(function (socket, next) { - try { - if (socket.handshake.auth.token) { - admin - .auth() - .verifyIdToken(socket.handshake.auth.token) - .then((user) => { - socket.user = user; - next(); - }) - .catch((error) => { - next(new Error("Authentication error", JSON.stringify(error))); - }); - } else { - next(new Error("Authentication error - no authorization token.")); - } - } catch (error) { - //console.log("Uncaught connection error:::", error); - logger.log("websocket-connection-error", "error", null, null, { - token: socket.handshake.auth.token, - ...error - }); - next(new Error(`Authentication error ${error}`)); - } -}); +function SetLegacyWebsocketHandlers(io) { -io.on("connection", (socket) => { - socket.log_level = "DEBUG"; - createLogEvent(socket, "DEBUG", `Connected and Authenticated.`); - - socket.on("set-log-level", (level) => { - socket.log_level = level; - socket.emit("log-event", { - timestamp: new Date(), - level: "INFO", - message: `Updated log level to ${level}` - }); - }); - - ///CDK - 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; - CdkSelectedCustomer(socket, selectedCustomerId); - }); - - socket.on("cdk-get-makes", async (cdk_dealerid, callback) => { + io.use(function (socket, next) { try { - const makes = await CdkGetMakes(socket, cdk_dealerid); - callback(makes); + if (socket.handshake.auth.token) { + admin + .auth() + .verifyIdToken(socket.handshake.auth.token) + .then((user) => { + socket.user = user; + next(); + }) + .catch((error) => { + next(new Error("Authentication error", JSON.stringify(error))); + }); + } else { + next(new Error("Authentication error - no authorization token.")); + } } catch (error) { - createLogEvent(socket, "ERROR", `Error in cdk-get-makes WS call. ${JSON.stringify(error, null, 2)}`); - } - }); - - socket.on("cdk-calculate-allocations", async (jobid, callback) => { - const allocations = await CdkCalculateAllocations(socket, jobid); - createLogEvent(socket, "DEBUG", `Allocations calculated.`); - createLogEvent(socket, "SILLY", `Allocations calculated. ${JSON.stringify(allocations, null, 2)}`); - - callback(allocations); - }); - //END CDK - - //PBS AR - socket.on("pbs-calculate-allocations", async (jobid, callback) => { - const allocations = await CdkCalculateAllocations(socket, jobid); - createLogEvent(socket, "DEBUG", `Allocations calculated.`); - createLogEvent(socket, "SILLY", `Allocations calculated. ${JSON.stringify(allocations, null, 2)}`); - - callback(allocations); - }); - socket.on("pbs-export-job", (jobid) => { - PbsExportJob(socket, jobid); - }); - socket.on("pbs-selected-customer", (selectedCustomerId) => { - createLogEvent(socket, "DEBUG", `User selected customer ID ${selectedCustomerId}`); - socket.selectedCustomerId = selectedCustomerId; - PbsSelectedCustomer(socket, selectedCustomerId); - }); - //End PBS AR - - //PBS AP - socket.on("pbs-calculate-allocations-ap", async (billids, callback) => { - const allocations = await PbsCalculateAllocationsAp(socket, billids); - createLogEvent(socket, "DEBUG", `AP Allocations calculated.`); - createLogEvent(socket, "DEBUG", `Allocations calculated. ${JSON.stringify(allocations, null, 2)}`); - socket.apAllocations = allocations; - callback(allocations); - }); - - socket.on("pbs-export-ap", ({ billids, txEnvelope }) => { - socket.txEnvelope = txEnvelope; - PbsExportAp(socket, { billids, txEnvelope }); - }); - - //END PBS AP - - socket.on("disconnect", () => { - createLogEvent(socket, "DEBUG", `User disconnected.`); - }); -}); - -function createLogEvent(socket, level, message) { - if (LogLevelHierarchy(socket.log_level) >= LogLevelHierarchy(level)) { - // console.log(`[WS LOG EVENT] ${level} - ${new Date()} - ${socket.user.email} - ${socket.id} - ${message}`); - socket.emit("log-event", { - timestamp: new Date(), - level, - message - }); - - logger.log("ws-log-event", level, socket.user.email, socket.recordid, { - wsmessage: message - }); - - if (socket.logEvents && isArray(socket.logEvents)) { - socket.logEvents.push({ - timestamp: new Date(), - level, - message + //console.log("Uncaught connection error:::", error); + logger.log("websocket-connection-error", "error", null, null, { + token: socket.handshake.auth.token, + ...error }); + next(new Error(`Authentication error ${error}`)); } - // if (level === "ERROR") { - // throw new Error(message); - // } - } + }); + + io.on("connection", (socket) => { + socket.log_level = "DEBUG"; + createLogEvent(socket, "DEBUG", `Connected and Authenticated.`); + + socket.on("set-log-level", (level) => { + socket.log_level = level; + socket.emit("log-event", { + timestamp: new Date(), + level: "INFO", + message: `Updated log level to ${level}` + }); + }); + + ///CDK + 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; + CdkSelectedCustomer(socket, selectedCustomerId); + }); + + socket.on("cdk-get-makes", async (cdk_dealerid, callback) => { + try { + const makes = await CdkGetMakes(socket, cdk_dealerid); + callback(makes); + } catch (error) { + createLogEvent(socket, "ERROR", `Error in cdk-get-makes WS call. ${JSON.stringify(error, null, 2)}`); + } + }); + + socket.on("cdk-calculate-allocations", async (jobid, callback) => { + console.log("cdk-calculate-allocations called", typeof CdkCalculateAllocations); + const allocations = await CdkCalculateAllocations(socket, jobid); + createLogEvent(socket, "DEBUG", `Allocations calculated.`); + createLogEvent(socket, "SILLY", `Allocations calculated. ${JSON.stringify(allocations, null, 2)}`); + + callback(allocations); + }); + //END CDK + + //PBS AR + socket.on("pbs-calculate-allocations", async (jobid, callback) => { + const allocations = await CdkCalculateAllocations(socket, jobid); + createLogEvent(socket, "DEBUG", `Allocations calculated.`); + createLogEvent(socket, "SILLY", `Allocations calculated. ${JSON.stringify(allocations, null, 2)}`); + + callback(allocations); + }); + socket.on("pbs-export-job", (jobid) => { + PbsExportJob(socket, jobid); + }); + socket.on("pbs-selected-customer", (selectedCustomerId) => { + createLogEvent(socket, "DEBUG", `User selected customer ID ${selectedCustomerId}`); + socket.selectedCustomerId = selectedCustomerId; + PbsSelectedCustomer(socket, selectedCustomerId); + }); + //End PBS AR + + //PBS AP + socket.on("pbs-calculate-allocations-ap", async (billids, callback) => { + const allocations = await PbsCalculateAllocationsAp(socket, billids); + createLogEvent(socket, "DEBUG", `AP Allocations calculated.`); + createLogEvent(socket, "DEBUG", `Allocations calculated. ${JSON.stringify(allocations, null, 2)}`); + socket.apAllocations = allocations; + callback(allocations); + }); + + socket.on("pbs-export-ap", ({ billids, txEnvelope }) => { + socket.txEnvelope = txEnvelope; + PbsExportAp(socket, { billids, txEnvelope }); + }); + + //END PBS AP + + socket.on("disconnect", () => { + createLogEvent(socket, "DEBUG", `User disconnected.`); + }); + }); + } -function createJsonEvent(socket, level, message, json) { - if (LogLevelHierarchy(socket.log_level) >= LogLevelHierarchy(level)) { - //console.log(`[WS LOG EVENT] ${level} - ${new Date()} - ${socket.user.email} - ${socket.id} - ${message}`); - socket.emit("log-event", { - timestamp: new Date(), - level, - message - }); - } - logger.log( - "ws-log-event-json", - level, - socket.user.email, - socket.recordid, - { - wsmessage: message, - json - }, - true - ); - - if (socket.logEvents && isArray(socket.logEvents)) { - socket.logEvents.push({ - timestamp: new Date(), - level, - message - }); - } - // if (level === "ERROR") { - // throw new Error(message); - // } -} - -function createXmlEvent(socket, xml, message, isError = false) { - if (LogLevelHierarchy(socket.log_level) >= LogLevelHierarchy("SILLY")) { - socket.emit("log-event", { - timestamp: new Date(), - level: isError ? "ERROR" : "SILLY", - message: `${message}: ${xml}` - }); - } - - logger.log( - isError ? "ws-log-event-xml-error" : "ws-log-event-xml", - isError ? "ERROR" : "SILLY", - socket.user.email, - socket.recordid, - { - wsmessage: message, - xml - }, - true - ); - - if (socket.logEvents && isArray(socket.logEvents)) { - socket.logEvents.push({ - timestamp: new Date(), - level: isError ? "ERROR" : "SILLY", - message, - xml - }); - } -} - -function LogLevelHierarchy(level) { - switch (level) { - case "XML": - return 5; - case "SILLY": - return 5; - case "DEBUG": - return 4; - case "INFO": - return 3; - case "WARN": - return 2; - case "ERROR": - return 1; - default: - return 3; - } -} - -exports.createLogEvent = createLogEvent; -exports.createXmlEvent = createXmlEvent; -exports.createJsonEvent = createJsonEvent; +exports.SetLegacyWebsocketHandlers = SetLegacyWebsocketHandlers; \ No newline at end of file