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 queries = require("../../graphql-client/queries");
const WsLogger = require("../../web-sockets/createLogEvent")
const WsLogger = require("../../web-sockets/createLogEvent");
const moment = require("moment");
const Dinero = require("dinero.js");
const AxiosLib = require("axios").default;
@@ -18,8 +18,9 @@ axios.interceptors.request.use((x) => {
...x.headers
};
const printable = `${new Date()} | Request: ${x.method.toUpperCase()} | ${x.url
} | ${JSON.stringify(x.data)} | ${JSON.stringify(headers)}`;
const printable = `${new Date()} | Request: ${x.method.toUpperCase()} | ${
x.url
} | ${JSON.stringify(x.data)} | ${JSON.stringify(headers)}`;
//console.log(printable);
WsLogger.createJsonEvent(socket, "SILLY", `Raw Request: ${printable}`, x.data);
@@ -146,7 +147,9 @@ async function PbsCalculateAllocationsAp(socket, billids) {
...billHash[key],
Amount: billHash[key].Amount.toFormat("0.00")
});
APAmount = APAmount.add(billHash[key].Amount); //Calculate the total expense for the bill iteratively to create the corresponding credit to AP.
//Calculate the total expense for the bill iteratively to
// create the corresponding credit to AP.
APAmount = APAmount.add(billHash[key].Amount);
}
});
@@ -174,9 +177,13 @@ exports.PbsCalculateAllocationsAp = PbsCalculateAllocationsAp;
async function QueryBillData(socket, billids) {
WsLogger.createLogEvent(socket, "DEBUG", `Querying bill data for id(s) ${billids}`);
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {});
const currentToken =
(socket?.data && socket.data.authToken) || (socket?.handshake?.auth && socket.handshake.auth.token);
const result = await client
.setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` })
.setHeaders({ Authorization: `Bearer ${currentToken}` })
.request(queries.GET_PBS_AP_ALLOCATIONS, { billids: billids });
WsLogger.createLogEvent(socket, "SILLY", `Bill data query result ${JSON.stringify(result, null, 2)}`);
return result;
@@ -191,7 +198,32 @@ function getCostAccount(billline, respcenters) {
return respcenters.costs.find((c) => c.name === acctName);
}
exports.PbsExportAp = async function (socket, { billids, txEnvelope }) {
async function MarkApExported(socket, billids) {
WsLogger.createLogEvent(socket, "DEBUG", `Marking bills as exported for id ${billids}`);
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {});
const currentToken =
(socket?.data && socket.data.authToken) || (socket?.handshake?.auth && socket.handshake.auth.token);
const result = await client
.setHeaders({ Authorization: `Bearer ${currentToken}` })
.request(queries.MARK_BILLS_EXPORTED, {
billids,
bill: {
exported: true,
exported_at: new Date()
},
logs: socket.bills.map((bill) => ({
bodyshopid: socket.bodyshop.id,
billid: bill.id,
successful: true,
useremail: socket.user.email
}))
});
return result;
}
const defaultHandler = async (socket, { billids, txEnvelope }) => {
WsLogger.createLogEvent(socket, "DEBUG", `Exporting selected AP.`);
//apAllocations has the same shap as the lines key for the accounting posting to PBS.
@@ -222,24 +254,4 @@ exports.PbsExportAp = async function (socket, { billids, txEnvelope }) {
socket.emit("ap-export-complete");
};
async function MarkApExported(socket, billids) {
WsLogger.createLogEvent(socket, "DEBUG", `Marking bills as exported for id ${billids}`);
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {});
const result = await client
.setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` })
.request(queries.MARK_BILLS_EXPORTED, {
billids,
bill: {
exported: true,
exported_at: new Date()
},
logs: socket.bills.map((bill) => ({
bodyshopid: socket.bodyshop.id,
billid: bill.id,
successful: true,
useremail: socket.user.email
}))
});
return result;
}
exports.PbsExportAp = defaultHandler;

View File

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