diff --git a/fortellis-scratch.js b/fortellis-scratch.js deleted file mode 100644 index b37e6e87c..000000000 --- a/fortellis-scratch.js +++ /dev/null @@ -1,305 +0,0 @@ -const path = require('path'); -const Dinero = require('dinero.js'); -const { gql } = require('graphql-request'); -const queries = require('./server/graphql-client/queries'); -const GraphQLClient = require('graphql-request').GraphQLClient; -const logger = require('./server/utils/logger'); -const AxiosLib = require('axios').default; -const axios = AxiosLib.create(); -const uuid = require('uuid').v4; - -const FORTELLIS_KEY = 'X1FxzLyOk3kjHvMbzdPQXFZShkdbgzuo'; -const FORTELLIS_SECRET = '7Yvs0wpQeHcUS5r95ht8pqOaAvBq7dHV'; -const FORTELLIS_AUTH_URL = 'https://identity.fortellis.io/oauth2/aus1p1ixy7YL8cMq02p7/v1/token'; -const FORTELLIS_URL = 'https://api.fortellis.io'; -const SubscriptionID = '5b527d7d-baf3-40bc-adae-e7a541e37363'; -let SubscriptionMeta = null; -//const SubscriptionID = "cb59fa04-e53e-4b57-b071-80a48ebc346c"; - -function sleep(time, callback) { - var stop = new Date().getTime(); - while (new Date().getTime() < stop + time) {} - callback(); -} -async function GetAuthToken() { - const { - data: { access_token, expires_in, token_type }, - } = await axios.post( - FORTELLIS_AUTH_URL, - {}, - { - auth: { - username: FORTELLIS_KEY, - password: FORTELLIS_SECRET, - }, - params: { - grant_type: 'client_credentials', - scope: 'anonymous', - }, - }, - ); - return access_token; -} - -async function FetchSubscriptions() { - const access_token = await GetAuthToken(); - try { - const subscriptions = await axios.get( - `https://subscriptions.fortellis.io/v1/solution/subscriptions`, - { - headers: { Authorization: `Bearer ${access_token}` }, - }, - ); - - return subscriptions.data.subscriptions; - } catch (error) { - console.log('🚀 ~ FetchSubscriptions ~ error:', error); - } -} -async function GetBulkVendors() { - const departmentIds = (await FetchSubscriptions()) - .find((s) => s.subscriptionId === SubscriptionID) //Get the subscription object. - ?.apiDmsInfo.find((info) => info.name === 'CDK Drive Async Vendors')?.departments; //Departments are categorized by API name and have an array of departments. - - const access_token = await GetAuthToken(); - const ReqId = uuid(); - try { - //TODO: This is pointing towards the test environment. Need to carefully watch for the production switch. - const Vendors = await axios.get(`https://api.fortellis.io/cdk-test/drive/vendor/v2/bulk`, { - headers: { - Authorization: `Bearer ${access_token}`, - 'Subscription-Id': SubscriptionID, - 'Request-Id': ReqId, - 'Department-Id': departmentIds[0].id, - }, - }); - - //Returns a long poll. Need to wait specified seconds until checking. - console.log( - '🚀 ~ GetBulkVendors ~ Vendors - waiting to execute callback:', - Vendors.data.checkStatusAfterSeconds, - ); - sleep(Vendors.data.checkStatusAfterSeconds * 1000, async () => { - const VendorsResult = await axios.get(Vendors.data._links.status.href, { - headers: { - Authorization: `Bearer ${access_token}`, - 'Subscription-Id': SubscriptionID, - 'Request-Id': ReqId, - 'Department-Id': departmentIds[0].id, - }, - }); - - //This may have to check again if it isn't ready. - const VendorsResult2 = await axios.get(VendorsResult.data._links.result.href, { - headers: { - Authorization: `Bearer ${access_token}`, - 'Subscription-Id': SubscriptionID, - 'Request-Id': ReqId, - 'Department-Id': departmentIds[0].id, - }, - }); - console.log('🚀 ~ sleep ~ VendorsResult2:', VendorsResult2); - }); - - console.log('🚀 ~ GetBulkVendors ~ Vendors:', ReqId, Vendors.data); - } catch (error) { - console.log('🚀 ~ GetBulkVendors ~ error:', ReqId, error); - } -} - -async function FetchVehicles({ SubscriptionID }) { - const access_token = await GetAuthToken(); - try { - //This doesn't seem to work as it is for production only. - const Vehicles = await axios.get(`https://api.fortellis.io/cdkdrive/service/v1/vehicles/`, { - headers: { Authorization: `Bearer ${access_token}`, 'Subscription-Id': SubscriptionID }, - }); - console.log('🚀 ~ FetchVehicles ~ Vehicles:', Vehicles); - - return Vehicles.data; - } catch (error) { - console.log('🚀 ~ FetchVehicles ~ error:', error); - } -} - -async function PostVehicleServiceHistory() { - const access_token = await GetAuthToken(); - const ReqId = uuid(); - const departmentIds = (await FetchSubscriptions()) - .find((s) => s.subscriptionId === SubscriptionID) //Get the subscription object. - ?.apiDmsInfo.find((info) => info.name === 'CDK Drive Async Vendors')?.departments; //Departments are categorized by API name and have an array of departments. - - //Need to get a vehicle ID from somewhere. - const vehicles = await FetchVehicles({ SubscriptionID }); - try { - //TODO: This is pointing towards the test environment. Need to carefully watch for the production switch. - const Vendors = await axios.post( - `https://api.fortellis.io/cdk-test/drive/post/service-vehicle-history-mgmt/v2/ - `, - { - headers: { - Authorization: `Bearer ${access_token}`, - 'Subscription-Id': SubscriptionID, - 'Request-Id': ReqId, - 'Department-Id': departmentIds[0].id, - }, - }, - ); - } catch (error) { - console.log('🚀 ~ PostVehicleServiceHistory ~ error:', ReqId, error); - } -} - -//PostVehicleServiceHistory(); -//GetBulkVendors(); - -async function GetDepartmentId() { - const departmentIds = await FetchSubscriptions(); - console.log('🚀 ~ GetDepartmentId ~ departmentIds:', departmentIds); - const departmentIds2 = departmentIds - .find((s) => s.subscriptionId === SubscriptionID) //Get the subscription object. - ?.apiDmsInfo.find((info) => info.name === 'CDK Drive Async Vendors')?.departments; //Departments are categorized by API name and have an array of departments. - - return departmentIds[0].id; -} -//////////////////GL WIP Section ////////////////////// -async function OrgHelpers() { - console.log('Executing Org Helpers'); - const ReqId = uuid(); - const access_token = await GetAuthToken(); - const DepartmentId = await GetDepartmentId(); - - try { - //This doesn't seem to work as it is for production only. - const OrgHelpers = await axios.get( - `https://api.fortellis.io/cdk-test/drive/businessofficeglwippost/orgHelper`, - { - headers: { - Authorization: `Bearer ${access_token}`, - 'Subscription-Id': SubscriptionID, - 'Request-Id': ReqId, - 'Department-Id': DepartmentId, - }, - }, - ); - console.log('🚀 ~ OrgHelpers ~ Data:', OrgHelpers); - - return OrgHelpers.data; - } catch (error) { - console.log('🚀 ~ OrgHelpers ~ error:', error); - } -} -async function JournalHelpers({ glCompanyNumber }) { - console.log('Executing Journal Helpers'); - const ReqId = uuid(); - const access_token = await GetAuthToken(); - const DepartmentId = await GetDepartmentId(); - - try { - //This doesn't seem to work as it is for production only. - const JournalHelpers = await axios.get( - `https://api.fortellis.io/cdk-test/drive/businessofficeglwippost/jrnlHelper/${glCompanyNumber}`, - { - headers: { - Authorization: `Bearer ${access_token}`, - 'Subscription-Id': SubscriptionID, - 'Request-Id': ReqId, - 'Department-Id': DepartmentId, - }, - }, - ); - console.log('🚀 ~ JournalHelpers ~ Data:', JournalHelpers); - return JournalHelpers.data; - } catch (error) { - console.log('🚀 ~ JournalHelpers ~ error:', error); - } -} - -async function GlSalesChain() { - console.log('Executing GL Sales Chain'); - const ReqId = uuid(); - const access_token = await GetAuthToken(); - const DepartmentId = await GetDepartmentId(); - - try { - //This doesn't seem to work as it is for production only. - const GlSalesChain = await axios.get( - `https://api.fortellis.io/cdk-test/drive/businessofficeglwippost/glSalesChain`, - { - headers: { - Authorization: `Bearer ${access_token}`, - 'Subscription-Id': SubscriptionID, - 'Request-Id': ReqId, - 'Department-Id': DepartmentId, - }, - }, - ); - console.log('🚀 ~ GlSalesChain ~ Data:', GlSalesChain); - return GlSalesChain.data; - } catch (error) { - console.log('🚀 ~ GlSalesChain ~ error:', error); - } -} -async function GlExpenseAllocation() { - console.log('Executing GL Expense Allocation'); - const ReqId = uuid(); - const access_token = await GetAuthToken(); - const DepartmentId = await GetDepartmentId(); - - try { - //This doesn't seem to work as it is for production only. - const GlExpenseAllocation = await axios.get( - `https://api.fortellis.io/cdk-test/drive/businessofficeglwippost/glExpenseAllocation`, - { - headers: { - Authorization: `Bearer ${access_token}`, - 'Subscription-Id': SubscriptionID, - 'Request-Id': ReqId, - 'Department-Id': DepartmentId, - }, - }, - ); - console.log('🚀 ~ GlExpenseAllocation ~ Data:', GlExpenseAllocation); - return GlExpenseAllocation.data; - } catch (error) { - console.log('🚀 ~ GlSalesChain ~ error:', error); - } -} - -///EXEC FUNCTIONS -async function PostAccountsGLWIP() { - //const orgHelpers = await OrgHelpers(); - //const jrnlHelpers = await JournalHelpers({ glCompanyNumber: orgHelpers[0].coID }); - - //const glSalesChain = await GlSalesChain(); - const glExpenseAllocation = await GlExpenseAllocation(); -} - -//PostAccountsGLWIP(); - -async function GetCOA() { - console.log('Executing GetCOA'); - const ReqId = uuid(); - const access_token = await GetAuthToken(); - const DepartmentId = await GetDepartmentId(); - - try { - //This doesn't seem to work as it is for production only. - const GetCOA = await axios.get( - `https://api.fortellis.io/cdk-test/drive/chartofaccounts/v2/bulk`, - { - headers: { - Authorization: `Bearer ${access_token}`, - 'Subscription-Id': SubscriptionID, - 'Request-Id': ReqId, - 'Department-Id': DepartmentId, - }, - }, - ); - console.log('🚀 ~ GetCOA ~ Data:', GetCOA); - return GetCOA.data; - } catch (error) { - console.log('🚀 ~ GetCOA ~ error:', error); - } -} -GetCOA(); diff --git a/fortellis.js b/fortellis.js deleted file mode 100644 index 4c6a7553a..000000000 --- a/fortellis.js +++ /dev/null @@ -1,235 +0,0 @@ -const path = require("path"); -const AxiosLib = require("axios").default; -const axios = AxiosLib.create(); -const uuid = require("uuid").v4; - -const FORTELLIS_KEY = "X1FxzLyOk3kjHvMbzdPQXFZShkdbgzuo"; //TODO: Regenerate these keys after testing and move to env vars. -const FORTELLIS_SECRET = "7Yvs0wpQeHcUS5r95ht8pqOaAvBq7dHV"; -const FORTELLIS_AUTH_URL = "https://identity.fortellis.io/oauth2/aus1p1ixy7YL8cMq02p7/v1/token"; -const FORTELLIS_URL = "https://api.fortellis.io"; -const ENVSubscriptionID = "5b527d7d-baf3-40bc-adae-e7a541e37363"; //TODO: Replace with the bodyshop.cdk_dealerid -let SubscriptionMeta = null; -//const ENVSubscriptionID = 'cb59fa04-e53e-4b57-b071-80a48ebc346c'; - -async function GetAuthToken() { - //Done with Authorization Code Flow - //https://docs.fortellis.io/docs/tutorials/solution-integration/authorization-code-flow/ - const { - data: { access_token, expires_in, token_type } - } = await axios.post( - FORTELLIS_AUTH_URL, - {}, - { - auth: { - username: FORTELLIS_KEY, - password: FORTELLIS_SECRET - }, - params: { - grant_type: "client_credentials", - scope: "anonymous" - } - } - ); - return access_token; -} - -async function FetchSubscriptions() { - const access_token = await GetAuthToken(); - try { - const subscriptions = await axios.get(`https://subscriptions.fortellis.io/v1/solution/subscriptions`, { - headers: { Authorization: `Bearer ${access_token}` } - }); - SubscriptionMeta = subscriptions.data.subscriptions.find((s) => s.subscriptionId === ENVSubscriptionID); - return SubscriptionMeta; - } catch (error) { - console.log("🚀 ~ FetchSubscriptions ~ error:", error); - } -} - -async function GetDepartmentId({ apiName, debug = false }) { - if (!apiName) throw new Error("apiName not provided. Unable to get department without apiName."); - if (debug) { - console.log("API Names & Departments "); - console.log("==========="); - console.log( - JSON.stringify( - SubscriptionMeta.apiDmsInfo.map((a) => ({ - name: a.name, - departments: a.departments.map((d) => d.id) - })), - null, - 4 - ) - ); - console.log("==========="); - } - const departmentIds2 = SubscriptionMeta.apiDmsInfo //Get the subscription object. - .find((info) => info.name === apiName)?.departments; //Departments are categorized by API name and have an array of departments. - - return departmentIds2[0].id; //TODO: This makes the assumption that there is only 1 department. -} - -async function MakeFortellisCall({ apiName, url, headers = {}, body = {}, type = "post", debug = false }) { - if (debug) console.log(`Executing ${type} to ${url}`); - const ReqId = uuid(); - const access_token = await GetAuthToken(); - const DepartmentId = await GetDepartmentId({ apiName, debug }); - - if (debug) { - console.log( - `ReqID: ${ReqId} | SubscriptionID: ${SubscriptionMeta.subscriptionId} | DepartmentId: ${DepartmentId}` - ); - console.log(`Body Contents: ${JSON.stringify(body, null, 4)}`); - } - - try { - let result; - switch (type) { - case "post": - default: - result = await axios.post(url, body, { - headers: { - Authorization: `Bearer ${access_token}`, - "Subscription-Id": SubscriptionMeta.subscriptionId, - "Request-Id": ReqId, - "Department-Id": DepartmentId, - ...headers - } - }); - break; - case "get": - result = await axios.get(url, { - headers: { - Authorization: `Bearer ${access_token}`, - "Subscription-Id": SubscriptionMeta.subscriptionId, - "Request-Id": ReqId, - "Department-Id": DepartmentId, - ...headers - } - }); - break; - } - - if (debug) { - console.log(`ReqID: ${ReqId} Data`); - console.log(JSON.stringify(result.data, null, 4)); - } - - if (result.data.checkStatusAfterSeconds) { - return DelayedCallback({ - delayMeta: result.data, - access_token, - SubscriptionID: SubscriptionMeta.subscriptionId, - ReqId, - departmentIds: DepartmentId - }); - } - return result.data; - } catch (error) { - console.log(`ReqID: ${ReqId} Error`, error.response?.data); - //console.log(`ReqID: ${ReqId} Full Error`, JSON.stringify(error, null, 4)); - } -} -//Get the status meta, then keep checking and return the result. -async function DelayedCallback({ delayMeta, access_token, SubscriptionID, ReqId, departmentIds }) { - for (let index = 0; index < 5; index++) { - await sleep(delayMeta.checkStatusAfterSeconds * 1000); - //Check to see if the call is ready. - const statusResult = await axios.get(delayMeta._links.status.href, { - headers: { - Authorization: `Bearer ${access_token}`, - "Subscription-Id": SubscriptionID, - "Request-Id": ReqId, - "Department-Id": departmentIds[0].id - } - }); - - //TODO: Add a check if the status result is not ready, to try again. - if (statusResult.data.status === "complete") { - //This may have to check again if it isn't ready. - const batchResult = await axios.get(statusResult.data._links.result.href, { - headers: { - Authorization: `Bearer ${access_token}`, - "Subscription-Id": SubscriptionID, - "Request-Id": ReqId, - //"Department-Id": departmentIds[0].id - } - }); - return batchResult; - } else { - return "Error!!! Still need to implement batch waiting."; - } - } -} -function sleep(ms) { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -async function GetCOA() { - console.log("Executing GetCOA"); - await MakeFortellisCall({ - debug: true, - type: "get", - apiName: "CDK Drive Post Accounts GL WIP", - url: `https://api.fortellis.io/cdk-test/drive/chartofaccounts/v2/bulk`, - waitForResult: true - }); -} - -async function StartWIP() { - const TransactionWip = MakeFortellisCall({ - url: "https://api.fortellis.io/cdk-test/drive/glwippost/startWIP", - apiName: "CDK Drive Post Accounts GL WIP", - body: { - acctgDate: "2023-09-26", //job.invoice - desc: "TEST TRANSACTION", - docType: "3", //pulled from Doc Type workbook - m13Flag: "0", // Is this a M13 entry. Presumanbly always 0 - refer: "RO12345", //Supposed to be a doc reference number. Presumably the RO? - srcCo: "77", - srcJrnl: "80", - userID: "csr", //bodyshop user - userName: "PROGRAM, PARTNER*ADP" //Can leave blank to have this return to default. - }, - debug: true - }); - - return TransactionWip; -} - -async function InsertBatch({ transID }) { - const TransactionWip = MakeFortellisCall({ - url: "https://api.fortellis.io/cdk-test/drive/glwippost/transWIP", - apiName: "CDK Drive Post Accounts GL WIP", - body: [ - { - acct: "", - cntl: "", - cntl2: null, - credtMemoNo: null, - postAmt: Math.round(payer.amount * 100), - postDesc: "", //Required if required by the DMS setup - prod: null, //Productivity Number - statCnt: 1, //Auto count, leave as 1. - transID: transID, - trgtCoID: "77" //Add this to read from the header - } - ], - debug: true - }); -} - -async function DoTheThings() { - await FetchSubscriptions(); - //What do we have access to? - console.log("Sub Access : ", SubscriptionMeta.apiDmsInfo.map((i) => i.name).join(", ")); - await GetCOA(); - - return; - - //Insert Transactions - const TransactionHeader = await StartWIP(); - const BatchResult = await InsertBatch({ transID: TransactionHeader.transID }); -} - -DoTheThings(); diff --git a/server/accounting/pbs/pbs-job-export.js b/server/accounting/pbs/pbs-job-export.js index 911382e15..ee6360682 100644 --- a/server/accounting/pbs/pbs-job-export.js +++ b/server/accounting/pbs/pbs-job-export.js @@ -157,7 +157,7 @@ async function QueryJobData(socket, jobid) { .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .request(queries.QUERY_JOBS_FOR_PBS_EXPORT, { id: jobid }); - WsLogger.createLogEvent(socket, "DEBUG", `Job data query result ${JSON.stringify(result, null, 2)}`); + //WsLogger.createLogEvent(socket, "DEBUG", `Job data query result ${JSON.stringify(result, null, 2)}`); return result.jobs_by_pk; } @@ -687,13 +687,13 @@ async function InsertFailedExportLog(socket, error) { const result = await client .setHeaders({ Authorization: `Bearer ${socket.handshake.auth.token}` }) .request(queries.INSERT_EXPORT_LOG, { - log: { + logs: [{ bodyshopid: socket.JobData.bodyshop.id, jobid: socket.JobData.id, successful: false, message: JSON.stringify(error), useremail: socket.user.email - } + }] }); return result; diff --git a/server/cdk/cdk-calculate-allocations.js b/server/cdk/cdk-calculate-allocations.js index 4fca0fe9b..697a050bd 100644 --- a/server/cdk/cdk-calculate-allocations.js +++ b/server/cdk/cdk-calculate-allocations.js @@ -44,7 +44,7 @@ async function QueryJobData(connectionData, token, jobid, isFortellis) { 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 }); - loggingFunction(connectionData, "DEBUG", `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; } diff --git a/server/cdk/cdk-job-export.js b/server/cdk/cdk-job-export.js index 13a8553ec..c5d7835b3 100644 --- a/server/cdk/cdk-job-export.js +++ b/server/cdk/cdk-job-export.js @@ -159,7 +159,7 @@ async function QueryJobData(socket, jobid) { .setHeaders({ Authorization: `Bearer ${currentToken}` }) .request(queries.QUERY_JOBS_FOR_CDK_EXPORT, { id: jobid }); - WsLogger.createLogEvent(socket, "SILLY", `Job data query result ${JSON.stringify(result, null, 2)}`); + //WsLogger.createLogEvent(socket, "SILLY", `Job data query result ${JSON.stringify(result, null, 2)}`); return result.jobs_by_pk; } @@ -993,13 +993,13 @@ async function InsertFailedExportLog(socket, error) { const result = await client .setHeaders({ Authorization: `Bearer ${currentToken}` }) .request(queries.INSERT_EXPORT_LOG, { - log: { + logs: [{ bodyshopid: socket.JobData.bodyshop.id, jobid: socket.JobData.id, successful: false, message: JSON.stringify(error), useremail: socket.user.email - } + }] }); return result; diff --git a/server/fortellis/fortellis-helpers.js b/server/fortellis/fortellis-helpers.js index 3a46ab484..39539baf4 100644 --- a/server/fortellis/fortellis-helpers.js +++ b/server/fortellis/fortellis-helpers.js @@ -27,9 +27,6 @@ class FortellisApiError extends Error { } axiosCurlirize(axios, (result, err) => { - const { command } = result; - console.log("*** ~ axiosCurlirize ~ command:", command); - // if (err) { // use your logger here // } else { @@ -88,7 +85,8 @@ async function FetchSubscriptions({ redisHelpers, socket, jobid, SubscriptionObj } else { const access_token = await GetAuthToken(); const subscriptions = await axios.get(`https://subscriptions.fortellis.io/v1/solution/subscriptions`, { - headers: { Authorization: `Bearer ${access_token}` } + headers: { Authorization: `Bearer ${access_token}` }, + logRequest: false }); const SubscriptionMeta = subscriptions.data.subscriptions.find((s) => s.subscriptionId === SubscriptionID); if (setSessionTransactionData) { @@ -137,7 +135,7 @@ async function MakeFortellisCall({ headers = {}, body = {}, type = "post", - debug = true, + debug = false, requestPathParams, requestSearchParams = [], //Array of key/value strings like [["key", "value"]] jobid, @@ -209,7 +207,7 @@ async function MakeFortellisCall({ if (debug) { console.log(`ReqID: ${ReqId} Data`); - console.log(JSON.stringify(result.data, null, 4)); + //console.log(JSON.stringify(result.data, null, 4)); } if (result.data.checkStatusAfterSeconds) { @@ -221,6 +219,21 @@ async function MakeFortellisCall({ departmentIds: DepartmentId }); } + + logger.log( + "fortellis-log-event-json", + "DEBUG", + socket?.user?.email, + jobid, + { + requestcurl: result.config.curlCommand, + reqid: result.config.headers["Request-Id"] || null, + subscriptionId: result.config.headers["Subscription-Id"] || null, + resultdata: result.data, + resultStatus: result.status + }, + ); + return result.data; } catch (error) { console.log(`ReqID: ${ReqId} Error`, error.response?.data); @@ -236,6 +249,20 @@ async function MakeFortellisCall({ originalError: error }; + logger.log( + "fortellis-log-event-error", + "ERROR", + socket?.user?.email, + socket?.recordid, + { + wsmessage: "",//message, + curl: error.config.curl.curlCommand, + reqid: error.request.headers["Request-Id"] || null, + subscriptionId: error.request.headers["Subscription-Id"] || null, + }, + true + ); + // CreateFortellisLogEvent(socket, "ERROR", `Error in MakeFortellisCall for ${apiName}: ${error.message}`, { // ...errorDetails, // errorStack: error.stack @@ -376,6 +403,13 @@ const FortellisActions = { type: "post", apiName: "CDK Drive Post Accounts GL" }, + DeleteTranWip: { + url: isProduction + ? "https://api.fortellis.io/cdk/drive/glpost/postWIP" + : "https://api.fortellis.io/cdk-test/drive/glpost/postWIP", + type: "post", + apiName: "CDK Drive Post Accounts GL" + }, QueryErrorWip: { url: isProduction ? "https://api.fortellis.io/cdk/drive/glpost/errWIP/" //Get requests should have the trailing slash/ diff --git a/server/fortellis/fortellis.js b/server/fortellis/fortellis.js index 9c4a0a50c..f46de5cdb 100644 --- a/server/fortellis/fortellis.js +++ b/server/fortellis/fortellis.js @@ -252,80 +252,68 @@ async function FortellisSelectedCustomer({ socket, redisHelpers, selectedCustome CreateFortellisLogEvent(socket, "DEBUG", `{5.1} Creating Transaction with ID ${DMSTransHeader.transID}`); - // const DMSBatchTxn = await InsertDmsBatchWip({ socket, redisHelpers, JobData }); - // await setSessionTransactionData( - // socket.id, - // getTransactionType(jobid), - // FortellisCacheEnums.DMSBatchTxn, - // DMSBatchTxn, - // defaultFortellisTTL - // ); - if (DMSTransHeader.rtnCode === "0") { - CreateFortellisLogEvent(socket, "DEBUG", `{6} Attempting to post Transaction with ID ${DMSTransHeader.transID}`); + try { + CreateFortellisLogEvent(socket, "DEBUG", `{6} Attempting to post Transaction with ID ${DMSTransHeader.transID}`); - const DmsBatchTxnPost = await PostDmsBatchWip({ socket, redisHelpers, JobData }); - await setSessionTransactionData( - socket.id, - getTransactionType(jobid), - FortellisCacheEnums.DmsBatchTxnPost, - DmsBatchTxnPost, - defaultFortellisTTL - ); - - if (DmsBatchTxnPost.rtnCode === "0") { - //TODO: Validate this is a string and not # - //something - CreateFortellisLogEvent(socket, "DEBUG", `{6} Successfully posted transaction to DMS.`); - - await MarkJobExported({ socket, jobid: JobData.id }); - - CreateFortellisLogEvent(socket, "DEBUG", `{5} Updating Service Vehicle History.`); - const DMSVehHistory = await InsertServiceVehicleHistory({ socket, redisHelpers, JobData }); + const DmsBatchTxnPost = await PostDmsBatchWip({ socket, redisHelpers, JobData }); // 2 in 1 call that includes a post and the transactions. await setSessionTransactionData( socket.id, getTransactionType(jobid), - FortellisCacheEnums.DMSVehHistory, - DMSVehHistory, + FortellisCacheEnums.DmsBatchTxnPost, + DmsBatchTxnPost, defaultFortellisTTL ); - socket.emit("export-success", JobData.id); - } else { - //Get the error code + + + if (DmsBatchTxnPost.rtnCode === "0") { + //TODO: Validate this is a string and not # + //something + CreateFortellisLogEvent(socket, "DEBUG", `{6} Successfully posted transaction to DMS.`); + + await MarkJobExported({ socket, jobid: JobData.id, JobData }); + + CreateFortellisLogEvent(socket, "DEBUG", `{5} Updating Service Vehicle History.`); + const DMSVehHistory = await InsertServiceVehicleHistory({ socket, redisHelpers, JobData }); + await setSessionTransactionData( + socket.id, + getTransactionType(jobid), + FortellisCacheEnums.DMSVehHistory, + DMSVehHistory, + defaultFortellisTTL + ); + socket.emit("export-success", JobData.id); + } else { + //There was something wrong. Throw an error to trigger clean up. + throw new Error("Error posting DMS Batch Transaction"); + } + + + } catch (error) { + //Clean up the transaction and insert a faild error code + // //Get the error code CreateFortellisLogEvent(socket, "DEBUG", `{6.1} Getting errors for Transaction ID ${DMSTransHeader.transID}`); await QueryDmsErrWip({ socket, redisHelpers, JobData }); const DmsError = await QueryDmsErrWip({ socket, redisHelpers, JobData }); // //Delete the transaction - CreateFortellisLogEvent(socket, "DEBUG", `{{ 6.2 } Deleting Transaction ID ${DMSTransHeader.transID}`); + CreateFortellisLogEvent(socket, "DEBUG", `{6.2} Deleting Transaction ID ${DMSTransHeader.transID}`); - const DmsBatchTxnDelete = await DeleteDmsWip({ socket, redisHelpers, JobData }); + await DeleteDmsWip({ socket, redisHelpers, JobData }); - DmsError.errMsg.map( + DmsError.errLine.map( (e) => e !== null && e !== "" && - CreateFortellisLogEvent(socket, "ERROR", `Error(s) encountered in posting transaction.${e} `) + CreateFortellisLogEvent(socket, "ERROR", `Error encountered in posting transaction => ${e} `) ); await InsertFailedExportLog({ socket, JobData, - error: DmsError.errMsg + error: DmsError.errLine }); } - } else { - //Creating transaction failed. - CreateFortellisLogEvent( - socket, - "ERROR", - `DMS Batch Return code was not successful: ${DMSTransHeader.rtnCode} - ${DMSTransHeader.sendline}` - ); - await InsertFailedExportLog({ - socket, - JobData, - error: `DMS Batch Return code was not successful: ${DMSTransHeader.rtnCode} - ${DMSTransHeader.sendline}` - }); } } catch (error) { CreateFortellisLogEvent(socket, "ERROR", `Error in FortellisSelectedCustomer - ${error} `, { @@ -1231,7 +1219,6 @@ async function PostDmsBatchWip({ socket, redisHelpers, JobData }) { transID: DMSTransHeader.transID, transWipReqList: await GenerateTransWips({ socket, redisHelpers, JobData }) }, - overrideDepartmentId: "D100152198" }); return result; } catch (error) { @@ -1260,7 +1247,6 @@ async function QueryDmsErrWip({ socket, redisHelpers, JobData }) { jobid: JobData.id, requestPathParams: DMSTransHeader.transID, body: {}, - overrideDepartmentId: "D100152198" }); return result; } catch (error) { @@ -1282,7 +1268,7 @@ async function DeleteDmsWip({ socket, redisHelpers, JobData }) { ); const result = await MakeFortellisCall({ - ...FortellisActions.PostBatchWip, + ...FortellisActions.DeleteTranWip, headers: {}, redisHelpers, socket, @@ -1291,7 +1277,6 @@ async function DeleteDmsWip({ socket, redisHelpers, JobData }) { opCode: "D", transID: DMSTransHeader.transID }, - overrideDepartmentId: "D100152198" }); return result; } catch (error) { @@ -1303,7 +1288,7 @@ async function DeleteDmsWip({ socket, redisHelpers, JobData }) { } } -async function MarkJobExported({ socket, jobid }) { +async function MarkJobExported({ socket, jobid, JobData }) { CreateFortellisLogEvent(socket, "ERROR", `Marking job as exported for id ${jobid}`); const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {}); @@ -1315,11 +1300,11 @@ async function MarkJobExported({ socket, jobid }) { .request(queries.MARK_JOB_EXPORTED, { jobId: jobid, job: { - status: socket.JobData.bodyshop.md_ro_statuses.default_exported || "Exported*", + status: JobData.bodyshop.md_ro_statuses.default_exported || "Exported*", date_exported: new Date() }, log: { - bodyshopid: socket.JobData.bodyshop.id, + bodyshopid: JobData.bodyshop.id, jobid: jobid, successful: true, useremail: socket.user.email, @@ -1343,13 +1328,13 @@ async function InsertFailedExportLog({ socket, JobData, error }) { const result = await client .setHeaders({ Authorization: `Bearer ${currentToken}` }) .request(queries.INSERT_EXPORT_LOG, { - log: { + logs: [{ bodyshopid: JobData.bodyshop.id, jobid: JobData.id, successful: false, message: JSON.stringify(error), useremail: socket.user.email - } + }] }); return result; diff --git a/server/graphql-client/queries.js b/server/graphql-client/queries.js index 60a37eebd..7965a171b 100644 --- a/server/graphql-client/queries.js +++ b/server/graphql-client/queries.js @@ -2173,19 +2173,7 @@ mutation UPDATE_BILLS($billids: [uuid!]!, $bill: bills_set_input!, $logs: [expor } }`; -exports.INSERT_EXPORT_LOG = ` -mutation INSERT_EXPORT_LOG($log: exportlog_insert_input!) { - insert_exportlog_one(object: $log) { - id - } -}`; -exports.QUERY_EXISTING_TRANSITION = ` -mutation INSERT_EXPORT_LOG($log: exportlog_insert_input!) { - insert_exportlog_one(object: $log) { - id - } -}`; exports.UPDATE_OLD_TRANSITION = `mutation UPDATE_OLD_TRANSITION($jobid: uuid!, $existingTransition: transitions_set_input!){ update_transitions(where:{jobid:{_eq:$jobid}, end:{_is_null:true