Compare commits

..

3 Commits

Author SHA1 Message Date
Allan Carr
92fd5b0315 IO-3503 Job Costing Bug Fix
Signed-off-by: Allan Carr <allan@imexsystems.ca>
2026-01-14 18:02:26 -08:00
Dave Richer
be2df79555 Merged in hotfix/2026-01-13 (pull request #2813)
Hotfix/2026 01 13 into master-AIO
2026-01-13 20:52:00 +00:00
Allan Carr
9c733702e4 Merged in feature/IO-3498-QBO-Auth-Token (pull request #2810)
IO-3498 QBO Auth Token

Approved-by: Dave Richer
2026-01-13 20:45:42 +00:00
5 changed files with 361 additions and 208 deletions

View File

@@ -57,3 +57,14 @@ exports.refresh = async (oauthClient, req) => {
});
}
};
exports.setNewRefreshToken = async (email, apiResponse) => {
// Deprecated - tokens are now auto-updated in the oauthClient and the token isn't pushed back from QBO API calls anymore
// logger.log("qbo-token-updated", "DEBUG", email, null, {apiResponse: apiResponse});
// await client.request(queries.SET_QBO_AUTH, {
// email,
// qbo_auth: { ...apiResponse.token, createdAt: Date.now() }
// });
};

View File

@@ -6,7 +6,7 @@ const Dinero = require("dinero.js");
const DineroQbFormat = require("../accounting-constants").DineroQbFormat;
const apiGqlClient = require("../../graphql-client/graphql-client").client;
const queries = require("../../graphql-client/queries");
const { refresh: refreshOauthToken } = require("./qbo-callback");
const { refresh: refreshOauthToken, setNewRefreshToken } = require("./qbo-callback");
const OAuthClient = require("intuit-oauth");
const moment = require("moment-timezone");
const findTaxCode = require("../qb-receivables-lines").findTaxCode;
@@ -87,17 +87,17 @@ exports.default = async (req, res) => {
} catch (error) {
logger.log("qbo-paybles-create-error", "ERROR", req.user.email, null, {
error:
error?.authResponse?.body ||
error?.response?.data?.Fault?.Error.map((e) => e.Detail).join(", ") ||
(error?.authResponse && error.authResponse.body) ||
error.response?.data?.Fault?.Error.map((e) => e.Detail).join(", ") ||
error?.message
});
ret.push({
billid: bill.id,
success: false,
errorMessage:
error?.authResponse?.body ||
error?.response?.data?.Fault?.Error.map((e) => e.Detail).join(", ") ||
error?.message
(error && error.authResponse && error.authResponse.body) ||
error.response?.data?.Fault?.Error.map((e) => e.Detail).join(", ") ||
(error && error.message)
});
//Add the export log error.
@@ -108,7 +108,9 @@ exports.default = async (req, res) => {
bodyshopid: bodyshop.id,
billid: bill.id,
successful: false,
message: JSON.stringify([error?.authResponse?.body || error?.message]),
message: JSON.stringify([
(error && error.authResponse && error.authResponse.body) || (error && error.message)
]),
useremail: req.user.email
}
]
@@ -134,7 +136,9 @@ async function QueryVendorRecord(oauthClient, qbo_realmId, req, bill) {
url: urlBuilder(
qbo_realmId,
"query",
`select * From vendor where DisplayName = '${StandardizeName(bill.vendor.name)}'`
`select *
From vendor
where DisplayName = '${StandardizeName(bill.vendor.name)}'`
),
method: "POST",
headers: {
@@ -146,17 +150,21 @@ async function QueryVendorRecord(oauthClient, qbo_realmId, req, bill) {
method: "POST",
name: "QueryVendorRecord",
billid: bill.id,
status: result.status,
status: result.response?.status,
bodyshopid: bill.job.shopid,
email: req.user.email
});
return result.json?.QueryResponse?.Vendor?.[0];
setNewRefreshToken(req.user.email, result);
return (
result.json &&
result.json.QueryResponse &&
result.json.QueryResponse.Vendor &&
result.json.QueryResponse.Vendor[0]
);
} catch (error) {
logger.log("qbo-payables-error", "DEBUG", req.user.email, bill.id, {
method: "QueryVendorRecord",
error: error.message,
stack: error.stack
error: (error && error.authResponse && error.authResponse.body) || (error && error.message),
method: "QueryVendorRecord"
});
throw error;
}
@@ -180,20 +188,16 @@ async function InsertVendorRecord(oauthClient, qbo_realmId, req, bill) {
method: "POST",
name: "InsertVendorRecord",
billid: bill.id,
status: result.status,
status: result.response?.status,
bodyshopid: bill.job.shopid,
email: req.user.email
});
if (result.status >= 400) {
throw new Error(JSON.stringify(result.json.Fault));
}
if (result.status === 200) return result?.json.Vendor;
setNewRefreshToken(req.user.email, result);
return result && result.json && result.json.Vendor;
} catch (error) {
logger.log("qbo-payables-error", "DEBUG", req.user.email, bill.id, {
method: "InsertVendorRecord",
validationError: error.message,
stack: error.stack
error: (error && error.authResponse && error.authResponse.body) || (error && error.message),
method: "InsertVendorRecord"
});
throw error;
}
@@ -246,7 +250,12 @@ async function InsertBill(oauthClient, qbo_realmId, req, bill, vendor, bodyshop)
}
//QB USA with GST
//This was required for the No. 1 Collision Group.
if (bodyshop.accountingconfig?.qbo && bodyshop.accountingconfig?.qbo_usa && bodyshop.region_config.includes("CA_")) {
if (
bodyshop.accountingconfig &&
bodyshop.accountingconfig.qbo &&
bodyshop.accountingconfig.qbo_usa &&
bodyshop.region_config.includes("CA_")
) {
lines.push({
DetailType: "AccountBasedExpenseLineDetail",
@@ -265,16 +274,16 @@ async function InsertBill(oauthClient, qbo_realmId, req, bill, vendor, bodyshop)
)
})
.percentage(bill.federal_tax_rate)
.toFormat(DineroQbFormat)
});
}
let billQbo, VendorCredit;
const billObject = {
const billQbo = {
VendorRef: {
value: vendor.Id
},
...(vendor.TermRef && !bill.is_credit_memo && {
...(vendor.TermRef && {
SalesTermRef: {
value: vendor.TermRef.value
}
@@ -292,30 +301,22 @@ async function InsertBill(oauthClient, qbo_realmId, req, bill, vendor, bodyshop)
DocNumber: bill.invoice_number,
//...(bill.job.class ? { ClassRef: { Id: classes[bill.job.class] } } : {}),
...(!(
bodyshop.accountingconfig?.qbo &&
bodyshop.accountingconfig?.qbo_usa &&
bodyshop.accountingconfig &&
bodyshop.accountingconfig.qbo &&
bodyshop.accountingconfig.qbo_usa &&
bodyshop.region_config.includes("CA_")
)
? { GlobalTaxCalculation: "TaxExcluded" }
: {}),
...(bodyshop.accountingconfig.qbo_departmentid?.trim() !== "" && {
DepartmentRef: { value: bodyshop.accountingconfig.qbo_departmentid }
}),
...(bodyshop.accountingconfig.qbo_departmentid &&
bodyshop.accountingconfig.qbo_departmentid.trim() !== "" && {
DepartmentRef: { value: bodyshop.accountingconfig.qbo_departmentid }
}),
PrivateNote: `RO ${bill.job.ro_number || ""}`,
Line: lines
};
if (bill.is_credit_memo) {
VendorCredit = billObject;
} else {
billQbo = billObject;
}
const logKey = bill.is_credit_memo ? "VendorCredit" : "billQbo";
const logValue = bill.is_credit_memo ? VendorCredit : billQbo;
logger.log("qbo-payable-objectlog", "DEBUG", req.user.email, bill.id, {
[logKey]: logValue
billQbo
});
try {
const result = await oauthClient.makeApiCall({
@@ -324,28 +325,25 @@ async function InsertBill(oauthClient, qbo_realmId, req, bill, vendor, bodyshop)
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(bill.is_credit_memo ? VendorCredit : billQbo)
body: JSON.stringify(billQbo)
});
logger.LogIntegrationCall({
platform: "QBO",
method: "POST",
name: "InsertBill",
billid: bill.id,
status: result.status,
status: result.response?.status,
bodyshopid: bill.job.shopid,
email: req.user.email
});
if (result.status >= 400) {
throw new Error(JSON.stringify(result.json.Fault));
}
if (result.status === 200) return result?.json;
setNewRefreshToken(req.user.email, result);
return result && result.json && result.json.Bill;
} catch (error) {
logger.log("qbo-payables-error", "DEBUG", req.user.email, bill.id, {
method: "InsertBill",
validationError: error.message,
error: error, //(error && error.authResponse && error.authResponse.body) || (error && error.message),
validationError: JSON.stringify(error?.response?.data),
accountmeta: JSON.stringify({ accounts, taxCodes, classes }),
stack: error.stack
method: "InsertBill"
});
throw error;
}
@@ -405,7 +403,9 @@ async function QueryMetaData(oauthClient, qbo_realmId, req, bodyshopid) {
url: urlBuilder(
qbo_realmId,
"query",
`select * From Account where AccountType in ('Cost of Goods Sold', 'Other Current Liability')`
`select *
From Account
where AccountType in ('Cost of Goods Sold', 'Other Current Liability')`
),
method: "POST",
headers: {
@@ -416,13 +416,18 @@ async function QueryMetaData(oauthClient, qbo_realmId, req, bodyshopid) {
platform: "QBO",
method: "POST",
name: "QueryAccountType",
status: accounts.status,
status: accounts.response?.status,
bodyshopid,
email: req.user.email
});
setNewRefreshToken(req.user.email, accounts);
const taxCodes = await oauthClient.makeApiCall({
url: urlBuilder(qbo_realmId, "query", `select * From TaxCode`),
url: urlBuilder(
qbo_realmId,
"query",
`select *
From TaxCode`
),
method: "POST",
headers: {
"Content-Type": "application/json"
@@ -437,7 +442,12 @@ async function QueryMetaData(oauthClient, qbo_realmId, req, bodyshopid) {
email: req.user.email
});
const classes = await oauthClient.makeApiCall({
url: urlBuilder(qbo_realmId, "query", `select * From Class`),
url: urlBuilder(
qbo_realmId,
"query",
`select *
From Class`
),
method: "POST",
headers: {
"Content-Type": "application/json"
@@ -451,14 +461,31 @@ async function QueryMetaData(oauthClient, qbo_realmId, req, bodyshopid) {
bodyshopid,
email: req.user.email
});
const taxCodeMapping = {};
const taxCodeMapping = Object.fromEntries((taxCodes.json?.QueryResponse?.TaxCode || []).map((t) => [t.Name, t.Id]));
taxCodes.json &&
taxCodes.json.QueryResponse &&
taxCodes.json.QueryResponse.TaxCode &&
taxCodes.json.QueryResponse.TaxCode.forEach((t) => {
taxCodeMapping[t.Name] = t.Id;
});
const accountMapping = Object.fromEntries(
(accounts.json?.QueryResponse?.Account || []).map((t) => [t.FullyQualifiedName, t.Id])
);
const accountMapping = {};
const classMapping = Object.fromEntries((classes.json?.QueryResponse?.Class || []).map((c) => [c.Name, c.Id]));
accounts.json &&
accounts.json.QueryResponse &&
accounts.json.QueryResponse.Account &&
accounts.json.QueryResponse.Account.forEach((t) => {
accountMapping[t.FullyQualifiedName] = t.Id;
});
const classMapping = {};
classes.json &&
classes.json.QueryResponse &&
classes.json.QueryResponse.Class &&
classes.json.QueryResponse.Class.forEach((t) => {
classMapping[t.Name] = t.Id;
});
return {
accounts: accountMapping,

View File

@@ -3,7 +3,7 @@ const Dinero = require("dinero.js");
const apiGqlClient = require("../../graphql-client/graphql-client").client;
const queries = require("../../graphql-client/queries");
const { refresh: refreshOauthToken } = require("./qbo-callback");
const { refresh: refreshOauthToken, setNewRefreshToken } = require("./qbo-callback");
const OAuthClient = require("intuit-oauth");
const moment = require("moment-timezone");
const {
@@ -145,7 +145,7 @@ exports.default = async (req, res) => {
ret.push({ paymentid: payment.id, success: true });
} catch (error) {
logger.log("qbo-payment-create-error", "ERROR", req.user.email, null, {
error: error?.authResponse?.body || error?.message
error: (error && error.authResponse && error.authResponse.body) || (error && error.message)
});
//Add the export log error.
if (elgen) {
@@ -155,7 +155,9 @@ exports.default = async (req, res) => {
bodyshopid: bodyshop.id,
paymentid: payment.id,
successful: false,
message: JSON.stringify([error?.authResponse?.body || error?.message]),
message: JSON.stringify([
(error && error.authResponse && error.authResponse.body) || (error && error.message)
]),
useremail: req.user.email
}
]
@@ -165,13 +167,14 @@ exports.default = async (req, res) => {
ret.push({
paymentid: payment.id,
success: false,
errorMessage: error?.authResponse?.body || error?.message
errorMessage: (error && error.authResponse && error.authResponse.body) || (error && error.message)
});
}
}
res.status(200).json(ret);
} catch (error) {
//console.log(error);
logger.log("qbo-payment-create-error", "ERROR", req.user.email, null, {
error: error.message,
stack: error.stack
@@ -199,7 +202,9 @@ async function InsertPayment(oauthClient, qbo_realmId, req, payment, parentRef)
CustomerRef: {
value: parentRef.Id
},
TxnDate: moment(payment.date).format("YYYY-MM-DD"),
TxnDate: moment(payment.date) //.tz(bodyshop.timezone)
.format("YYYY-MM-DD"),
//DueDate: bill.due_date && moment(bill.due_date).format("YYYY-MM-DD"),
DocNumber: payment.paymentnum,
TotalAmt: Dinero({
amount: Math.round(payment.amount * 100)
@@ -207,13 +212,19 @@ async function InsertPayment(oauthClient, qbo_realmId, req, payment, parentRef)
PaymentMethodRef: {
value: paymentMethods[payment.type]
},
PrivateNote: payment.memo?.substring(0, 4000)?.trim() ?? "",
PrivateNote: payment.memo
? payment.memo.length > 4000
? payment.memo.substring(0, 4000).trim()
: payment.memo.trim()
: "",
PaymentRefNum: payment.transactionid,
...(invoices?.length === 1 && invoices[0]
...(invoices && invoices.length === 1 && invoices[0]
? {
Line: [
{
Amount: Dinero({ amount: Math.round(payment.amount * 100) }).toFormat(DineroQbFormat),
Amount: Dinero({
amount: Math.round(payment.amount * 100)
}).toFormat(DineroQbFormat),
LinkedTxn: [
{
TxnId: invoices[0].Id,
@@ -242,20 +253,16 @@ async function InsertPayment(oauthClient, qbo_realmId, req, payment, parentRef)
method: "POST",
name: "InsertPayment",
paymentid: payment.id,
status: result.status,
status: result.response?.status,
bodyshopid: payment.job.shopid,
email: req.user.email
});
if (result.status >= 400) {
throw new Error(JSON.stringify(result.json.Fault));
}
if (result.status === 200) return result?.json.Customer;
setNewRefreshToken(req.user.email, result);
return result && result.Bill;
} catch (error) {
logger.log("qbo-payables-error", "DEBUG", req.user.email, payment.id, {
method: "InsertPayment",
validationError: error.message,
stack: error.stack
error: error && error.message,
method: "InsertPayment"
});
throw error;
}
@@ -263,7 +270,13 @@ async function InsertPayment(oauthClient, qbo_realmId, req, payment, parentRef)
async function QueryMetaData(oauthClient, qbo_realmId, req, ro_number, isCreditMemo, parentTierRef, bodyshopid) {
const invoice = await oauthClient.makeApiCall({
url: urlBuilder(qbo_realmId, "query", `select * From Invoice where DocNumber like '${ro_number}%'`),
url: urlBuilder(
qbo_realmId,
"query",
`select *
From Invoice
where DocNumber like '${ro_number}%'`
),
method: "POST",
headers: {
"Content-Type": "application/json"
@@ -273,12 +286,18 @@ async function QueryMetaData(oauthClient, qbo_realmId, req, ro_number, isCreditM
platform: "QBO",
method: "POST",
name: "QueryInvoice",
status: invoice.status,
status: invoice.response?.status,
bodyshopid,
email: req.user.email
});
const paymentMethods = await oauthClient.makeApiCall({
url: urlBuilder(qbo_realmId, "query", `select * From PaymentMethod`),
url: urlBuilder(
qbo_realmId,
"query",
`select *
From PaymentMethod`
),
method: "POST",
headers: {
"Content-Type": "application/json"
@@ -288,10 +307,11 @@ async function QueryMetaData(oauthClient, qbo_realmId, req, ro_number, isCreditM
platform: "QBO",
method: "POST",
name: "QueryPaymentMethod",
status: paymentMethods.status,
status: paymentMethods.response?.status,
bodyshopid,
email: req.user.email
});
setNewRefreshToken(req.user.email, paymentMethods);
// const classes = await oauthClient.makeApiCall({
// url: urlBuilder(qbo_realmId, "query", `select * From Class`),
@@ -301,9 +321,14 @@ async function QueryMetaData(oauthClient, qbo_realmId, req, ro_number, isCreditM
// },
// });
const paymentMethodMapping = Object.fromEntries(
(paymentMethods.json?.QueryResponse?.PaymentMethod || []).map((t) => [t.Name, t.Id])
);
const paymentMethodMapping = {};
paymentMethods.json &&
paymentMethods.json.QueryResponse &&
paymentMethods.json.QueryResponse.PaymentMethod &&
paymentMethods.json.QueryResponse.PaymentMethod.forEach((t) => {
paymentMethodMapping[t.Name] = t.Id;
});
// const accountMapping = {};
@@ -323,7 +348,12 @@ async function QueryMetaData(oauthClient, qbo_realmId, req, ro_number, isCreditM
if (isCreditMemo) {
const taxCodes = await oauthClient.makeApiCall({
url: urlBuilder(qbo_realmId, "query", `select * From TaxCode`),
url: urlBuilder(
qbo_realmId,
"query",
`select *
From TaxCode`
),
method: "POST",
headers: {
"Content-Type": "application/json"
@@ -333,12 +363,18 @@ async function QueryMetaData(oauthClient, qbo_realmId, req, ro_number, isCreditM
platform: "QBO",
method: "POST",
name: "QueryTaxCode",
status: taxCodes.status,
status: taxCodes.response?.status,
bodyshopid,
email: req.user.email
});
const items = await oauthClient.makeApiCall({
url: urlBuilder(qbo_realmId, "query", `select * From Item`),
url: urlBuilder(
qbo_realmId,
"query",
`select *
From Item`
),
method: "POST",
headers: {
"Content-Type": "application/json"
@@ -348,15 +384,28 @@ async function QueryMetaData(oauthClient, qbo_realmId, req, ro_number, isCreditM
platform: "QBO",
method: "POST",
name: "QueryItems",
status: items.status,
status: items.response?.status,
bodyshopid,
email: req.user.email
});
setNewRefreshToken(req.user.email, items);
const taxCodeMapping = Object.fromEntries((taxCodes.json?.QueryResponse?.TaxCode || []).map((t) => [t.Name, t.Id]));
const itemMapping = {};
const itemMapping = Object.fromEntries((items.json?.QueryResponse?.Item || []).map((item) => [item.Name, item.Id]));
items.json &&
items.json.QueryResponse &&
items.json.QueryResponse.Item &&
items.json.QueryResponse.Item.forEach((t) => {
itemMapping[t.Name] = t.Id;
});
const taxCodeMapping = {};
taxCodes.json &&
taxCodes.json.QueryResponse &&
taxCodes.json.QueryResponse.TaxCode &&
taxCodes.json.QueryResponse.TaxCode.forEach((t) => {
taxCodeMapping[t.Name] = t.Id;
});
ret = {
...ret,
items: itemMapping,
@@ -368,10 +417,12 @@ async function QueryMetaData(oauthClient, qbo_realmId, req, ro_number, isCreditM
...ret,
paymentMethods: paymentMethodMapping,
invoices:
invoice.json?.QueryResponse?.Invoice &&
invoice.json &&
invoice.json.QueryResponse &&
invoice.json.QueryResponse.Invoice &&
(parentTierRef
? [invoice.json?.QueryResponse?.Invoice.find((x) => x.CustomerRef?.value === parentTierRef?.Id)]
: [invoice.json?.QueryResponse?.Invoice?.[0]])
? [invoice.json.QueryResponse.Invoice.find((x) => x.CustomerRef.value === parentTierRef.Id)]
: [invoice.json.QueryResponse.Invoice[0]])
};
}
@@ -386,7 +437,7 @@ async function InsertCreditMemo(oauthClient, qbo_realmId, req, payment, parentRe
payment.job.shopid
);
if (invoices?.length !== 1) {
if (invoices && invoices.length !== 1) {
throw new Error(`More than 1 invoice with DocNumber ${payment.ro_number} found.`);
}
@@ -394,9 +445,11 @@ async function InsertCreditMemo(oauthClient, qbo_realmId, req, payment, parentRe
CustomerRef: {
value: parentRef.Id
},
TxnDate: moment(payment.date).format("YYYY-MM-DD"),
TxnDate: moment(payment.date)
//.tz(bodyshop.timezone)
.format("YYYY-MM-DD"),
DocNumber: payment.paymentnum,
...(invoices?.[0] ? { InvoiceRef: { value: invoices[0].Id } } : {}),
...(invoices && invoices[0] ? { InvoiceRef: { value: invoices[0].Id } } : {}),
PaymentRefNum: payment.transactionid,
Line: [
{
@@ -441,21 +494,18 @@ async function InsertCreditMemo(oauthClient, qbo_realmId, req, payment, parentRe
method: "POST",
name: "InsertCreditMemo",
paymentid: payment.id,
status: result.status,
status: result.response?.status,
bodyshopid: req.user.bodyshopid,
email: req.user.email
});
if (result.status >= 400) {
throw new Error(JSON.stringify(result.json.Fault));
}
if (result.status === 200) return result?.json;
setNewRefreshToken(req.user.email, result);
return result && result.Bill;
} catch (error) {
logger.log("qbo-payables-error", "DEBUG", req.user.email, payment.id, {
method: "InsertCreditMemo",
validationError: error.message,
error: error,
validationError: JSON.stringify(error?.response?.data),
accountmeta: JSON.stringify({ items, taxCodes }),
stack: error.stack
method: "InsertCreditMemo"
});
throw error;
}

View File

@@ -4,7 +4,7 @@ const StandardizeName = require("./qbo").StandardizeName;
const logger = require("../../utils/logger");
const apiGqlClient = require("../../graphql-client/graphql-client").client;
const queries = require("../../graphql-client/queries");
const { refresh: refreshOauthToken } = require("./qbo-callback");
const { refresh: refreshOauthToken, setNewRefreshToken } = require("./qbo-callback");
const OAuthClient = require("intuit-oauth");
const CreateInvoiceLines = require("../qb-receivables-lines").default;
const moment = require("moment-timezone");
@@ -71,7 +71,7 @@ exports.default = async (req, res) => {
if (isThreeTier || (!isThreeTier && twoTierPref === "name")) {
//Insert the name/owner and account for whether the source should be the ins co in 3 tier..
ownerCustomerTier = await QueryOwner(oauthClient, qbo_realmId, req, job, insCoCustomerTier);
ownerCustomerTier = await QueryOwner(oauthClient, qbo_realmId, req, job, isThreeTier, insCoCustomerTier);
//Query for the owner itself.
if (!ownerCustomerTier) {
ownerCustomerTier = await InsertOwner(oauthClient, qbo_realmId, req, job, isThreeTier, insCoCustomerTier);
@@ -103,12 +103,12 @@ exports.default = async (req, res) => {
if (!req.body.custDataOnly) {
await InsertInvoice(oauthClient, qbo_realmId, req, job, bodyshop, jobTier);
if (job.qb_multiple_payers?.length > 0) {
if (job.qb_multiple_payers && job.qb_multiple_payers.length > 0) {
for (const [index, payer] of job.qb_multiple_payers.entries()) {
//do the thing.
//Create the source level.
let insCoCustomerTier, jobTier;
let insCoCustomerTier, ownerCustomerTier, jobTier;
//Insert the insurance company tier.
//Query for top level customer, the insurance company name.
@@ -150,21 +150,23 @@ exports.default = async (req, res) => {
// //No error. Mark the job exported & insert export log.
if (elgen) {
await client.setHeaders({ Authorization: BearerToken }).request(queries.QBO_MARK_JOB_EXPORTED, {
jobId: job.id,
job: {
status: bodyshop.md_ro_statuses.default_exported || "Exported*",
date_exported: moment().tz(bodyshop.timezone)
},
logs: [
{
bodyshopid: bodyshop.id,
jobid: job.id,
successful: true,
useremail: req.user.email
}
]
});
const result = await client
.setHeaders({ Authorization: BearerToken })
.request(queries.QBO_MARK_JOB_EXPORTED, {
jobId: job.id,
job: {
status: bodyshop.md_ro_statuses.default_exported || "Exported*",
date_exported: moment().tz(bodyshop.timezone)
},
logs: [
{
bodyshopid: bodyshop.id,
jobid: job.id,
successful: true,
useremail: req.user.email
}
]
});
}
}
ret.push({ jobid: job.id, success: true });
@@ -185,13 +187,15 @@ exports.default = async (req, res) => {
});
//Add the export log error.
if (elgen) {
await client.setHeaders({ Authorization: BearerToken }).request(queries.INSERT_EXPORT_LOG, {
const result = await client.setHeaders({ Authorization: BearerToken }).request(queries.INSERT_EXPORT_LOG, {
logs: [
{
bodyshopid: bodyshop.id,
jobid: job.id,
successful: false,
message: JSON.stringify([error?.authResponse?.body || error?.message]),
message: JSON.stringify([
(error && error.authResponse && error.authResponse.body) || (error && error.message)
]),
useremail: req.user.email
}
]
@@ -217,7 +221,10 @@ async function QueryInsuranceCo(oauthClient, qbo_realmId, req, job) {
url: urlBuilder(
qbo_realmId,
"query",
`select * From Customer where DisplayName = '${StandardizeName(job.ins_co_nm.trim())}' and Active = true`
`select *
From Customer
where DisplayName = '${StandardizeName(job.ins_co_nm.trim())}'
and Active = true`
),
method: "POST",
headers: {
@@ -228,13 +235,18 @@ async function QueryInsuranceCo(oauthClient, qbo_realmId, req, job) {
platform: "QBO",
method: "POST",
name: "QueryCustomer",
status: result.status,
status: result.response?.status,
bodyshopid: job.shopid,
jobid: job.id,
email: req.user.email
});
return result.json?.QueryResponse?.Customer?.[0];
setNewRefreshToken(req.user.email, result);
return (
result.json &&
result.json.QueryResponse &&
result.json.QueryResponse.Customer &&
result.json.QueryResponse.Customer[0]
);
} catch (error) {
logger.log("qbo-receivables-error", "DEBUG", req.user.email, job.id, {
error,
@@ -278,13 +290,13 @@ async function InsertInsuranceCo(oauthClient, qbo_realmId, req, job, bodyshop) {
platform: "QBO",
method: "POST",
name: "InsertCustomer",
status: result.status,
status: result.response.status,
bodyshopid: job.shopid,
jobid: job.id,
email: req.user.email
});
return result.json?.Customer;
setNewRefreshToken(req.user.email, result);
return result && result.json.Customer;
} catch (error) {
logger.log("qbo-receivables-error", "DEBUG", req.user.email, job.id, {
error,
@@ -296,13 +308,16 @@ async function InsertInsuranceCo(oauthClient, qbo_realmId, req, job, bodyshop) {
exports.InsertInsuranceCo = InsertInsuranceCo;
async function QueryOwner(oauthClient, qbo_realmId, req, job, parentTierRef) {
async function QueryOwner(oauthClient, qbo_realmId, req, job, isThreeTier, parentTierRef) {
const ownerName = generateOwnerTier(job, true, null);
const result = await oauthClient.makeApiCall({
url: urlBuilder(
qbo_realmId,
"query",
`select * From Customer where DisplayName = '${StandardizeName(ownerName)}' and Active = true`
`select *
From Customer
where DisplayName = '${StandardizeName(ownerName)}'
and Active = true`
),
method: "POST",
headers: {
@@ -313,13 +328,18 @@ async function QueryOwner(oauthClient, qbo_realmId, req, job, parentTierRef) {
platform: "QBO",
method: "POST",
name: "QueryCustomer",
status: result.status,
status: result.response?.status,
bodyshopid: job.shopid,
jobid: job.id,
email: req.user.email
});
return result.json?.QueryResponse?.Customer?.find((x) => x.ParentRef?.value === parentTierRef?.Id);
setNewRefreshToken(req.user.email, result);
return (
result.json &&
result.json.QueryResponse &&
result.json.QueryResponse.Customer &&
result.json.QueryResponse.Customer.find((x) => x.ParentRef?.value === parentTierRef?.Id)
);
}
exports.QueryOwner = QueryOwner;
@@ -359,13 +379,13 @@ async function InsertOwner(oauthClient, qbo_realmId, req, job, isThreeTier, pare
platform: "QBO",
method: "POST",
name: "InsertCustomer",
status: result.status,
status: result.response?.status,
bodyshopid: job.shopid,
jobid: job.id,
email: req.user.email
});
return result.json?.Customer;
setNewRefreshToken(req.user.email, result);
return result && result.json.Customer;
} catch (error) {
logger.log("qbo-receivables-error", "DEBUG", req.user.email, job.id, {
error,
@@ -382,7 +402,10 @@ async function QueryJob(oauthClient, qbo_realmId, req, job, parentTierRef) {
url: urlBuilder(
qbo_realmId,
"query",
`select * From Customer where DisplayName = '${job.ro_number}' and Active = true`
`select *
From Customer
where DisplayName = '${job.ro_number}'
and Active = true`
),
method: "POST",
headers: {
@@ -393,14 +416,20 @@ async function QueryJob(oauthClient, qbo_realmId, req, job, parentTierRef) {
platform: "QBO",
method: "POST",
name: "QueryCustomer",
status: result.status,
status: result.response?.status,
bodyshopid: job.shopid,
jobid: job.id,
email: req.user.email
});
const customers = result.json?.QueryResponse?.Customer;
return customers && (parentTierRef ? customers.find((x) => x.ParentRef.value === parentTierRef.Id) : customers[0]);
setNewRefreshToken(req.user.email, result);
return (
result.json &&
result.json.QueryResponse &&
result.json.QueryResponse.Customer &&
(parentTierRef
? result.json.QueryResponse.Customer.find((x) => x.ParentRef.value === parentTierRef.Id)
: result.json.QueryResponse.Customer[0])
);
}
exports.QueryJob = QueryJob;
@@ -435,21 +464,17 @@ async function InsertJob(oauthClient, qbo_realmId, req, job, parentTierRef) {
platform: "QBO",
method: "POST",
name: "InsertCustomer",
status: result.status,
status: result.response?.status,
bodyshopid: job.shopid,
jobid: job.id,
email: req.user.email
});
if (result.status >= 400) {
throw new Error(JSON.stringify(result.json.Fault));
}
if (result.status === 200) return result?.json.Customer;
setNewRefreshToken(req.user.email, result);
return result && result.json.Customer;
} catch (error) {
logger.log("qbo-receivables-error", "DEBUG", req.user.email, job.id, {
method: "InsertOwner",
validationError: error.message,
stack: error.stack
error,
method: "InsertOwner"
});
throw error;
}
@@ -459,7 +484,13 @@ exports.InsertJob = InsertJob;
async function QueryMetaData(oauthClient, qbo_realmId, req, bodyshopid, jobid) {
const items = await oauthClient.makeApiCall({
url: urlBuilder(qbo_realmId, "query", `select * From Item where active = true maxresults 1000`),
url: urlBuilder(
qbo_realmId,
"query",
`select *
From Item
where active = true maxresults 1000`
),
method: "POST",
headers: {
"Content-Type": "application/json"
@@ -469,14 +500,20 @@ async function QueryMetaData(oauthClient, qbo_realmId, req, bodyshopid, jobid) {
platform: "QBO",
method: "POST",
name: "QueryItems",
status: items.status,
status: items.response?.status,
bodyshopid,
jobid: jobid,
email: req.user.email
});
setNewRefreshToken(req.user.email, items);
const taxCodes = await oauthClient.makeApiCall({
url: urlBuilder(qbo_realmId, "query", `select * From TaxCode where active = true`),
url: urlBuilder(
qbo_realmId,
"query",
`select *
From TaxCode
where active = true`
),
method: "POST",
headers: {
"Content-Type": "application/json"
@@ -486,13 +523,18 @@ async function QueryMetaData(oauthClient, qbo_realmId, req, bodyshopid, jobid) {
platform: "QBO",
method: "POST",
name: "QueryTaxCodes",
status: taxCodes.status,
status: taxCodes.response?.status,
bodyshopid,
jobid: jobid,
email: req.user.email
});
const classes = await oauthClient.makeApiCall({
url: urlBuilder(qbo_realmId, "query", `select * From Class`),
url: urlBuilder(
qbo_realmId,
"query",
`select *
From Class`
),
method: "POST",
headers: {
"Content-Type": "application/json"
@@ -502,17 +544,36 @@ async function QueryMetaData(oauthClient, qbo_realmId, req, bodyshopid, jobid) {
platform: "QBO",
method: "POST",
name: "QueryClasses",
status: classes.status,
status: classes.response?.status,
bodyshopid,
jobid: jobid,
email: req.user.email
});
const taxCodeMapping = {};
const taxCodeMapping = Object.fromEntries((taxCodes.json?.QueryResponse?.TaxCode || []).map((t) => [t.Name, t.Id]));
taxCodes.json &&
taxCodes.json.QueryResponse &&
taxCodes.json.QueryResponse.TaxCode &&
taxCodes.json.QueryResponse.TaxCode.forEach((t) => {
taxCodeMapping[t.Name] = t.Id;
});
const itemMapping = Object.fromEntries((items.json?.QueryResponse?.Item || []).map((item) => [item.Name, item.Id]));
const itemMapping = {};
const classMapping = Object.fromEntries((classes.json?.QueryResponse?.Class || []).map((c) => [c.Name, c.Id]));
items.json &&
items.json.QueryResponse &&
items.json.QueryResponse.Item &&
items.json.QueryResponse.Item.forEach((t) => {
itemMapping[t.Name] = t.Id;
});
const classMapping = {};
classes.json &&
classes.json.QueryResponse &&
classes.json.QueryResponse.Class &&
classes.json.QueryResponse.Class.forEach((t) => {
classMapping[t.Name] = t.Id;
});
return {
items: itemMapping,
@@ -545,11 +606,12 @@ async function InsertInvoice(oauthClient, qbo_realmId, req, job, bodyshop, paren
} ${job.v_vin || ""} ${job.plate_no || ""} `.trim()
},
CustomerRef: {
value: parentTierRef?.Id
value: parentTierRef.Id
},
...(bodyshop.accountingconfig.qbo_departmentid?.trim() !== "" && {
DepartmentRef: { value: bodyshop.accountingconfig.qbo_departmentid }
}),
...(bodyshop.accountingconfig.qbo_departmentid &&
bodyshop.accountingconfig.qbo_departmentid.trim() !== "" && {
DepartmentRef: { value: bodyshop.accountingconfig.qbo_departmentid }
}),
CustomField: [
...(bodyshop.accountingconfig.ReceivableCustomField1
? [
@@ -579,8 +641,9 @@ async function InsertInvoice(oauthClient, qbo_realmId, req, job, bodyshop, paren
]
: [])
],
...(bodyshop.accountingconfig?.qbo &&
bodyshop.accountingconfig?.qbo_usa && {
...(bodyshop.accountingconfig &&
bodyshop.accountingconfig.qbo &&
bodyshop.accountingconfig.qbo_usa && {
TxnTaxDetail: {
TxnTaxCodeRef: {
value: taxCodes[bodyshop.md_responsibility_centers.taxes.state.accountitem]
@@ -616,22 +679,19 @@ async function InsertInvoice(oauthClient, qbo_realmId, req, job, bodyshop, paren
platform: "QBO",
method: "POST",
name: "InsertInvoice",
status: result.status,
status: result.response?.status,
bodyshopid: job.shopid,
jobid: job.id,
email: req.user.email
});
if (result.status >= 400) {
throw new Error(JSON.stringify(result.json.Fault));
}
if (result.status === 200) return result?.json;
setNewRefreshToken(req.user.email, result);
return result && result.json && result.json.Invoice;
} catch (error) {
logger.log("qbo-receivables-error", "DEBUG", req.user.email, job.id, {
error,
method: "InsertInvoice",
validationError: error.message,
accountmeta: JSON.stringify({ items, taxCodes, classes }),
stack: error.stack
validationError: JSON.stringify(error?.response?.data),
accountmeta: JSON.stringify({ items, taxCodes, classes })
});
throw error;
}
@@ -674,9 +734,10 @@ async function InsertInvoiceMultiPayerInvoice(
CustomerRef: {
value: parentTierRef.Id
},
...(bodyshop.accountingconfig.qbo_departmentid?.trim() !== "" && {
DepartmentRef: { value: bodyshop.accountingconfig.qbo_departmentid }
}),
...(bodyshop.accountingconfig.qbo_departmentid &&
bodyshop.accountingconfig.qbo_departmentid.trim() !== "" && {
DepartmentRef: { value: bodyshop.accountingconfig.qbo_departmentid }
}),
CustomField: [
...(bodyshop.accountingconfig.ReceivableCustomField1
? [
@@ -706,8 +767,9 @@ async function InsertInvoiceMultiPayerInvoice(
]
: [])
],
...(bodyshop.accountingconfig?.qbo &&
bodyshop.accountingconfig?.qbo_usa &&
...(bodyshop.accountingconfig &&
bodyshop.accountingconfig.qbo &&
bodyshop.accountingconfig.qbo_usa &&
bodyshop.region_config.includes("CA_") && {
TxnTaxDetail: {
TxnTaxCodeRef: {
@@ -743,23 +805,18 @@ async function InsertInvoiceMultiPayerInvoice(
logger.LogIntegrationCall({
platform: "QBO",
method: "POST",
name: "InsertInvoiceMultiPayerInvoice",
status: result.status,
name: "InsertInvoice",
status: result.response?.status,
bodyshopid: job.shopid,
jobid: job.id,
email: req.user.email
});
if (result.status >= 400) {
throw new Error(JSON.stringify(result.json.Fault));
}
if (result.status === 200) return result?.json;
setNewRefreshToken(req.user.email, result);
return result && result.json && result.json.Invoice;
} catch (error) {
logger.log("qbo-receivables-error", "DEBUG", req.user.email, job.id, {
method: "InsertInvoiceMultiPayerInvoice",
validationError: error.message,
accountmeta: JSON.stringify({ items, taxCodes, classes }),
stack: error.stack
error,
method: "InsertOwner"
});
throw error;
}

View File

@@ -304,6 +304,7 @@ function GenerateCostingData(job) {
if (
job.cieca_pfl &&
job.cieca_pfl[val.mod_lbr_ty.toUpperCase()] &&
typeof job.cieca_pfl[val.mod_lbr_ty.toUpperCase()].lbr_adjp === "number" &&
job.cieca_pfl[val.mod_lbr_ty.toUpperCase()].lbr_adjp !== 0
) {
let adjp = 0;
@@ -338,7 +339,7 @@ function GenerateCostingData(job) {
if (!acc.labor[laborProfitCenter]) acc.labor[laborProfitCenter] = Dinero();
acc.labor[laborProfitCenter] = acc.labor[laborProfitCenter].add(laborAmount);
if (val.mod_lb_hrs === 0 && val.act_price > 0 && val.lbr_op === "OP14") {
if (val.act_price > 0 && val.lbr_op === "OP14") {
//Scenario where SGI may pay out hours using a part price.
acc.labor[laborProfitCenter] = acc.labor[laborProfitCenter].add(
Dinero({
@@ -469,10 +470,7 @@ function GenerateCostingData(job) {
}
//Additional Profit Center
if (
(!val.part_type && !val.mod_lbr_ty) ||
(!val.part_type && val.mod_lbr_ty && val.act_price > 0 && val.lbr_op !== "OP14")
) {
if ((!val.part_type && !val.mod_lbr_ty) || (!val.part_type && val.mod_lbr_ty && val.lbr_op !== "OP14")) {
//Does it already have a defined profit center?
//If so, use it, otherwise try to use the same from the auto-allocate logic in IO app jobs-close-auto-allocate.
const partsProfitCenter = val.profitcenter_part || getAdditionalCostCenter(val, defaultProfits) || "Unknown";
@@ -524,7 +522,12 @@ function GenerateCostingData(job) {
}).multiply(materialsHours.mapaHrs || 0)
);
let adjp = 0;
if (job.materials["MAPA"] && job.materials["MAPA"].mat_adjp) {
if (
job.materials["MAPA"] &&
job.materials["MAPA"].mat_adjp &&
typeof job.materials["MAPA"].mat_adjp === "number" &&
job.materials["MAPA"].mat_adjp !== 0
) {
adjp =
Math.abs(job.materials["MAPA"].mat_adjp) > 1
? job.materials["MAPA"].mat_adjp
@@ -551,7 +554,12 @@ function GenerateCostingData(job) {
}).multiply(materialsHours.mashHrs || 0)
);
let adjp = 0;
if (job.materials["MASH"] && job.materials["MASH"].mat_adjp) {
if (
job.materials["MASH"] &&
job.materials["MASH"].mat_adjp &&
typeof job.materials["MASH"].mat_adjp === "number" &&
job.materials["MASH"].mat_adjp !== 0
) {
adjp =
Math.abs(job.materials["MASH"].mat_adjp) > 1
? job.materials["MASH"].mat_adjp
@@ -575,7 +583,7 @@ function GenerateCostingData(job) {
jobLineTotalsByProfitCenter.additional[defaultProfits["TOW"]] = Dinero();
jobLineTotalsByProfitCenter.additional[defaultProfits["TOW"]] = stlTowing
? Dinero({ amount: Math.round(stlTowing.ttl_amt * 100) })
? Dinero({ amount: Math.round((stlTowing.ttl_amt || 0) * 100) })
: Dinero({
amount: Math.round((job.towing_payable || 0) * 100)
});
@@ -584,7 +592,7 @@ function GenerateCostingData(job) {
jobLineTotalsByProfitCenter.additional[defaultProfits["STO"]] = Dinero();
jobLineTotalsByProfitCenter.additional[defaultProfits["STO"]] = stlStorage
? Dinero({ amount: Math.round(stlStorage.ttl_amt * 100) })
? Dinero({ amount: Math.round((stlStorage.ttl_amt || 0) * 100) })
: Dinero({
amount: Math.round((job.storage_payable || 0) * 100)
});