Merged in release/2021-10-01 (pull request #229)
release/2021-10-01 Approved-by: Patrick Fic
This commit is contained in:
@@ -9,8 +9,25 @@ import PayableExportAll from "../payable-export-all-button/payable-export-all-bu
|
|||||||
import { DateFormatter } from "../../utils/DateFormatter";
|
import { DateFormatter } from "../../utils/DateFormatter";
|
||||||
import queryString from "query-string";
|
import queryString from "query-string";
|
||||||
import { logImEXEvent } from "../../firebase/firebase.utils";
|
import { logImEXEvent } from "../../firebase/firebase.utils";
|
||||||
|
import QboAuthorizeComponent from "../qbo-authorize/qbo-authorize.component";
|
||||||
|
import { connect } from "react-redux";
|
||||||
|
import { createStructuredSelector } from "reselect";
|
||||||
|
import { selectBodyshop } from "../../redux/user/user.selectors";
|
||||||
|
|
||||||
export default function AccountingPayablesTableComponent({ loading, bills }) {
|
const mapStateToProps = createStructuredSelector({
|
||||||
|
bodyshop: selectBodyshop,
|
||||||
|
});
|
||||||
|
|
||||||
|
const mapDispatchToProps = (dispatch) => ({
|
||||||
|
//setUserLanguage: language => dispatch(setUserLanguage(language))
|
||||||
|
});
|
||||||
|
|
||||||
|
export default connect(
|
||||||
|
mapStateToProps,
|
||||||
|
mapDispatchToProps
|
||||||
|
)(AccountingPayablesTableComponent);
|
||||||
|
|
||||||
|
export function AccountingPayablesTableComponent({ bodyshop, loading, bills }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [selectedBills, setSelectedBills] = useState([]);
|
const [selectedBills, setSelectedBills] = useState([]);
|
||||||
const [transInProgress, setTransInProgress] = useState(false);
|
const [transInProgress, setTransInProgress] = useState(false);
|
||||||
@@ -166,6 +183,9 @@ export default function AccountingPayablesTableComponent({ loading, bills }) {
|
|||||||
loadingCallback={setTransInProgress}
|
loadingCallback={setTransInProgress}
|
||||||
completedCallback={setSelectedBills}
|
completedCallback={setSelectedBills}
|
||||||
/>
|
/>
|
||||||
|
{bodyshop.accountingconfig && bodyshop.accountingconfig.qbo && (
|
||||||
|
<QboAuthorizeComponent />
|
||||||
|
)}
|
||||||
<Input
|
<Input
|
||||||
value={state.search}
|
value={state.search}
|
||||||
onChange={handleSearch}
|
onChange={handleSearch}
|
||||||
|
|||||||
@@ -99,7 +99,7 @@ export function JobsAvailableContainer({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
//IO-539 Check for Parts Rate on PAL for SGI use case.
|
//IO-539 Check for Parts Rate on PAL for SGI use case.
|
||||||
await CheckTaxRates(estData, bodyshop);
|
await CheckTaxRates(estData.est_data, bodyshop);
|
||||||
|
|
||||||
const newTotals = (
|
const newTotals = (
|
||||||
await Axios.post("/job/totals", {
|
await Axios.post("/job/totals", {
|
||||||
|
|||||||
@@ -35,52 +35,61 @@ export function PayableExportAll({
|
|||||||
|
|
||||||
const handleQbxml = async () => {
|
const handleQbxml = async () => {
|
||||||
logImEXEvent("accounting_payables_export_all");
|
logImEXEvent("accounting_payables_export_all");
|
||||||
|
let PartnerResponse;
|
||||||
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
if (!!loadingCallback) loadingCallback(true);
|
if (!!loadingCallback) loadingCallback(true);
|
||||||
|
if (bodyshop.accountingconfig && bodyshop.accountingconfig.qbo) {
|
||||||
let QbXmlResponse;
|
PartnerResponse = await axios.post(`/qbo/receivables`, {
|
||||||
try {
|
withCredentials: true,
|
||||||
QbXmlResponse = await axios.post(
|
bills: billids,
|
||||||
"/accounting/qbxml/payables",
|
|
||||||
{ bills: billids },
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${await auth.currentUser.getIdToken()}`,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
console.log("Error getting QBXML from Server.", error);
|
|
||||||
notification["error"]({
|
|
||||||
message: t("bills.errors.exporting", {
|
|
||||||
error: "Unable to retrieve QBXML. " + JSON.stringify(error.message),
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
if (loadingCallback) loadingCallback(false);
|
} else {
|
||||||
setLoading(false);
|
let QbXmlResponse;
|
||||||
return;
|
try {
|
||||||
}
|
QbXmlResponse = await axios.post(
|
||||||
|
"/accounting/qbxml/payables",
|
||||||
|
{ bills: billids },
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${await auth.currentUser.getIdToken()}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.log("Error getting QBXML from Server.", error);
|
||||||
|
notification["error"]({
|
||||||
|
message: t("bills.errors.exporting", {
|
||||||
|
error: "Unable to retrieve QBXML. " + JSON.stringify(error.message),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
if (loadingCallback) loadingCallback(false);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
let PartnerResponse;
|
try {
|
||||||
|
PartnerResponse = await axios.post(
|
||||||
try {
|
"http://localhost:1337/qb/",
|
||||||
PartnerResponse = await axios.post(
|
QbXmlResponse.data
|
||||||
"http://localhost:1337/qb/",
|
);
|
||||||
QbXmlResponse.data
|
} catch (error) {
|
||||||
);
|
console.log("Error connecting to quickbooks or partner.", error);
|
||||||
} catch (error) {
|
notification["error"]({
|
||||||
console.log("Error connecting to quickbooks or partner.", error);
|
message: t("bills.errors.exporting-partner"),
|
||||||
notification["error"]({
|
});
|
||||||
message: t("bills.errors.exporting-partner"),
|
if (!!loadingCallback) loadingCallback(false);
|
||||||
});
|
setLoading(false);
|
||||||
if (!!loadingCallback) loadingCallback(false);
|
return;
|
||||||
setLoading(false);
|
}
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("handleQbxml -> PartnerResponse", PartnerResponse);
|
console.log("handleQbxml -> PartnerResponse", PartnerResponse);
|
||||||
const groupedData = _.groupBy(PartnerResponse.data, "id");
|
const groupedData = _.groupBy(
|
||||||
|
PartnerResponse.data,
|
||||||
|
bodyshop.accountingconfig.qbo ? "billid" : "id"
|
||||||
|
);
|
||||||
|
|
||||||
const proms = [];
|
const proms = [];
|
||||||
Object.keys(groupedData).forEach((key) => {
|
Object.keys(groupedData).forEach((key) => {
|
||||||
proms.push(
|
proms.push(
|
||||||
|
|||||||
@@ -38,44 +38,53 @@ export function PayableExportButton({
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
if (!!loadingCallback) loadingCallback(true);
|
if (!!loadingCallback) loadingCallback(true);
|
||||||
|
|
||||||
let QbXmlResponse;
|
//Check if it's a QBO Setup.
|
||||||
try {
|
|
||||||
QbXmlResponse = await axios.post(
|
|
||||||
"/accounting/qbxml/payables",
|
|
||||||
{ bills: [billId] },
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${await auth.currentUser.getIdToken()}`,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
console.log("Error getting QBXML from Server.", error);
|
|
||||||
notification["error"]({
|
|
||||||
message: t("bills.errors.exporting", {
|
|
||||||
error: "Unable to retrieve QBXML. " + JSON.stringify(error.message),
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
if (loadingCallback) loadingCallback(false);
|
|
||||||
setLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let PartnerResponse;
|
let PartnerResponse;
|
||||||
|
if (bodyshop.accountingconfig && bodyshop.accountingconfig.qbo) {
|
||||||
try {
|
PartnerResponse = await axios.post(`/qbo/payables`, {
|
||||||
PartnerResponse = await axios.post(
|
withCredentials: true,
|
||||||
"http://localhost:1337/qb/",
|
bills: [billId],
|
||||||
QbXmlResponse.data
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
console.log("Error connecting to quickbooks or partner.", error);
|
|
||||||
notification["error"]({
|
|
||||||
message: t("bills.errors.exporting-partner"),
|
|
||||||
});
|
});
|
||||||
if (!!loadingCallback) loadingCallback(false);
|
} else {
|
||||||
setLoading(false);
|
//Default is QBD
|
||||||
return;
|
|
||||||
|
let QbXmlResponse;
|
||||||
|
try {
|
||||||
|
QbXmlResponse = await axios.post(
|
||||||
|
"/accounting/qbxml/payables",
|
||||||
|
{ bills: [billId] },
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${await auth.currentUser.getIdToken()}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.log("Error getting QBXML from Server.", error);
|
||||||
|
notification["error"]({
|
||||||
|
message: t("bills.errors.exporting", {
|
||||||
|
error: "Unable to retrieve QBXML. " + JSON.stringify(error.message),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
if (loadingCallback) loadingCallback(false);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
PartnerResponse = await axios.post(
|
||||||
|
"http://localhost:1337/qb/",
|
||||||
|
QbXmlResponse.data
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.log("Error connecting to quickbooks or partner.", error);
|
||||||
|
notification["error"]({
|
||||||
|
message: t("bills.errors.exporting-partner"),
|
||||||
|
});
|
||||||
|
if (!!loadingCallback) loadingCallback(false);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("handleQbxml -> PartnerResponse", PartnerResponse);
|
console.log("handleQbxml -> PartnerResponse", PartnerResponse);
|
||||||
@@ -123,7 +132,14 @@ export function PayableExportButton({
|
|||||||
});
|
});
|
||||||
const billUpdateResponse = await updateBill({
|
const billUpdateResponse = await updateBill({
|
||||||
variables: {
|
variables: {
|
||||||
billIdList: successfulTransactions.map((st) => st.id),
|
billIdList: successfulTransactions.map(
|
||||||
|
(st) =>
|
||||||
|
st[
|
||||||
|
bodyshop.accountingconfig && bodyshop.accountingconfig.qbo
|
||||||
|
? "billid"
|
||||||
|
: "id"
|
||||||
|
]
|
||||||
|
),
|
||||||
bill: {
|
bill: {
|
||||||
exported: true,
|
exported: true,
|
||||||
exported_at: new Date(),
|
exported_at: new Date(),
|
||||||
|
|||||||
@@ -85,7 +85,6 @@ function JobsCreateContainer({ bodyshop, setBreadcrumbs, setSelectedHeader }) {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log("Manual State", state);
|
|
||||||
const handleFinish = (values) => {
|
const handleFinish = (values) => {
|
||||||
let job = Object.assign(
|
let job = Object.assign(
|
||||||
{},
|
{},
|
||||||
@@ -142,6 +141,10 @@ function JobsCreateContainer({ bodyshop, setBreadcrumbs, setSelectedHeader }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
job = { ...job, ...ownerData };
|
job = { ...job, ...ownerData };
|
||||||
|
|
||||||
|
if (job.owner === null) delete job.owner;
|
||||||
|
if (job.vehicle === null) delete job.vehicle;
|
||||||
|
|
||||||
runInsertJob(job);
|
runInsertJob(job);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ const DineroQbFormat = require("./accounting-constants").DineroQbFormat;
|
|||||||
const Dinero = require("dinero.js");
|
const Dinero = require("dinero.js");
|
||||||
const logger = require("../utils/logger");
|
const logger = require("../utils/logger");
|
||||||
|
|
||||||
module.exports = function ({
|
exports.default = function ({
|
||||||
bodyshop,
|
bodyshop,
|
||||||
jobs_by_pk,
|
jobs_by_pk,
|
||||||
qbo = false,
|
qbo = false,
|
||||||
@@ -591,3 +591,4 @@ const findTaxCode = ({ local, state, federal }, taxcode) => {
|
|||||||
return "No Tax Code Matches";
|
return "No Tax Code Matches";
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
exports.findTaxCode = findTaxCode;
|
||||||
|
|||||||
@@ -16,9 +16,9 @@ const {
|
|||||||
setNewRefreshToken,
|
setNewRefreshToken,
|
||||||
} = require("./qbo-callback");
|
} = require("./qbo-callback");
|
||||||
const OAuthClient = require("intuit-oauth");
|
const OAuthClient = require("intuit-oauth");
|
||||||
|
const moment = require("moment");
|
||||||
const GraphQLClient = require("graphql-request").GraphQLClient;
|
const GraphQLClient = require("graphql-request").GraphQLClient;
|
||||||
const { generateOwnerTier } = require("../qbxml/qbxml-utils");
|
const findTaxCode = require("../qb-receivables-lines").findTaxCode;
|
||||||
|
|
||||||
exports.default = async (req, res) => {
|
exports.default = async (req, res) => {
|
||||||
const oauthClient = new OAuthClient({
|
const oauthClient = new OAuthClient({
|
||||||
@@ -53,20 +53,36 @@ exports.default = async (req, res) => {
|
|||||||
.request(queries.QUERY_BILLS_FOR_PAYABLES_EXPORT, {
|
.request(queries.QUERY_BILLS_FOR_PAYABLES_EXPORT, {
|
||||||
bills: billsToQuery,
|
bills: billsToQuery,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { bills } = result;
|
const { bills } = result;
|
||||||
|
const ret = [];
|
||||||
|
|
||||||
for (const bill of bills) {
|
for (const bill of bills) {
|
||||||
let vendorRecord;
|
try {
|
||||||
vendorRecord = await QueryVendorRecord(oauthClient, req, bill);
|
let vendorRecord;
|
||||||
|
vendorRecord = await QueryVendorRecord(oauthClient, req, bill);
|
||||||
|
|
||||||
if (!vendorRecord) {
|
if (!vendorRecord) {
|
||||||
vendorRecord = await InsertVendorRecord(oauthClient, req, bill);
|
vendorRecord = await InsertVendorRecord(oauthClient, req, bill);
|
||||||
|
}
|
||||||
|
|
||||||
|
const insertResults = await InsertBill(
|
||||||
|
oauthClient,
|
||||||
|
req,
|
||||||
|
bill,
|
||||||
|
vendorRecord
|
||||||
|
);
|
||||||
|
ret.push({ billid: bill.id, success: true });
|
||||||
|
} catch (error) {
|
||||||
|
ret.push({
|
||||||
|
billid: bill.id,
|
||||||
|
success: false,
|
||||||
|
errorMessage: error.message,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const insertResults = await InsertBill(oauthClient, req, bill);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({});
|
res.status(200).json(ret);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
logger.log("qbo-payable-create-error", "ERROR", req.user.email, { error });
|
logger.log("qbo-payable-create-error", "ERROR", req.user.email, { error });
|
||||||
@@ -126,54 +142,108 @@ async function InsertVendorRecord(oauthClient, req, bill) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function InsertBill(oauthClient, req, bill) {
|
async function InsertBill(oauthClient, req, bill, vendor) {
|
||||||
const vendor = {
|
const { accounts, taxCodes, classes } = await QueryMetaData(oauthClient, req);
|
||||||
DisplayName: job.ro_number,
|
|
||||||
BillAddr: {
|
const billQbo = {
|
||||||
City: job.ownr_city,
|
VendorRef: {
|
||||||
Line1: job.ownr_addr1,
|
value: vendor.Id,
|
||||||
Line2: job.ownr_addr2,
|
|
||||||
PostalCode: job.ownr_zip,
|
|
||||||
CountrySubDivisionCode: job.ownr_st,
|
|
||||||
},
|
},
|
||||||
...(isThreeTier
|
TxnDate: moment(bill.date).format("YYYY-MM-DD"),
|
||||||
? {
|
DueDate: bill.due_date && moment(bill.due_date).format("YYYY-MM-DD"),
|
||||||
Job: true,
|
DocNumber: bill.invoice_number,
|
||||||
ParentRef: {
|
...(bill.job.class ? { ClassRef: { Id: classes[bill.job.class] } } : {}),
|
||||||
value: parentTierRef.Id,
|
|
||||||
},
|
Memo: `RO ${bill.job.ro_number || ""} OWNER ${bill.job.ownr_fn || ""} ${
|
||||||
}
|
bill.job.ownr_ln || ""
|
||||||
: {}),
|
} ${bill.job.ownr_co_nm || ""}`,
|
||||||
|
Line: bill.billlines.map((il) =>
|
||||||
|
generateBillLine(
|
||||||
|
il,
|
||||||
|
accounts,
|
||||||
|
bill.job.class,
|
||||||
|
bill.job.bodyshop.md_responsibility_centers.sales_tax_codes,
|
||||||
|
classes,
|
||||||
|
taxCodes
|
||||||
|
)
|
||||||
|
),
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
const result = await oauthClient.makeApiCall({
|
const result = await oauthClient.makeApiCall({
|
||||||
url: urlBuilder(req.cookies.qbo_realmId, "vendor"),
|
url: urlBuilder(req.cookies.qbo_realmId, "bill"),
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify(vendor),
|
body: JSON.stringify(billQbo),
|
||||||
});
|
});
|
||||||
setNewRefreshToken(req.user.email, result);
|
setNewRefreshToken(req.user.email, result);
|
||||||
return result && result.Customer;
|
return result && result.Bill;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.log("qbo-payables-error", "DEBUG", req.user.email, bill.id, {
|
logger.log("qbo-payables-error", "DEBUG", req.user.email, bill.id, {
|
||||||
error,
|
error,
|
||||||
method: "InsertOwner",
|
method: "InsertBill",
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// [
|
||||||
|
// {
|
||||||
|
// DetailType: "AccountBasedExpenseLineDetail",
|
||||||
|
// Amount: 200.0,
|
||||||
|
// Id: "1",
|
||||||
|
// AccountBasedExpenseLineDetail: {
|
||||||
|
// AccountRef: {
|
||||||
|
// value: "7",
|
||||||
|
// },
|
||||||
|
// },
|
||||||
|
// },
|
||||||
|
// ],
|
||||||
|
|
||||||
|
const generateBillLine = (
|
||||||
|
billLine,
|
||||||
|
accounts,
|
||||||
|
jobClass,
|
||||||
|
responsibilityCenters,
|
||||||
|
classes,
|
||||||
|
taxCodes
|
||||||
|
) => {
|
||||||
|
return {
|
||||||
|
DetailType: "AccountBasedExpenseLineDetail",
|
||||||
|
|
||||||
|
AccountBasedExpenseLineDetail: {
|
||||||
|
...(jobClass ? { ClassRef: { Id: classes[jobClass] } } : {}),
|
||||||
|
TaxCodeRef: {
|
||||||
|
value:
|
||||||
|
taxCodes[
|
||||||
|
findTaxCode(billLine.applicable_taxes, responsibilityCenters)
|
||||||
|
],
|
||||||
|
},
|
||||||
|
AccountRef: {
|
||||||
|
value: accounts[billLine.cost_center],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
Amount: Dinero({
|
||||||
|
amount: Math.round(billLine.actual_cost * 100),
|
||||||
|
})
|
||||||
|
.multiply(billLine.quantity || 1)
|
||||||
|
.toFormat(DineroQbFormat),
|
||||||
|
};
|
||||||
|
};
|
||||||
async function QueryMetaData(oauthClient, req) {
|
async function QueryMetaData(oauthClient, req) {
|
||||||
const items = await oauthClient.makeApiCall({
|
const accounts = await oauthClient.makeApiCall({
|
||||||
url: urlBuilder(req.cookies.qbo_realmId, "query", `select * From Item`),
|
url: urlBuilder(
|
||||||
|
req.cookies.qbo_realmId,
|
||||||
|
"query",
|
||||||
|
`select * From Account where AccountType = 'Cost of Goods Sold'`
|
||||||
|
),
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
setNewRefreshToken(req.user.email, items);
|
setNewRefreshToken(req.user.email, accounts);
|
||||||
const taxCodes = await oauthClient.makeApiCall({
|
const taxCodes = await oauthClient.makeApiCall({
|
||||||
url: urlBuilder(req.cookies.qbo_realmId, "query", `select * From TaxCode`),
|
url: urlBuilder(req.cookies.qbo_realmId, "query", `select * From TaxCode`),
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -182,368 +252,40 @@ async function QueryMetaData(oauthClient, req) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const taxCodeMapping = {};
|
const classes = await oauthClient.makeApiCall({
|
||||||
|
url: urlBuilder(req.cookies.qbo_realmId, "query", `select * From Class`),
|
||||||
const accounts = await oauthClient.makeApiCall({
|
|
||||||
url: urlBuilder(req.cookies.qbo_realmId, "query", `select * From Account`),
|
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const taxCodeMapping = {};
|
||||||
|
|
||||||
taxCodes.json &&
|
taxCodes.json &&
|
||||||
taxCodes.json.QueryResponse &&
|
taxCodes.json.QueryResponse &&
|
||||||
taxCodes.json.QueryResponse.TaxCode.forEach((t) => {
|
taxCodes.json.QueryResponse.TaxCode.forEach((t) => {
|
||||||
taxCodeMapping[t.Name] = t.Id;
|
taxCodeMapping[t.Name] = t.Id;
|
||||||
});
|
});
|
||||||
|
|
||||||
const itemMapping = {};
|
const accountMapping = {};
|
||||||
|
|
||||||
items.json &&
|
accounts.json &&
|
||||||
items.json.QueryResponse &&
|
accounts.json.QueryResponse &&
|
||||||
items.json.QueryResponse.Item.forEach((t) => {
|
accounts.json.QueryResponse.Account.forEach((t) => {
|
||||||
itemMapping[t.Name] = t.Id;
|
accountMapping[t.Name] = t.Id;
|
||||||
|
});
|
||||||
|
|
||||||
|
const classMapping = {};
|
||||||
|
classes.json &&
|
||||||
|
classes.json.QueryResponse &&
|
||||||
|
classes.json.QueryResponse.Class.forEach((t) => {
|
||||||
|
accountMapping[t.Name] = t.Id;
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
items: itemMapping,
|
accounts: accountMapping,
|
||||||
taxCodes: taxCodeMapping,
|
taxCodes: taxCodeMapping,
|
||||||
|
classes: classMapping,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function InsertInvoice(oauthClient, req, job, bodyshop, parentTierRef) {
|
|
||||||
const { items, taxCodes } = await QueryMetaData(oauthClient, req);
|
|
||||||
const InvoiceLineAdd = [];
|
|
||||||
const responsibilityCenters = bodyshop.md_responsibility_centers;
|
|
||||||
|
|
||||||
const invoiceLineHash = {}; //The hash of cost and profit centers based on the center name.
|
|
||||||
|
|
||||||
//Determine if there are MAPA and MASH lines already on the estimate.
|
|
||||||
//If there are, don't do anything extra (mitchell estimate)
|
|
||||||
//Otherwise, calculate them and add them to the default MAPA and MASH centers.
|
|
||||||
let hasMapaLine = false;
|
|
||||||
let hasMashLine = false;
|
|
||||||
|
|
||||||
//Create the invoice lines mapping.
|
|
||||||
job.joblines.map((jobline) => {
|
|
||||||
//Parts Lines
|
|
||||||
if (jobline.db_ref === "936008") {
|
|
||||||
//If either of these DB REFs change, they also need to change in job-totals/job-costing calculations.
|
|
||||||
hasMapaLine = true;
|
|
||||||
}
|
|
||||||
if (jobline.db_ref === "936007") {
|
|
||||||
hasMashLine = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (jobline.profitcenter_part && jobline.act_price) {
|
|
||||||
let DineroAmount = Dinero({
|
|
||||||
amount: Math.round(jobline.act_price * 100),
|
|
||||||
}).multiply(jobline.part_qty || 1);
|
|
||||||
|
|
||||||
if (jobline.prt_dsmk_p && jobline.prt_dsmk_p !== 0) {
|
|
||||||
// console.log("Have a part discount", jobline);
|
|
||||||
DineroAmount = DineroAmount.add(
|
|
||||||
DineroAmount.percentage(jobline.prt_dsmk_p || 0)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const account = responsibilityCenters.profits.find(
|
|
||||||
(i) => jobline.profitcenter_part.toLowerCase() === i.name.toLowerCase()
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!account) {
|
|
||||||
logger.log("qbxml-payables-no-account", "warn", null, jobline.id, null);
|
|
||||||
throw new Error(
|
|
||||||
`A matching account does not exist for the part allocation. Center: ${jobline.profitcenter_part}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (!invoiceLineHash[account.name]) {
|
|
||||||
invoiceLineHash[account.name] = {
|
|
||||||
ItemRef: { FullName: account.accountitem },
|
|
||||||
Desc: account.accountdesc,
|
|
||||||
Quantity: 1, //jobline.part_qty,
|
|
||||||
Amount: DineroAmount, //.toFormat(DineroQbFormat),
|
|
||||||
SalesTaxCodeRef: {
|
|
||||||
FullName: "E",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
invoiceLineHash[account.name].Amount =
|
|
||||||
invoiceLineHash[account.name].Amount.add(DineroAmount);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Labor Lines
|
|
||||||
if (jobline.profitcenter_labor && jobline.mod_lb_hrs) {
|
|
||||||
const DineroAmount = Dinero({
|
|
||||||
amount: Math.round(
|
|
||||||
job[`rate_${jobline.mod_lbr_ty.toLowerCase()}`] * 100
|
|
||||||
),
|
|
||||||
}).multiply(jobline.mod_lb_hrs);
|
|
||||||
const account = responsibilityCenters.profits.find(
|
|
||||||
(i) => jobline.profitcenter_labor.toLowerCase() === i.name.toLowerCase()
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!account) {
|
|
||||||
throw new Error(
|
|
||||||
`A matching account does not exist for the labor allocation. Center: ${jobline.profitcenter_labor}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (!invoiceLineHash[account.name]) {
|
|
||||||
invoiceLineHash[account.name] = {
|
|
||||||
ItemRef: { FullName: account.accountitem },
|
|
||||||
Desc: account.accountdesc,
|
|
||||||
Quantity: 1, // jobline.mod_lb_hrs,
|
|
||||||
Amount: DineroAmount,
|
|
||||||
//Amount: DineroAmount.toFormat(DineroQbFormat),
|
|
||||||
SalesTaxCodeRef: {
|
|
||||||
FullName: "E",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
invoiceLineHash[account.name].Amount =
|
|
||||||
invoiceLineHash[account.name].Amount.add(DineroAmount);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
// console.log("Done creating hash", JSON.stringify(invoiceLineHash));
|
|
||||||
|
|
||||||
if (!hasMapaLine && job.job_totals.rates.mapa.total.amount > 0) {
|
|
||||||
// console.log("Adding MAPA Line Manually.");
|
|
||||||
const mapaAccountName = responsibilityCenters.defaults.profits.MAPA;
|
|
||||||
|
|
||||||
const mapaAccount = responsibilityCenters.profits.find(
|
|
||||||
(c) => c.name === mapaAccountName
|
|
||||||
);
|
|
||||||
|
|
||||||
if (mapaAccount) {
|
|
||||||
InvoiceLineAdd.push({
|
|
||||||
ItemRef: { FullName: mapaAccount.accountitem },
|
|
||||||
Desc: mapaAccount.accountdesc,
|
|
||||||
Quantity: 1,
|
|
||||||
Amount: Dinero(job.job_totals.rates.mapa.total).toFormat(
|
|
||||||
DineroQbFormat
|
|
||||||
),
|
|
||||||
SalesTaxCodeRef: {
|
|
||||||
FullName: "E",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
//console.log("NO MAPA ACCOUNT FOUND!!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!hasMashLine && job.job_totals.rates.mash.total.amount > 0) {
|
|
||||||
// console.log("Adding MASH Line Manually.");
|
|
||||||
|
|
||||||
const mashAccountName = responsibilityCenters.defaults.profits.MASH;
|
|
||||||
|
|
||||||
const mashAccount = responsibilityCenters.profits.find(
|
|
||||||
(c) => c.name === mashAccountName
|
|
||||||
);
|
|
||||||
|
|
||||||
if (mashAccount) {
|
|
||||||
InvoiceLineAdd.push({
|
|
||||||
ItemRef: { FullName: mashAccount.accountitem },
|
|
||||||
Desc: mashAccount.accountdesc,
|
|
||||||
Quantity: 1,
|
|
||||||
Amount: Dinero(job.job_totals.rates.mash.total).toFormat(
|
|
||||||
DineroQbFormat
|
|
||||||
),
|
|
||||||
SalesTaxCodeRef: {
|
|
||||||
FullName: "E",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// console.log("NO MASH ACCOUNT FOUND!!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//Convert the hash to an array.
|
|
||||||
Object.keys(invoiceLineHash).forEach((key) => {
|
|
||||||
InvoiceLineAdd.push({
|
|
||||||
...invoiceLineHash[key],
|
|
||||||
Amount: invoiceLineHash[key].Amount.toFormat(DineroQbFormat),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
//Add Towing, storage and adjustment lines.
|
|
||||||
|
|
||||||
if (job.towing_payable && job.towing_payable !== 0) {
|
|
||||||
InvoiceLineAdd.push({
|
|
||||||
ItemRef: {
|
|
||||||
FullName: responsibilityCenters.profits.find(
|
|
||||||
(c) => c.name === responsibilityCenters.defaults.profits["TOW"]
|
|
||||||
).accountitem,
|
|
||||||
},
|
|
||||||
Desc: "Towing",
|
|
||||||
Quantity: 1,
|
|
||||||
Amount: Dinero({
|
|
||||||
amount: Math.round((job.towing_payable || 0) * 100),
|
|
||||||
}).toFormat(DineroQbFormat),
|
|
||||||
SalesTaxCodeRef: {
|
|
||||||
FullName: "E",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (job.storage_payable && job.storage_payable !== 0) {
|
|
||||||
InvoiceLineAdd.push({
|
|
||||||
ItemRef: {
|
|
||||||
FullName: responsibilityCenters.profits.find(
|
|
||||||
(c) => c.name === responsibilityCenters.defaults.profits["TOW"]
|
|
||||||
).accountitem,
|
|
||||||
},
|
|
||||||
Desc: "Storage",
|
|
||||||
Quantity: 1,
|
|
||||||
Amount: Dinero({
|
|
||||||
amount: Math.round((job.storage_payable || 0) * 100),
|
|
||||||
}).toFormat(DineroQbFormat),
|
|
||||||
SalesTaxCodeRef: {
|
|
||||||
FullName: "E",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (job.adjustment_bottom_line && job.adjustment_bottom_line !== 0) {
|
|
||||||
InvoiceLineAdd.push({
|
|
||||||
ItemRef: {
|
|
||||||
FullName: responsibilityCenters.profits.find(
|
|
||||||
(c) => c.name === responsibilityCenters.defaults.profits["PAO"]
|
|
||||||
).accountitem,
|
|
||||||
},
|
|
||||||
Desc: "Adjustment",
|
|
||||||
Quantity: 1,
|
|
||||||
Amount: Dinero({
|
|
||||||
amount: Math.round((job.adjustment_bottom_line || 0) * 100),
|
|
||||||
}).toFormat(DineroQbFormat),
|
|
||||||
SalesTaxCodeRef: {
|
|
||||||
FullName: "E",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
//Add tax lines
|
|
||||||
const job_totals = job.job_totals;
|
|
||||||
|
|
||||||
const federal_tax = Dinero(job_totals.totals.federal_tax);
|
|
||||||
const state_tax = Dinero(job_totals.totals.state_tax);
|
|
||||||
const local_tax = Dinero(job_totals.totals.local_tax);
|
|
||||||
|
|
||||||
if (federal_tax.getAmount() > 0) {
|
|
||||||
InvoiceLineAdd.push({
|
|
||||||
ItemRef: {
|
|
||||||
FullName: bodyshop.md_responsibility_centers.taxes.federal.accountitem,
|
|
||||||
},
|
|
||||||
Desc: bodyshop.md_responsibility_centers.taxes.federal.accountdesc,
|
|
||||||
Amount: federal_tax.toFormat(DineroQbFormat),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (state_tax.getAmount() > 0) {
|
|
||||||
InvoiceLineAdd.push({
|
|
||||||
ItemRef: {
|
|
||||||
FullName: bodyshop.md_responsibility_centers.taxes.state.accountitem,
|
|
||||||
},
|
|
||||||
Desc: bodyshop.md_responsibility_centers.taxes.state.accountdesc,
|
|
||||||
Amount: state_tax.toFormat(DineroQbFormat),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (local_tax.getAmount() > 0) {
|
|
||||||
InvoiceLineAdd.push({
|
|
||||||
ItemRef: {
|
|
||||||
FullName: bodyshop.md_responsibility_centers.taxes.local.accountitem,
|
|
||||||
},
|
|
||||||
Desc: bodyshop.md_responsibility_centers.taxes.local.accountdesc,
|
|
||||||
Amount: local_tax.toFormat(DineroQbFormat),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
//Region Specific
|
|
||||||
const { ca_bc_pvrt } = job;
|
|
||||||
if (ca_bc_pvrt) {
|
|
||||||
InvoiceLineAdd.push({
|
|
||||||
ItemRef: {
|
|
||||||
FullName: bodyshop.md_responsibility_centers.taxes.state.accountitem,
|
|
||||||
},
|
|
||||||
Desc: "PVRT",
|
|
||||||
Amount: Dinero({ amount: (ca_bc_pvrt || 0) * 100 }).toFormat(
|
|
||||||
DineroQbFormat
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
//map each invoice line to the correct style for QBO.
|
|
||||||
|
|
||||||
const invoiceObj = {
|
|
||||||
Line: [
|
|
||||||
{
|
|
||||||
DetailType: "SalesItemLineDetail",
|
|
||||||
Amount: 100,
|
|
||||||
SalesItemLineDetail: {
|
|
||||||
// ItemRef: {
|
|
||||||
// // name: "Services",
|
|
||||||
// value: "16",
|
|
||||||
// },
|
|
||||||
TaxCodeRef: {
|
|
||||||
value: "2",
|
|
||||||
},
|
|
||||||
Qty: 1,
|
|
||||||
UnitPrice: 100,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
// Line: InvoiceLineAdd.map((i) => {
|
|
||||||
// return {
|
|
||||||
// DetailType: "SalesItemLineDetail",
|
|
||||||
// Amount: i.Amount,
|
|
||||||
// SalesItemLineDetail: {
|
|
||||||
// ItemRef: {
|
|
||||||
// //name: "Services",
|
|
||||||
// value: items[i.ItemRef.FullName],
|
|
||||||
// },
|
|
||||||
// // TaxCodeRef: {
|
|
||||||
// // value: "2",
|
|
||||||
// // },
|
|
||||||
// Qty: 1,
|
|
||||||
// },
|
|
||||||
// };
|
|
||||||
// }),
|
|
||||||
TxnTaxDetail: {
|
|
||||||
TaxLine: [
|
|
||||||
{
|
|
||||||
DetailType: "TaxLineDetail",
|
|
||||||
|
|
||||||
TaxLineDetail: {
|
|
||||||
NetAmountTaxable: 100,
|
|
||||||
TaxPercent: 7,
|
|
||||||
TaxRateRef: {
|
|
||||||
value: "16",
|
|
||||||
},
|
|
||||||
PercentBased: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
CustomerRef: {
|
|
||||||
value: parentTierRef.Id,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await oauthClient.makeApiCall({
|
|
||||||
url: urlBuilder(req.cookies.qbo_realmId, "invoice"),
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify(invoiceObj),
|
|
||||||
});
|
|
||||||
setNewRefreshToken(req.user.email, result);
|
|
||||||
return result && result.Invoice;
|
|
||||||
} catch (error) {
|
|
||||||
logger.log("qbo-payables-error", "DEBUG", req.user.email, job.id, {
|
|
||||||
error,
|
|
||||||
method: "InsertOwner",
|
|
||||||
});
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ const {
|
|||||||
setNewRefreshToken,
|
setNewRefreshToken,
|
||||||
} = require("./qbo-callback");
|
} = require("./qbo-callback");
|
||||||
const OAuthClient = require("intuit-oauth");
|
const OAuthClient = require("intuit-oauth");
|
||||||
const CreateInvoiceLines = require("../qb-receivables-lines");
|
const CreateInvoiceLines = require("../qb-receivables-lines").default;
|
||||||
const moment = require("moment");
|
const moment = require("moment");
|
||||||
|
|
||||||
const GraphQLClient = require("graphql-request").GraphQLClient;
|
const GraphQLClient = require("graphql-request").GraphQLClient;
|
||||||
@@ -332,6 +332,14 @@ async function QueryMetaData(oauthClient, req) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const classes = await oauthClient.makeApiCall({
|
||||||
|
url: urlBuilder(req.cookies.qbo_realmId, "query", `select * From Class`),
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const taxCodeMapping = {};
|
const taxCodeMapping = {};
|
||||||
|
|
||||||
taxCodes.json &&
|
taxCodes.json &&
|
||||||
@@ -348,14 +356,22 @@ async function QueryMetaData(oauthClient, req) {
|
|||||||
itemMapping[t.Name] = t.Id;
|
itemMapping[t.Name] = t.Id;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const classMapping = {};
|
||||||
|
classes.json &&
|
||||||
|
classes.json.QueryResponse &&
|
||||||
|
classes.json.QueryResponse.Class.forEach((t) => {
|
||||||
|
itemMapping[t.Name] = t.Id;
|
||||||
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
items: itemMapping,
|
items: itemMapping,
|
||||||
taxCodes: taxCodeMapping,
|
taxCodes: taxCodeMapping,
|
||||||
|
classes: classMapping,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function InsertInvoice(oauthClient, req, job, bodyshop, parentTierRef) {
|
async function InsertInvoice(oauthClient, req, job, bodyshop, parentTierRef) {
|
||||||
const { items, taxCodes } = await QueryMetaData(oauthClient, req);
|
const { items, taxCodes, classes } = await QueryMetaData(oauthClient, req);
|
||||||
const InvoiceLineAdd = CreateInvoiceLines({
|
const InvoiceLineAdd = CreateInvoiceLines({
|
||||||
bodyshop,
|
bodyshop,
|
||||||
jobs_by_pk: job,
|
jobs_by_pk: job,
|
||||||
@@ -368,6 +384,7 @@ async function InsertInvoice(oauthClient, req, job, bodyshop, parentTierRef) {
|
|||||||
Line: InvoiceLineAdd,
|
Line: InvoiceLineAdd,
|
||||||
TxnDate: moment(job.date_invoiced).format("YYYY-MM-DD"),
|
TxnDate: moment(job.date_invoiced).format("YYYY-MM-DD"),
|
||||||
DocNumber: job.ro_number,
|
DocNumber: job.ro_number,
|
||||||
|
...(job.class ? { ClassRef: { Id: classes[job.class] } } : {}),
|
||||||
CustomerRef: {
|
CustomerRef: {
|
||||||
value: parentTierRef.Id,
|
value: parentTierRef.Id,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ const moment = require("moment");
|
|||||||
var builder = require("xmlbuilder2");
|
var builder = require("xmlbuilder2");
|
||||||
const QbXmlUtils = require("./qbxml-utils");
|
const QbXmlUtils = require("./qbxml-utils");
|
||||||
const logger = require("../../utils/logger");
|
const logger = require("../../utils/logger");
|
||||||
const CreateInvoiceLines = require("../qb-receivables-lines");
|
const CreateInvoiceLines = require("../qb-receivables-lines").default;
|
||||||
|
|
||||||
require("dotenv").config({
|
require("dotenv").config({
|
||||||
path: path.resolve(
|
path: path.resolve(
|
||||||
@@ -109,7 +109,7 @@ exports.default = async (req, res) => {
|
|||||||
"error",
|
"error",
|
||||||
req.user.email,
|
req.user.email,
|
||||||
req.body.jobIds,
|
req.body.jobIds,
|
||||||
{error: (error)}
|
{ error: error }
|
||||||
);
|
);
|
||||||
res.status(400).send(JSON.stringify(error));
|
res.status(400).send(JSON.stringify(error));
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user