Merge branch 'feature/qbo' into release/2021-09-03

This commit is contained in:
Patrick Fic
2021-08-30 12:57:38 -07:00
19 changed files with 10845 additions and 77 deletions

View File

@@ -6,26 +6,27 @@ require("dotenv").config({
),
});
const OAuthClient = require("intuit-oauth");
var Tokens = require("csrf");
var tokens = new Tokens();
const logger = require("../../utils/logger");
const oauthClient = new OAuthClient({
clientId: process.env.QB_ONLINE_CLIENT_ID,
clientSecret: process.env.QB_ONLINE_SECRET,
environment: "sandbox", //process.env.NODE_ENV === "production" ? "production" : "sandbox",
redirectUri: process.env.QB_ONLINE_REDIRECT_URI,
clientId: process.env.QBO_CLIENT_ID,
clientSecret: process.env.QBO_SECRET,
environment: process.env.NODE_ENV === "production" ? "production" : "sandbox",
redirectUri: process.env.QBO_REDIRECT_URI,
});
exports.default = async (req, res) => {
console.log("QBO Authorize Called");
const { userId } = req.body;
console.log("exports.default -> userId", userId);
// AuthorizationUri
try {
logger.log("qbo-auth-uri", "DEBUG", req.user.email, null, null);
const authUri = oauthClient.authorizeUri({
scope: [OAuthClient.scopes.Accounting, OAuthClient.scopes.OpenId],
state: req.user.email,
}); // can be an array of multiple scopes ex : {scope:[OAuthClient.scopes.Accounting,OAuthClient.scopes.OpenId]}
const authUri = oauthClient.authorizeUri({
scope: [OAuthClient.scopes.Accounting, OAuthClient.scopes.OpenId],
state: tokens.create(userId),
}); // can be an array of multiple scopes ex : {scope:[OAuthClient.scopes.Accounting,OAuthClient.scopes.OpenId]}
console.log("authUri", authUri);
// Redirect the authUri
res.send(authUri);
res.send(authUri);
} catch (error) {
logger.log("qbo-auth-uri-error", "ERROR", req.user.email, null, { error });
res.status(500).json(error);
}
};

View File

@@ -5,32 +5,79 @@ require("dotenv").config({
`.env.${process.env.NODE_ENV || "development"}`
),
});
const logger = require("../../utils/logger");
const OAuthClient = require("intuit-oauth");
var Tokens = require("csrf");
var QuickBooks = require("node-quickbooks");
const Promise = require("bluebird");
const QuickBooksPromise = Promise.promisifyAll(QuickBooks.prototype);
const client = require("../../graphql-client/graphql-client").client;
const queries = require("../../graphql-client/queries");
const queryString = require("query-string");
const oauthClient = new OAuthClient({
clientId: process.env.QB_ONLINE_CLIENT_ID,
clientSecret: process.env.QB_ONLINE_SECRET,
environment: "sandbox", //process.env.NODE_ENV === "production" ? "production" : "sandbox",
redirectUri: process.env.QB_ONLINE_REDIRECT_URI,
clientId: process.env.QBO_CLIENT_ID,
clientSecret: process.env.QBO_SECRET,
environment: process.env.NODE_ENV === "production" ? "production" : "sandbox",
redirectUri: process.env.QBO_REDIRECT_URI,
logging: true,
});
exports.default = async (req, res) => {
// Parse the redirect URL for authCode and exchange them for tokens
const parseRedirect = req.url;
const { code, state, realmId } = req.query;
console.log("exports.default -> state", state);
// Exchange the auth code retrieved from the **req.url** on the redirectUri
oauthClient
.createToken(parseRedirect)
.then(function (authResponse) {
console.log("The Token is " + JSON.stringify(authResponse.getJson()));
const { access_token, refresh_token } = authResponse.getJson();
console.log("exports.default -> refresh_token", refresh_token);
console.log("exports.default -> access_token", access_token);
})
.catch(function (e) {
console.error("The error message is :" + e.originalMessage);
console.error(e.intuit_tid);
const params = queryString.parse(req.url.split("?").reverse()[0]);
try {
logger.log("qbo-callback-create-token", "DEBUG", params.state, null, null);
const authResponse = await oauthClient.createToken(req.url);
if (authResponse.json.error) {
logger.log("qbo-callback-error", "ERROR", params.state, null, {
error: authResponse.json,
});
res.redirect(
`http://localhost:3000/manage/accounting/qbo?error=${encodeURIComponent(
JSON.stringify(authResponse.json)
)}`
);
} else {
await client.request(queries.SET_QBO_AUTH, {
email: params.state,
qbo_auth: { ...authResponse.json, createdAt: Date.now() },
});
logger.log(
"qbo-callback-create-token-success",
"DEBUG",
params.state,
null,
null
);
res.redirect(`http://localhost:3000/manage/accounting/qbo?`);
}
} catch (e) {
logger.log("qbo-callback-error", "ERROR", params.state, null, {
error: e,
});
res.status(400).json(e);
}
};
exports.refresh = async (oauthClient, req) => {
try {
logger.log("qbo-token-refresh", "DEBUG", req.user.email, null, null);
const authResponse = await oauthClient.refresh();
await client.request(queries.SET_QBO_AUTH, {
email: req.user.email,
qbo_auth: { ...authResponse.json, createdAt: Date.now() },
});
} catch (error) {
logger.log("qbo-token-refresh-error", "ERROR", req.user.email, null, {
error,
});
}
};
exports.setNewRefreshToken = async (email, apiResponse) => {
logger.log("qbo-token-updated", "DEBUG", email, null, null);
await client.request(queries.SET_QBO_AUTH, {
email,
qbo_auth: { ...apiResponse.token, createdAt: Date.now() },
});
};

View File

@@ -0,0 +1,312 @@
const urlBuilder = require("./qbo").urlBuilder;
const path = require("path");
require("dotenv").config({
path: path.resolve(
process.cwd(),
`.env.${process.env.NODE_ENV || "development"}`
),
});
const logger = require("../../utils/logger");
const apiGqlClient = require("../../graphql-client/graphql-client").client;
const queries = require("../../graphql-client/queries");
const {
refresh: refreshOauthToken,
setNewRefreshToken,
} = require("./qbo-callback");
const OAuthClient = require("intuit-oauth");
var QuickBooks = require("node-quickbooks");
const GraphQLClient = require("graphql-request").GraphQLClient;
const { generateOwnerTier } = require("../qbxml/qbxml-utils");
const oauthClient = new OAuthClient({
clientId: process.env.QBO_CLIENT_ID,
clientSecret: process.env.QBO_SECRET,
environment: process.env.NODE_ENV === "production" ? "production" : "sandbox",
redirectUri: process.env.QBO_REDIRECT_URI,
logging: true,
});
exports.default = async (req, res) => {
try {
//Fetch the API Access Tokens & Set them for the session.
const response = await apiGqlClient.request(queries.GET_QBO_AUTH, {
email: req.user.email,
});
response.associations[0].qbo_auth;
oauthClient.setToken(response.associations[0].qbo_auth);
if (!oauthClient.token.isAccessTokenValid()) {
await refreshOauthToken(oauthClient, req);
if (!oauthClient.token.isAccessTokenValid()) {
res.sendStatus(401);
}
}
const BearerToken = req.headers.authorization;
const { jobIds } = req.body;
//Query Job Info
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {
headers: {
Authorization: BearerToken,
},
});
const result = await client
.setHeaders({ Authorization: BearerToken })
.request(queries.QUERY_JOBS_FOR_RECEIVABLES_EXPORT, {
ids: ["966dc7f9-2acd-44dc-9df5-d07c5578070a"],
//jobIds
});
const { jobs, bodyshops } = result;
const job = jobs[0];
const bodyshop = bodyshops[0];
const isThreeTier = bodyshop.accountingconfig.tiers === 3;
const twoTierPref = bodyshop.accountingconfig.twotierpref;
//Replace this with a for-each loop to check every single Job that's included in the list.
let insCoCustomerTier, ownerCustomerTier;
if (isThreeTier || twoTierPref === "source") {
//Insert the insurance company tier.
//Query for top level customer, the insurance company name.
insCoCustomerTier = await QueryInsuranceCo(oauthClient, req, job);
if (!insCoCustomerTier) {
//Creating the Insurance Customer.
insCoCustomerTier = await InsertInsuranceCo(
oauthClient,
req,
job,
bodyshop
);
}
}
if (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, req, job);
//Query for the owner itself.
if (!ownerCustomerTier) {
ownerCustomerTier = await InsertOwner(
oauthClient,
req,
job,
isThreeTier,
insCoCustomerTier
);
}
}
//Query for the Job or Create it.
const jobrecord = await InsertJob(
oauthClient,
req,
job,
isThreeTier,
ownerCustomerTier
);
//Is there a job associated to the owner? If so, get the ID and move on.
//Otherwise create it.
res.sendStatus(200);
} catch (error) {
console.log(error);
res.status(400).json(error);
}
};
async function QueryInsuranceCo(oauthClient, req, job) {
const result = await oauthClient.makeApiCall({
url: urlBuilder(
req.cookies.qbo_realmId,
"query",
`select * From Customer where DisplayName = '${job.ins_co_nm}'`
),
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
setNewRefreshToken(req.user.email, result);
return (
result.json &&
result.json.QueryResponse &&
result.json.QueryResponse.Customer &&
result.json.QueryResponse.Customer[0]
);
}
async function InsertInsuranceCo(oauthClient, req, job, bodyshop) {
const insCo = bodyshop.md_ins_cos.find((i) => i.name === job.ins_co_nm);
const Customer = {
DisplayName: job.ins_co_nm,
BillAddr: {
City: job.ownr_city,
Line1: insCo.street1,
Line2: insCo.street2,
PostalCode: insCo.zip,
CountrySubDivisionCode: insCo.state,
},
};
try {
const result = await oauthClient.makeApiCall({
url: urlBuilder(req.cookies.qbo_realmId, "customer"),
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(Customer),
});
setNewRefreshToken(req.user.email, result);
return result && result.Customer;
} catch (error) {
logger.log("qbo-receivables-error", "DEBUG", req.user.email, job.id, {
error,
method: "InsertInsuranceCo",
});
throw error;
}
}
async function QueryOwner(oauthClient, req, job) {
const ownerName = generateOwnerTier(job, true, null);
const result = await oauthClient.makeApiCall({
url: urlBuilder(
req.cookies.qbo_realmId,
"query",
`select * From Customer where DisplayName = '${ownerName}'`
),
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
setNewRefreshToken(req.user.email, result);
return (
result.json &&
result.json.QueryResponse &&
result.json.QueryResponse.Customer &&
result.json.QueryResponse.Customer[0]
);
}
async function InsertOwner(oauthClient, req, job, isThreeTier, parentTierRef) {
const ownerName = generateOwnerTier(job, true, null);
const Customer = {
DisplayName: ownerName,
BillAddr: {
City: job.ownr_city,
Line1: job.ownr_addr1,
Line2: job.ownr_addr2,
PostalCode: job.ownr_zip,
CountrySubDivisionCode: job.ownr_st,
},
...(isThreeTier
? {
Job: true,
ParentRef: {
value: parentTierRef.Id,
},
}
: {}),
};
try {
const result = await oauthClient.makeApiCall({
url: urlBuilder(req.cookies.qbo_realmId, "customer"),
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(Customer),
});
setNewRefreshToken(req.user.email, result);
return result && result.Customer;
} catch (error) {
logger.log("qbo-receivables-error", "DEBUG", req.user.email, job.id, {
error,
method: "InsertOwner",
});
throw error;
}
}
async function InsertJob(oauthClient, req, job, isThreeTier, parentTierRef) {
const Customer = {
DisplayName: job.ro_number,
BillAddr: {
City: job.ownr_city,
Line1: job.ownr_addr1,
Line2: job.ownr_addr2,
PostalCode: job.ownr_zip,
CountrySubDivisionCode: job.ownr_st,
},
...(isThreeTier
? {
Job: true,
ParentRef: {
value: parentTierRef.Id,
},
}
: {}),
};
try {
const result = await oauthClient.makeApiCall({
url: urlBuilder(req.cookies.qbo_realmId, "customer"),
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(Customer),
});
setNewRefreshToken(req.user.email, result);
return result && result.Customer;
} catch (error) {
logger.log("qbo-receivables-error", "DEBUG", req.user.email, job.id, {
error,
method: "InsertOwner",
});
throw error;
}
}
// const customerCreate = {
// FullyQualifiedName: "A Test Customer",
// DisplayName: "A test Customer",
// };
// const ret = await oauthClient.makeApiCall({
// url: urlBuilder(req.cookies.qbo_realmId, "customer"),
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// },
// body: JSON.stringify(customerCreate),
// });
// const invoice = {
// Line: [
// {
// DetailType: "SalesItemLineDetail",
// Amount: 100,
// SalesItemLineDetail: {
// ItemRef: {
// name: "Services",
// value: "1",
// },
// TaxCodeRef: {
// value: "2",
// },
// Qty: 1,
// UnitPrice: 100,
// },
// },
// ],
// CustomerRef: {
// name: "A test Customer",
// },
// };
// const ret2 = await oauthClient.makeApiCall({
// url: urlBuilder(req.cookies.qbo_realmId, "invoice"),
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// },
// body: JSON.stringify(invoice),
// });

View File

@@ -1,7 +1,3 @@
exports.callback = require("./qbo-callback").default;
exports.authorize = require("./qbo-authorize").default;
const OAuthClient = require("intuit-oauth");
const path = require("path");
require("dotenv").config({
path: path.resolve(
@@ -9,3 +5,19 @@ require("dotenv").config({
`.env.${process.env.NODE_ENV || "development"}`
),
});
function urlBuilder(realmId, object, query = null) {
return `https://${
process.env.NODE_ENV === "development" || !process.env.NODE_ENV
? "sandbox-"
: ""
}quickbooks.api.intuit.com/v3/company/${realmId}/${object}${
query ? `?query=${encodeURIComponent(query)}` : ""
}`;
}
exports.urlBuilder = urlBuilder;
exports.callback = require("./qbo-callback").default;
exports.authorize = require("./qbo-authorize").default;
exports.refresh = require("./qbo-callback").refresh;
exports.receivables = require("./qbo-receivables").default;

View File

@@ -114,6 +114,7 @@ query QUERY_JOBS_FOR_RECEIVABLES_EXPORT($ids: [uuid!]!) {
id
md_responsibility_centers
accountingconfig
md_ins_cos
}
}
`;
@@ -1049,3 +1050,17 @@ exports.GET_CDK_ALLOCATIONS = `
}
}
`;
exports.GET_QBO_AUTH = `query GET_QBO_AUTH($email: String!) {
associations(where: {_and: {active: {_eq: true}, useremail: {_eq: $email}}}){
id
qbo_auth
}
}`;
exports.SET_QBO_AUTH = `mutation SET_QBO_AUTH($email: String!, $qbo_auth: jsonb!) {
update_associations(_set: {qbo_auth: $qbo_auth}, where: {_and: {active: {_eq: true}, useremail: {_eq: $email}}}){
affected_rows
}
}
`;