1098 lines
33 KiB
JavaScript
1098 lines
33 KiB
JavaScript
const Dinero = require("dinero.js");
|
|
const queries = require("../graphql-client/queries");
|
|
const GraphQLClient = require("graphql-request").GraphQLClient;
|
|
const adminClient = require("../graphql-client/graphql-client").client;
|
|
const _ = require("lodash");
|
|
const logger = require("../utils/logger");
|
|
// Dinero.defaultCurrency = "USD";
|
|
// Dinero.globalLocale = "en-CA";
|
|
Dinero.globalRoundingMode = "HALF_EVEN";
|
|
|
|
exports.totalsSsu = async function (req, res) {
|
|
const BearerToken = req.headers.authorization;
|
|
const { id } = req.body;
|
|
logger.log("job-totals-ssu", "DEBUG", req.user.email, id, null);
|
|
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {
|
|
headers: {
|
|
Authorization: BearerToken,
|
|
},
|
|
});
|
|
|
|
try {
|
|
const job = await client
|
|
.setHeaders({ Authorization: BearerToken })
|
|
.request(queries.GET_JOB_BY_PK, {
|
|
id: id,
|
|
});
|
|
|
|
const newTotals = await TotalsServerSide(
|
|
{ body: { job: job.jobs_by_pk, client: client } },
|
|
res,
|
|
true
|
|
);
|
|
|
|
const result = await client
|
|
.setHeaders({ Authorization: BearerToken })
|
|
.request(queries.UPDATE_JOB, {
|
|
jobId: id,
|
|
job: {
|
|
clm_total: newTotals.totals.total_repairs.toFormat("0.00"),
|
|
owner_owing: newTotals.totals.custPayable.total.toFormat("0.00"),
|
|
job_totals: newTotals,
|
|
//queued_for_parts: true,
|
|
},
|
|
});
|
|
|
|
res.status(200).send();
|
|
} catch (error) {
|
|
logger.log("job-totals-ssu-error", "ERROR", req.user.email, id, {
|
|
jobid: id,
|
|
error,
|
|
});
|
|
res.status(503).send();
|
|
}
|
|
};
|
|
|
|
//IMPORTANT*** These two functions MUST be mirrrored.
|
|
async function TotalsServerSide(req, res) {
|
|
const { job, client } = req.body;
|
|
await AutoAddAtsIfRequired({ job: job, client: client });
|
|
|
|
try {
|
|
let ret = {
|
|
rates: await CalculateRatesTotals({ job, client }),
|
|
parts: CalculatePartsTotals(job.joblines, job.parts_tax_rates, job),
|
|
additional: CalculateAdditional(job),
|
|
};
|
|
ret.totals = CalculateTaxesTotals(job, ret);
|
|
|
|
return ret;
|
|
} catch (error) {
|
|
logger.log("job-totals-ssu-error", "ERROR", req.user?.email, job.id, {
|
|
jobid: job.id,
|
|
error,
|
|
});
|
|
res.status(400).send(JSON.stringify(error));
|
|
}
|
|
}
|
|
|
|
async function Totals(req, res) {
|
|
const { job } = req.body;
|
|
logger.log("job-totals", "DEBUG", req.user.email, job.id, {
|
|
jobid: job.id,
|
|
});
|
|
|
|
const BearerToken = req.headers.authorization;
|
|
const { id } = req.body;
|
|
logger.log("job-totals-ssu", "DEBUG", req.user.email, id, null);
|
|
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {
|
|
headers: {
|
|
Authorization: BearerToken,
|
|
},
|
|
});
|
|
|
|
await AutoAddAtsIfRequired({ job, client });
|
|
try {
|
|
let ret = {
|
|
rates: await CalculateRatesTotals({ job, client }),
|
|
parts: CalculatePartsTotals(job.joblines, job.parts_tax_rates, job),
|
|
additional: CalculateAdditional(job),
|
|
};
|
|
ret.totals = CalculateTaxesTotals(job, ret);
|
|
|
|
res.status(200).json(ret);
|
|
} catch (error) {
|
|
logger.log("job-totals-error", "ERROR", req.user.email, job.id, {
|
|
jobid: job.id,
|
|
error,
|
|
});
|
|
res.status(400).send(JSON.stringify(error));
|
|
}
|
|
}
|
|
|
|
async function AutoAddAtsIfRequired({ job, client }) {
|
|
//Check if ATS should be automatically added.
|
|
if (job.auto_add_ats) {
|
|
//Get the total sum of hours that should be the ATS amount.
|
|
//Check to see if an ATS line exists.
|
|
let atsLineIndex = null;
|
|
const atsHours = job.joblines.reduce((acc, val, index) => {
|
|
if (val.line_desc && val.line_desc.toLowerCase() === "ats amount") {
|
|
atsLineIndex = index;
|
|
}
|
|
|
|
if (
|
|
val.mod_lbr_ty !== "LA1" &&
|
|
val.mod_lbr_ty !== "LA2" &&
|
|
val.mod_lbr_ty !== "LA3" &&
|
|
val.mod_lbr_ty !== "LA4" &&
|
|
val.mod_lbr_ty !== "LAU" &&
|
|
val.mod_lbr_ty !== "LAG" &&
|
|
val.mod_lbr_ty !== "LAS" &&
|
|
val.mod_lbr_ty !== "LAA"
|
|
) {
|
|
acc = acc + val.mod_lb_hrs;
|
|
}
|
|
|
|
return acc;
|
|
}, 0);
|
|
|
|
const atsAmount = atsHours * (job.rate_ats || 0);
|
|
//If it does, update it in place, and make sure it is updated for local calculations.
|
|
if (atsLineIndex === null) {
|
|
const newAtsLine = {
|
|
jobid: job.id,
|
|
alt_partm: null,
|
|
line_no: 35,
|
|
unq_seq: 0,
|
|
line_ind: "E",
|
|
line_desc: "ATS Amount",
|
|
line_ref: 0.0,
|
|
part_type: null,
|
|
oem_partno: null,
|
|
db_price: 0.0,
|
|
act_price: atsAmount,
|
|
part_qty: 1,
|
|
mod_lbr_ty: null,
|
|
db_hrs: 0.0,
|
|
mod_lb_hrs: 0.0,
|
|
lbr_op: "OP13",
|
|
lbr_amt: 0.0,
|
|
op_code_desc: "ADDITIONAL COSTS",
|
|
status: null,
|
|
location: null,
|
|
tax_part: true,
|
|
db_ref: null,
|
|
manual_line: true,
|
|
prt_dsmk_p: 0.0,
|
|
prt_dsmk_m: 0.0,
|
|
};
|
|
|
|
const result = await client.request(queries.INSERT_NEW_JOB_LINE, {
|
|
lineInput: [newAtsLine],
|
|
});
|
|
|
|
job.joblines.push(newAtsLine);
|
|
}
|
|
//If it does not, create one for local calculations and insert it.
|
|
else {
|
|
const result = await client.request(queries.UPDATE_JOB_LINE, {
|
|
line: { act_price: atsAmount },
|
|
lineId: job.joblines[atsLineIndex].id,
|
|
});
|
|
job.joblines[atsLineIndex].act_price = atsAmount;
|
|
}
|
|
}
|
|
}
|
|
|
|
async function CalculateRatesTotals({ job, client }) {
|
|
const jobLines = job.joblines.filter((jl) => !jl.removed);
|
|
|
|
let ret = {
|
|
la1: {
|
|
hours: 0,
|
|
rate: job.rate_la1 || 0,
|
|
},
|
|
la2: {
|
|
hours: 0,
|
|
rate: job.rate_la2 || 0,
|
|
},
|
|
la3: {
|
|
rate: job.rate_la3 || 0,
|
|
hours: 0,
|
|
},
|
|
la4: {
|
|
rate: job.rate_la4 || 0,
|
|
hours: 0,
|
|
},
|
|
laa: {
|
|
rate: job.rate_laa || 0,
|
|
hours: 0,
|
|
},
|
|
lab: {
|
|
rate: job.rate_lab || 0,
|
|
hours: 0,
|
|
},
|
|
lad: {
|
|
rate: job.rate_lad || 0,
|
|
hours: 0,
|
|
},
|
|
lae: {
|
|
rate: job.rate_lae || 0,
|
|
hours: 0,
|
|
},
|
|
laf: {
|
|
rate: job.rate_laf || 0,
|
|
hours: 0,
|
|
},
|
|
lag: {
|
|
rate: job.rate_lag || 0,
|
|
hours: 0,
|
|
},
|
|
lam: {
|
|
rate: job.rate_lam || 0,
|
|
hours: 0,
|
|
},
|
|
lar: {
|
|
rate: job.rate_lar || 0,
|
|
hours: 0,
|
|
},
|
|
las: {
|
|
rate: job.rate_las || 0,
|
|
hours: 0,
|
|
},
|
|
lau: {
|
|
rate: job.rate_lau || 0,
|
|
hours: 0,
|
|
},
|
|
mapa: {
|
|
rate: job.rate_mapa || 0,
|
|
hours: 0,
|
|
},
|
|
mash: {
|
|
rate: job.rate_mash || 0,
|
|
hours: 0,
|
|
},
|
|
};
|
|
|
|
//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;
|
|
let hasMahwLine = false;
|
|
let mapaOpCodes = ParseCalopCode(job.materials["mapa"]?.cal_opcode);
|
|
let mashOpCodes = ParseCalopCode(job.materials["mash"]?.cal_opcode);
|
|
|
|
jobLines.forEach((item) => {
|
|
//IO-1317 Use the lines on the estimate if they exist instead.
|
|
if (item.db_ref === "936008") {
|
|
//If either of these DB REFs change, they also need to change in job-totals/job-costing calculations.
|
|
hasMapaLine = true;
|
|
ret["mapa"].total = Dinero({
|
|
amount: Math.round((item.act_price || 0) * 100),
|
|
});
|
|
}
|
|
if (item.db_ref === "936007") {
|
|
hasMashLine = true;
|
|
ret["mash"].total = Dinero({
|
|
amount: Math.round((item.act_price || 0) * 100),
|
|
});
|
|
}
|
|
if (item.line_desc?.toLowerCase().includes("hazardous waste")) {
|
|
hasMahwLine = item;
|
|
}
|
|
|
|
if (item.mod_lbr_ty) {
|
|
//Check to see if it has 0 hours and a price instead.
|
|
if (
|
|
item.mod_lb_hrs === 0 &&
|
|
item.act_price > 0 &&
|
|
item.lbr_op === "OP14"
|
|
) {
|
|
//Scenario where SGI may pay out hours using a part price.
|
|
if (!ret[item.mod_lbr_ty.toLowerCase()].total) {
|
|
ret[item.mod_lbr_ty.toLowerCase()].total = Dinero();
|
|
}
|
|
ret[item.mod_lbr_ty.toLowerCase()].total = ret[
|
|
item.mod_lbr_ty.toLowerCase()
|
|
].total.add(
|
|
Dinero({ amount: Math.round((item.act_price || 0) * 100) }).multiply(
|
|
item.part_qty
|
|
)
|
|
);
|
|
}
|
|
|
|
//There's a labor type, assign the hours.
|
|
ret[item.mod_lbr_ty.toLowerCase()].hours =
|
|
ret[item.mod_lbr_ty.toLowerCase()].hours + item.mod_lb_hrs;
|
|
|
|
//Count up the number of materials/paint hours.
|
|
|
|
//Following change may be CCC specific.
|
|
if (item.mod_lbr_ty === "LAR") {
|
|
// if (mapaOpCodes.includes(item.lbr_op)) { //Unknown if this is needed. Seems to be ignored.
|
|
ret.mapa.hours = ret.mapa.hours + item.mod_lb_hrs;
|
|
// }
|
|
} else {
|
|
if (mashOpCodes.length === 0 || mashOpCodes.includes(item.lbr_op)) {
|
|
// Added when processing CIECA ID 14A60015 to have materials match.
|
|
ret.mash.hours = ret.mash.hours + item.mod_lb_hrs; //Apparently there may be an exclusion for glass hours in BC.
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
let subtotal = Dinero({ amount: 0 });
|
|
let rates_subtotal = Dinero({ amount: 0 });
|
|
|
|
for (const property in ret) {
|
|
//Skip calculating mapa and mash if we got the amounts.
|
|
if (
|
|
!(
|
|
(property === "mapa" && hasMapaLine) ||
|
|
(property === "mash" && hasMashLine)
|
|
)
|
|
) {
|
|
if (!ret[property].total) {
|
|
ret[property].total = Dinero();
|
|
}
|
|
let threshold;
|
|
//Check if there is a max for this type.
|
|
if (job.materials && job.materials[property]) {
|
|
//
|
|
|
|
if (
|
|
job.materials[property].cal_maxdlr !== undefined &&
|
|
job.materials[property].cal_maxdlr >= 0
|
|
) {
|
|
//It has an upper threshhold.
|
|
threshold = Dinero({
|
|
amount: Math.round(job.materials[property].cal_maxdlr * 100),
|
|
});
|
|
}
|
|
}
|
|
|
|
const total = Dinero({
|
|
amount: Math.round((ret[property].rate || 0) * 100),
|
|
}).multiply(ret[property].hours);
|
|
|
|
if (threshold && total.greaterThanOrEqual(threshold)) {
|
|
ret[property].total = ret[property].total.add(threshold);
|
|
} else {
|
|
ret[property].total = ret[property].total.add(total);
|
|
}
|
|
}
|
|
|
|
subtotal = subtotal.add(ret[property].total);
|
|
|
|
if (property !== "mapa" && property !== "mash")
|
|
rates_subtotal = rates_subtotal.add(ret[property].total);
|
|
}
|
|
|
|
const stlMahw = job.cieca_stl?.data.find((c) => c.ttl_typecd === "MAHW");
|
|
|
|
if (
|
|
stlMahw &&
|
|
stlMahw.ttl_amt !== 0 &&
|
|
(!hasMahwLine || hasMahwLine.act_price !== stlMahw.ttl_amt)
|
|
) {
|
|
//Add a hazardous waste material line in case there isn't one on the estimate.
|
|
if (hasMahwLine) {
|
|
//Update it
|
|
job.joblines.forEach((jl) => {
|
|
if (jl.id === hasMahwLine.id) {
|
|
jl.act_price = stlMahw.ttl_amt;
|
|
}
|
|
});
|
|
await client.request(queries.UPDATE_JOB_LINE, {
|
|
lineId: hasMahwLine.id,
|
|
line: { act_price: stlMahw.ttl_amt },
|
|
});
|
|
} else {
|
|
const newMahwLine = {
|
|
line_desc: "Hazardous Waste Removal*",
|
|
part_type: "PAS",
|
|
oem_partno: null,
|
|
db_price: 0,
|
|
act_price: stlMahw.ttl_amt,
|
|
part_qty: 1,
|
|
//mod_lbr_ty: "LAB",
|
|
db_hrs: 0,
|
|
mod_lb_hrs: 0,
|
|
lbr_op: "OP11",
|
|
lbr_amt: 0,
|
|
op_code_desc: "REMOVE / REPLACE",
|
|
tax_part: stlMahw.tax_amt > 0 ? true : false,
|
|
db_ref: null,
|
|
manual_line: true,
|
|
jobid: job.id,
|
|
};
|
|
job.joblines.push(newMahwLine);
|
|
await client.request(queries.INSERT_NEW_JOB_LINE, {
|
|
lineInput: [newMahwLine],
|
|
});
|
|
}
|
|
}
|
|
|
|
//Materials Scrubbing as required by CCC.
|
|
let matTotalLine = job.cieca_stl.data.find((l) => l.ttl_typecd === "MAT");
|
|
let shopMatLine = job.cieca_stl.data.find((l) => l.ttl_typecd === "MASH");
|
|
|
|
if (matTotalLine && shopMatLine) {
|
|
//Check to see if theyre different
|
|
let calcMapaAmount = Dinero({
|
|
amount: Math.round(
|
|
(matTotalLine?.ttl_amt - shopMatLine?.ttl_amt - stlMahw?.ttl_amt) * 100
|
|
),
|
|
});
|
|
let mapaDifference = calcMapaAmount.subtract(ret.mapa.total);
|
|
if (mapaDifference.getAmount() > 0) {
|
|
//fix it.
|
|
ret.mapa.total = calcMapaAmount;
|
|
//Add the difference to the subt total as well.
|
|
subtotal = subtotal.add(mapaDifference);
|
|
}
|
|
}
|
|
ret.subtotal = subtotal;
|
|
ret.rates_subtotal = rates_subtotal;
|
|
|
|
ret.mapa.hasMapaLine = hasMapaLine;
|
|
ret.mash.hasMashLine = hasMashLine;
|
|
return ret;
|
|
}
|
|
|
|
function CalculatePartsTotals(jobLines, parts_tax_rates, job) {
|
|
const jl = jobLines.filter((jl) => !jl.removed);
|
|
const ret = jl.reduce(
|
|
(acc, value) => {
|
|
switch (value.part_type) {
|
|
case "PAS":
|
|
case "PASL":
|
|
return {
|
|
...acc,
|
|
sublets: {
|
|
...acc.sublets,
|
|
subtotal: acc.sublets.subtotal.add(
|
|
Dinero({
|
|
amount: Math.round(value.act_price * 100),
|
|
})
|
|
.multiply(value.part_qty || 0)
|
|
.add(
|
|
((value.prt_dsmk_m && value.prt_dsmk_m !== 0) ||
|
|
(value.prt_dsmk_p && value.prt_dsmk_p !== 0)) &&
|
|
DiscountNotAlreadyCounted(value, jl)
|
|
? value.prt_dsmk_m
|
|
? Dinero({ amount: Math.round(value.prt_dsmk_m * 100) })
|
|
: Dinero({
|
|
amount: Math.round(value.act_price * 100),
|
|
})
|
|
.multiply(value.part_qty || 0)
|
|
.percentage(Math.abs(value.prt_dsmk_p || 0))
|
|
.multiply(value.prt_dsmk_p > 0 ? 1 : -1)
|
|
: Dinero()
|
|
)
|
|
),
|
|
},
|
|
};
|
|
|
|
default:
|
|
if (
|
|
!value.part_type &&
|
|
value.db_ref !== "900510" &&
|
|
value.db_ref !== "900511"
|
|
)
|
|
return acc;
|
|
return {
|
|
...acc,
|
|
parts: {
|
|
...acc.parts,
|
|
prt_dsmk_total: acc.parts.prt_dsmk_total.add(
|
|
((value.prt_dsmk_m && value.prt_dsmk_m !== 0) ||
|
|
(value.prt_dsmk_p && value.prt_dsmk_p !== 0)) &&
|
|
DiscountNotAlreadyCounted(value, jl)
|
|
? value.prt_dsmk_m
|
|
? Dinero({ amount: Math.round(value.prt_dsmk_m * 100) })
|
|
: Dinero({
|
|
amount: Math.round(value.act_price * 100),
|
|
})
|
|
.multiply(value.part_qty || 0)
|
|
.percentage(Math.abs(value.prt_dsmk_p || 0))
|
|
.multiply(value.prt_dsmk_p > 0 ? 1 : -1)
|
|
: Dinero()
|
|
),
|
|
...(value.part_type
|
|
? {
|
|
list: {
|
|
...acc.parts.list,
|
|
[value.part_type]:
|
|
acc.parts.list[value.part_type] &&
|
|
acc.parts.list[value.part_type].total
|
|
? {
|
|
total: acc.parts.list[value.part_type].total.add(
|
|
Dinero({
|
|
amount: Math.round(
|
|
(value.act_price || 0) * 100
|
|
),
|
|
}).multiply(value.part_qty || 0)
|
|
),
|
|
}
|
|
: {
|
|
total: Dinero({
|
|
amount: Math.round(
|
|
(value.act_price || 0) * 100
|
|
),
|
|
}).multiply(value.part_qty || 0),
|
|
},
|
|
},
|
|
}
|
|
: {}),
|
|
subtotal: acc.parts.subtotal
|
|
.add(
|
|
Dinero({
|
|
amount: Math.round(value.act_price * 100),
|
|
}).multiply(value.part_qty || 0)
|
|
)
|
|
.add(
|
|
((value.prt_dsmk_m && value.prt_dsmk_m !== 0) ||
|
|
(value.prt_dsmk_p && value.prt_dsmk_p !== 0)) &&
|
|
DiscountNotAlreadyCounted(value, jl)
|
|
? value.prt_dsmk_m
|
|
? Dinero({ amount: Math.round(value.prt_dsmk_m * 100) })
|
|
: Dinero({
|
|
amount: Math.round(value.act_price * 100),
|
|
})
|
|
.multiply(value.part_qty || 0)
|
|
.percentage(Math.abs(value.prt_dsmk_p || 0))
|
|
.multiply(value.prt_dsmk_p > 0 ? 1 : -1)
|
|
: Dinero()
|
|
),
|
|
},
|
|
};
|
|
}
|
|
},
|
|
{
|
|
parts: {
|
|
list: {},
|
|
prt_dsmk_total: Dinero(),
|
|
subtotal: Dinero({ amount: 0 }),
|
|
total: Dinero({ amount: 0 }),
|
|
},
|
|
sublets: {
|
|
subtotal: Dinero({ amount: 0 }),
|
|
|
|
total: Dinero({ amount: 0 }),
|
|
},
|
|
}
|
|
);
|
|
|
|
//Apply insurance based parts discuounts/markups.
|
|
let adjustments = {
|
|
PAA: Dinero(),
|
|
PAC: Dinero(),
|
|
PAG: Dinero(),
|
|
PAL: Dinero(),
|
|
PAN: Dinero(),
|
|
PAO: Dinero(),
|
|
PAP: Dinero(),
|
|
PAR: Dinero(),
|
|
PAS: Dinero(),
|
|
PAT: Dinero(),
|
|
};
|
|
//Track all adjustments that need to be made.
|
|
|
|
const linesToAdjustForDiscount = [];
|
|
Object.keys(parts_tax_rates).forEach((key) => {
|
|
//Check if there's a discount or a mark up.
|
|
let disc = Dinero(),
|
|
markup = Dinero();
|
|
|
|
let discountRate, markupRate;
|
|
if (
|
|
parts_tax_rates[key].prt_discp !== undefined &&
|
|
parts_tax_rates[key].prt_discp >= 0
|
|
) {
|
|
//Check if there's any parts in this part type.
|
|
if (ret.parts.list[key] !== undefined) {
|
|
discountRate =
|
|
Math.abs(parts_tax_rates[key].prt_discp) > 1
|
|
? parts_tax_rates[key].prt_discp
|
|
: parts_tax_rates[key].prt_discp * 100;
|
|
|
|
disc = ret.parts.list[key].total.percentage(discountRate).multiply(-1);
|
|
}
|
|
}
|
|
if (
|
|
parts_tax_rates[key].prt_mkupp !== undefined &&
|
|
parts_tax_rates[key].prt_mkupp >= 0
|
|
) {
|
|
//Check if there's any parts in this part type.
|
|
if (ret.parts.list[key] !== undefined) {
|
|
markupRate =
|
|
Math.abs(parts_tax_rates[key].prt_mkupp) > 1
|
|
? parts_tax_rates[key].prt_mkupp
|
|
: parts_tax_rates[key].prt_mkupp * 100; //Seems that mark up is written as decimal not %.
|
|
|
|
markup = ret.parts.list[key].total.percentage(markupRate);
|
|
}
|
|
}
|
|
let adjustment = disc.add(markup);
|
|
adjustments[key] = adjustment;
|
|
|
|
const correspondingCiecaStlTotalLine = job.cieca_stl?.data.find(
|
|
(c) => c.ttl_typecd === key
|
|
);
|
|
|
|
//If the difference is greater than a penny, fix it.
|
|
|
|
if (
|
|
correspondingCiecaStlTotalLine &&
|
|
Math.abs(
|
|
ret.parts.list[key]?.total.getAmount() -
|
|
correspondingCiecaStlTotalLine.ttl_amt * 100
|
|
) > 1
|
|
) {
|
|
// Update the total.
|
|
console.log(
|
|
key,
|
|
ret.parts.list[key]?.total.getAmount(),
|
|
correspondingCiecaStlTotalLine?.ttl_amt
|
|
);
|
|
//Find the corresponding lines. Update the discount/markup for them.
|
|
|
|
console.warn("There's a difference! Type: ", key);
|
|
let totalDiscountToAdjustBy = Dinero();
|
|
job.joblines.forEach((jobline) => {
|
|
//Modify the line in place to add the mark up/discount.
|
|
if (jobline.part_type === key) {
|
|
const discountAmountDinero = Dinero({
|
|
amount: Math.round(jobline.act_price * 100),
|
|
}).percentage(discountRate);
|
|
|
|
const discountAmount = parseFloat(
|
|
discountAmountDinero.toFormat("0.00")
|
|
);
|
|
totalDiscountToAdjustBy =
|
|
totalDiscountToAdjustBy.add(discountAmountDinero);
|
|
jobline.prt_dsmk_m = discountAmount * -1;
|
|
jobline.prt_dsmk_p = discountRate * -1;
|
|
|
|
linesToAdjustForDiscount.push(jobline);
|
|
}
|
|
});
|
|
// ret.parts.list[key].total = ret.parts.list[key]?.total.subtract(
|
|
// totalDiscountToAdjustBy
|
|
// );
|
|
ret.parts.prt_dsmk_total = ret.parts.prt_dsmk_total.add(
|
|
totalDiscountToAdjustBy
|
|
);
|
|
ret.parts.subtotal = ret.parts.subtotal.subtract(totalDiscountToAdjustBy);
|
|
ret.parts.total = ret.parts.total.subtract(totalDiscountToAdjustBy);
|
|
}
|
|
});
|
|
|
|
//UpdateJobLines(linesToAdjustForDiscount.filter((l) => l.prt_dsmk_m !== 0));
|
|
|
|
return {
|
|
adjustments,
|
|
parts: {
|
|
...ret.parts,
|
|
total: ret.parts.subtotal,
|
|
},
|
|
sublets: {
|
|
...ret.sublets,
|
|
total: ret.sublets.subtotal,
|
|
},
|
|
};
|
|
}
|
|
|
|
function IsAdditionalCost(jobLine) {
|
|
//May be able to use db_ref here to help.
|
|
//936012 is Haz Waste Dispoal
|
|
//936008 is Paint/Materials
|
|
//936007 is Shop/Materials
|
|
|
|
//Remove paint and shop mat lines. They're calculated under rates.
|
|
const isPaintOrShopMat =
|
|
jobLine.db_ref === "936008" || jobLine.db_ref === "936007";
|
|
|
|
return (
|
|
(jobLine.lbr_op === "OP13" || //Added to resolve manual job lines coming into other totals because they have no reference.
|
|
(jobLine.part_type === null && (jobLine.act_price || 0 > 0)) ||
|
|
(jobLine.db_ref && jobLine.db_ref.startsWith("9360"))) && //This ref works in Canada, but DB_REFS in the US do not fill in.
|
|
!isPaintOrShopMat
|
|
);
|
|
}
|
|
|
|
function CalculateAdditional(job) {
|
|
let ret = {
|
|
additionalCosts: null,
|
|
additionalCostItems: [],
|
|
adjustments: null,
|
|
towing: null,
|
|
shipping: Dinero(),
|
|
storage: null,
|
|
pvrt: null,
|
|
total: null,
|
|
};
|
|
ret.towing = Dinero({
|
|
amount: Math.round((job.towing_payable || 0) * 100),
|
|
});
|
|
|
|
ret.additionalCosts = job.joblines
|
|
.filter((jl) => !jl.removed && IsAdditionalCost(jl))
|
|
.reduce((acc, val) => {
|
|
const lineValue = Dinero({
|
|
amount: Math.round((val.act_price || 0) * 100),
|
|
}).multiply(val.part_qty);
|
|
|
|
if (val.db_ref === "936004") {
|
|
//Shipping line IO-1921.
|
|
ret.shipping = ret.shipping.add(lineValue);
|
|
}
|
|
|
|
if (val.line_desc.toLowerCase().includes("towing")) {
|
|
ret.towing = lineValue;
|
|
return acc;
|
|
} else {
|
|
ret.additionalCostItems.push({ key: val.line_desc, total: lineValue });
|
|
return acc.add(lineValue);
|
|
}
|
|
}, Dinero());
|
|
ret.adjustments = Dinero({
|
|
amount: Math.round((job.adjustment_bottom_line || 0) * 100),
|
|
});
|
|
ret.storage = Dinero({
|
|
amount: Math.round((job.storage_payable || 0) * 100),
|
|
});
|
|
ret.pvrt = Dinero({
|
|
amount: Math.round((job.ca_bc_pvrt || 0) * 100),
|
|
});
|
|
ret.total = ret.additionalCosts
|
|
.add(ret.adjustments) //IO-813 Adjustment takes care of GST & PST at labor rate.
|
|
.add(ret.towing)
|
|
.add(ret.storage);
|
|
|
|
return ret;
|
|
}
|
|
|
|
function CalculateTaxesTotals(job, otherTotals) {
|
|
const subtotal = otherTotals.parts.parts.subtotal
|
|
.add(otherTotals.parts.sublets.subtotal)
|
|
.add(otherTotals.rates.subtotal) //No longer using just rates subtotal to include mapa/mash.
|
|
.add(otherTotals.additional.total);
|
|
|
|
// .add(Dinero({ amount: (job.towing_payable || 0) * 100 }))
|
|
// .add(Dinero({ amount: (job.storage_payable || 0) * 100 }));
|
|
|
|
//Potential issue here with Sublet Calculation. Sublets are calculated under labor in Mitchell, but it's done in IO
|
|
//Under the parts rates.
|
|
|
|
let statePartsTax = Dinero();
|
|
let additionalItemsTax = Dinero();
|
|
|
|
//Audatex sends additional glass part types. IO-774
|
|
const BackupGlassTax =
|
|
job.parts_tax_rates &&
|
|
(job.parts_tax_rates.PAGD ||
|
|
job.parts_tax_rates.PAGF ||
|
|
job.parts_tax_rates.PAGP ||
|
|
job.parts_tax_rates.PAGQ ||
|
|
job.parts_tax_rates.PAGR);
|
|
|
|
const taxableAmounts = {
|
|
PAA: Dinero(),
|
|
PAN: Dinero(),
|
|
PAL: Dinero(),
|
|
PAR: Dinero(),
|
|
PAC: Dinero(),
|
|
PAG: Dinero(),
|
|
PAO: Dinero(),
|
|
PAS: Dinero(),
|
|
PAP: Dinero(),
|
|
PAM: Dinero(),
|
|
};
|
|
|
|
//For each line, determine if it's taxable, and if it is, add the line amount to the taxable amounts total.
|
|
job.joblines
|
|
.filter((jl) => !jl.removed)
|
|
.forEach((val) => {
|
|
if (!val.tax_part) return;
|
|
if (!val.part_type && IsAdditionalCost(val)) {
|
|
taxableAmounts.PAO = taxableAmounts.PAO.add(
|
|
Dinero({ amount: Math.round((val.act_price || 0) * 100) }).multiply(
|
|
val.part_qty || 0
|
|
)
|
|
);
|
|
} else if (!val.part_type) {
|
|
//Do nothing for now.
|
|
} else {
|
|
const typeOfPart = val.part_type === "PAM" ? "PAC" : val.part_type;
|
|
taxableAmounts[typeOfPart] = taxableAmounts[typeOfPart].add(
|
|
Dinero({ amount: Math.round((val.act_price || 0) * 100) })
|
|
.multiply(val.part_qty || 0)
|
|
.add(
|
|
val.prt_dsmk_m &&
|
|
val.prt_dsmk_m !== 0 &&
|
|
DiscountNotAlreadyCounted(val, job.joblines)
|
|
? val.prt_dsmk_m
|
|
? Dinero({ amount: Math.round(val.prt_dsmk_m * 100) })
|
|
: Dinero({
|
|
amount: Math.round(val.act_price * 100),
|
|
})
|
|
.multiply(val.part_qty || 0)
|
|
.percentage(Math.abs(val.prt_dsmk_p || 0))
|
|
.multiply(val.prt_dsmk_p > 0 ? 1 : -1)
|
|
: Dinero()
|
|
)
|
|
);
|
|
}
|
|
});
|
|
|
|
//Taxable amounts should match with what is in the STL file.
|
|
//Now that we have the taxable amounts, apply the tax.
|
|
|
|
const tieredTaxAmounts = {
|
|
ty1Tax: Dinero(),
|
|
ty2Tax: Dinero(),
|
|
ty3Tax: Dinero(),
|
|
ty4Tax: Dinero(),
|
|
ty5Tax: Dinero(),
|
|
ty6Tax: Dinero(),
|
|
};
|
|
|
|
const remainingTaxableAmounts = taxableAmounts;
|
|
console.log("Taxable Amounts");
|
|
console.table(JSON.parse(JSON.stringify(taxableAmounts)));
|
|
Object.keys(taxableAmounts).forEach((part_type) => {
|
|
//Check it's taxability in the PFP
|
|
try {
|
|
const pfp = job.parts_tax_rates;
|
|
|
|
const typeOfPart = part_type === "PAM" ? "PAC" : part_type;
|
|
if (IsTrueOrYes(pfp[typeOfPart].prt_tax_in)) {
|
|
//At least one of these scenarios must be taxable.
|
|
for (let tyCounter = 1; tyCounter <= 5; tyCounter++) {
|
|
if (IsTrueOrYes(pfp[typeOfPart][`prt_tx_in${tyCounter}`])) {
|
|
//i represents the tax number. If we got here, this type of tax is applicable. Now we need to add based on the thresholds.
|
|
for (let threshCounter = 1; threshCounter <= 5; threshCounter++) {
|
|
const thresholdAmount = parseFloat(
|
|
job.cieca_pft[`ty${tyCounter}_thres${threshCounter}`]
|
|
);
|
|
const thresholdTaxRate = parseFloat(
|
|
job.cieca_pft[`ty${tyCounter}_rate${threshCounter}`]
|
|
);
|
|
|
|
let taxableAmountInThisThreshold;
|
|
if (thresholdAmount === 9999.99) {
|
|
// THis is the last threshold. Tax the entire remaining amount.
|
|
taxableAmountInThisThreshold =
|
|
remainingTaxableAmounts[typeOfPart];
|
|
remainingTaxableAmounts[typeOfPart] = Dinero();
|
|
} else {
|
|
if (
|
|
thresholdAmount >=
|
|
remainingTaxableAmounts[typeOfPart].getAmount() / 100
|
|
) {
|
|
//This threshold is bigger than the remaining taxable balance. Add it all.
|
|
taxableAmountInThisThreshold =
|
|
remainingTaxableAmounts[typeOfPart];
|
|
remainingTaxableAmounts[typeOfPart] = Dinero();
|
|
} else {
|
|
//Take the size of the threshold from the remaining amount, tax it, and do it all over.
|
|
taxableAmountInThisThreshold = Dinero({
|
|
amount: Math.round(thresholdAmount * 100),
|
|
});
|
|
remainingTaxableAmounts[typeOfPart] = remainingTaxableAmounts[
|
|
typeOfPart
|
|
].subtract(
|
|
Dinero({
|
|
amount: Math.round(taxableAmountInThisThreshold * 100),
|
|
})
|
|
);
|
|
}
|
|
}
|
|
|
|
const taxAmountToAdd =
|
|
taxableAmountInThisThreshold.percentage(thresholdTaxRate);
|
|
|
|
tieredTaxAmounts[`ty${tyCounter}Tax`] =
|
|
tieredTaxAmounts[`ty${tyCounter}Tax`].add(taxAmountToAdd);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error("Shit the bed.");
|
|
}
|
|
});
|
|
|
|
statePartsTax = statePartsTax
|
|
.add(tieredTaxAmounts.ty1Tax)
|
|
.add(tieredTaxAmounts.ty2Tax)
|
|
.add(tieredTaxAmounts.ty3Tax)
|
|
.add(tieredTaxAmounts.ty4Tax)
|
|
.add(tieredTaxAmounts.ty5Tax)
|
|
.add(tieredTaxAmounts.ty6Tax);
|
|
console.log("Tiered Taxes Total for Parts", statePartsTax.toFormat());
|
|
let laborTaxTotal = Dinero();
|
|
|
|
if (Object.keys(job.cieca_pfl).length > 0) {
|
|
//Do it by labor type
|
|
const types = [
|
|
"la1",
|
|
"la2",
|
|
"la3",
|
|
"la4",
|
|
"lau",
|
|
"laa",
|
|
"lab",
|
|
"lad",
|
|
"lae",
|
|
"laf",
|
|
"lag",
|
|
"lam",
|
|
"lar",
|
|
"las",
|
|
];
|
|
types.forEach((type) => {
|
|
laborTaxTotal = laborTaxTotal.add(
|
|
otherTotals.rates[type].total.percentage(
|
|
job.cieca_pfl[type.toUpperCase()]
|
|
? job.cieca_pfl[type.toUpperCase()].lbr_taxp
|
|
: (job.tax_lbr_rt || 0) * 100
|
|
)
|
|
);
|
|
});
|
|
} else {
|
|
//We don't have it, just add in how it was before.
|
|
laborTaxTotal = otherTotals.rates.subtotal.percentage(
|
|
(job.tax_lbr_rt || 0) * 100
|
|
); // THis is currently using the lbr tax rate from PFH not PFL.
|
|
}
|
|
|
|
console.log("Labor Tax Total", laborTaxTotal.toFormat());
|
|
let ret = {
|
|
subtotal: subtotal,
|
|
federal_tax: subtotal
|
|
.percentage((job.federal_tax_rate || 0) * 100)
|
|
.add(
|
|
otherTotals.additional.pvrt.percentage(
|
|
(job.federal_tax_rate || 0) * 100
|
|
)
|
|
),
|
|
statePartsTax,
|
|
state_tax: statePartsTax
|
|
.add(laborTaxTotal)
|
|
.add(
|
|
otherTotals.additional.adjustments.percentage(
|
|
(job.tax_lbr_rt || 0) * 100
|
|
)
|
|
)
|
|
.add(
|
|
otherTotals.additional.towing.percentage((job.tax_tow_rt || 0) * 100)
|
|
)
|
|
.add(
|
|
otherTotals.additional.storage.percentage((job.tax_str_rt || 0) * 100)
|
|
)
|
|
// .add(additionalItemsTax)
|
|
.add(
|
|
otherTotals.rates.mapa.hasMapaLine === false //If parts and materials were not added as lines, we must calculate the taxes on them.
|
|
? otherTotals.rates.mapa.total.percentage(
|
|
(job.tax_paint_mat_rt || 0) * 100
|
|
)
|
|
: Dinero()
|
|
)
|
|
.add(
|
|
otherTotals.rates.mash.hasMashLine === false //If parts and materials were not added as lines, we must calculate the taxes on them.
|
|
? otherTotals.rates.mash.total.percentage(
|
|
(job.tax_shop_mat_rt || 0) * 100
|
|
)
|
|
: Dinero()
|
|
),
|
|
|
|
local_tax: subtotal.percentage((job.local_tax_rate || 0) * 100),
|
|
};
|
|
ret.total_repairs = ret.subtotal
|
|
.add(ret.federal_tax)
|
|
.add(ret.state_tax)
|
|
.add(ret.local_tax)
|
|
.add(otherTotals.additional.pvrt);
|
|
|
|
ret.custPayable = {
|
|
deductible: Dinero({ amount: Math.round((job.ded_amt || 0) * 100) }) || 0,
|
|
federal_tax: job.ca_gst_registrant
|
|
? job.ca_customer_gst === 0 || job.ca_customer_gst === null
|
|
? ret.federal_tax
|
|
: Dinero({ amount: Math.round(job.ca_customer_gst * 100) })
|
|
: Dinero(),
|
|
other_customer_amount: Dinero({
|
|
amount: Math.round((job.other_amount_payable || 0) * 100),
|
|
}),
|
|
dep_taxes: Dinero({
|
|
amount: Math.round((job.depreciation_taxes || 0) * 100),
|
|
}),
|
|
};
|
|
|
|
ret.custPayable.total = ret.custPayable.deductible
|
|
.add(ret.custPayable.federal_tax)
|
|
.add(ret.custPayable.other_customer_amount)
|
|
.add(ret.custPayable.dep_taxes);
|
|
|
|
ret.net_repairs = ret.total_repairs.subtract(ret.custPayable.total);
|
|
|
|
return ret;
|
|
}
|
|
|
|
exports.default = Totals;
|
|
|
|
function DiscountNotAlreadyCounted(jobline, joblines) {
|
|
//CCC already factors in the discount. If the difference between the 2 is exactly the discount, it's all good.
|
|
if (
|
|
Math.round(
|
|
(jobline.prt_dsmk_m / (jobline.act_price - jobline.prt_dsmk_m)) * 100
|
|
) === Math.abs(jobline.prt_dsmk_p)
|
|
) {
|
|
return false;
|
|
}
|
|
|
|
//Check it against the database price too? If it's an OE part.
|
|
// if (
|
|
// Math.abs(jobline.db_price - jobline.act_price) -
|
|
// Math.abs(jobline.prt_dsmk_m) <
|
|
// 0.01
|
|
// ) {
|
|
// return false;
|
|
// }
|
|
|
|
if (
|
|
//If it's not a discount line, then it definitely hasn't been counted yet.
|
|
jobline.db_ref !== "900510" &&
|
|
jobline.db_ref !== "900511"
|
|
)
|
|
return true;
|
|
|
|
const ParentLine = joblines.find((j) => j.unq_seq === jobline.line_ref);
|
|
|
|
return ParentLine && !(ParentLine.prt_dsmk_m && ParentLine.prt_dsmk_m !== 0);
|
|
}
|
|
|
|
exports.DiscountNotAlreadyCounted = DiscountNotAlreadyCounted;
|
|
|
|
function ParseCalopCode(opcode) {
|
|
if (!opcode) return [];
|
|
return opcode.trim().split(" ");
|
|
}
|
|
|
|
function IsTrueOrYes(value) {
|
|
return value === true || value === "Y" || value === "y";
|
|
}
|
|
|
|
async function UpdateJobLines(joblinesToUpdate) {
|
|
if (joblinesToUpdate.length === 0) return;
|
|
const updateQueries = joblinesToUpdate.map((line, index) =>
|
|
generateUpdateQuery(_.pick(line, ["id", "prt_dsmk_m", "prt_dsmk_p"]), index)
|
|
);
|
|
const query = `
|
|
mutation UPDATE_EST_LINES{
|
|
${updateQueries}
|
|
}
|
|
`;
|
|
|
|
const result = await adminClient.request(query);
|
|
}
|
|
|
|
const generateUpdateQuery = (lineToUpdate, index) => {
|
|
return `
|
|
update_joblines${index}: update_joblines(where: { id: { _eq: "${
|
|
lineToUpdate.id
|
|
}" } }, _set: ${JSON.stringify(lineToUpdate).replace(
|
|
/"(\w+)"\s*:/g,
|
|
"$1:"
|
|
)}) {
|
|
returning {
|
|
id
|
|
}
|
|
}`;
|
|
};
|