feat(dm): abbott trucklist will do orders and forecast now

This commit is contained in:
2025-12-11 15:56:34 -06:00
parent 2b5e77993b
commit 501709546d
2 changed files with 246 additions and 151 deletions

View File

@@ -1 +1,96 @@
export const abbottForecast = async () => {}; import XLSX from "xlsx";
import { db } from "../../../../../../../database/dbclient.js";
import { settings } from "../../../../../../../database/schema/settings.js";
import { delay } from "../../../../../../globalUtils/delay.js";
import { tryCatch } from "../../../../../../globalUtils/tryCatch.js";
import { excelDateStuff } from "../../../../utils/excelDateStuff.js";
import { postForecast } from "../postForecast.js";
export const abbottForecast = async (sheet: any, user: any) => {
const customerId = 8;
const posting: any = [];
const { data: s, error: e } = await tryCatch(db.select().from(settings));
if (e) {
return {
success: false,
message: `Error getting settings`,
data: e,
};
}
const plantToken = s.filter((s) => s.name === "plantToken");
const customHeaders = [
"date",
"time",
"newton8oz",
"newton10oz",
"E",
"F",
"fDate",
"f8ozqty",
"I",
"J",
"K",
"L",
"M",
"f10ozqty",
];
const forecastData = XLSX.utils.sheet_to_json(sheet, {
range: 5, // Start at row 5 (index 4)
header: customHeaders,
defval: "", // Default value for empty cells
});
for (let i = 1; i < forecastData.length; i++) {
const row: any = forecastData[i];
//console.log(row);
//if (row.fDate == undefined) continue;
if (row.fDate !== "") {
const date = isNaN(row.fDate)
? new Date(row.fDate)
: excelDateStuff(row.fDate);
// for 8oz do
if (row.f8ozqty > 0) {
posting.push({
customerArticleNo: "45300DA",
quantity: row.f8ozqty,
requirementDate: date,
});
}
if (row.f10ozqty > 0) {
posting.push({
customerArticleNo: "43836DA",
quantity: row.f10ozqty,
requirementDate: date,
});
}
}
}
// the predefined data that will never change
const predefinedObject = {
receivingPlantId: plantToken[0].value,
documentName: `ForecastFromLST-${new Date(Date.now()).toLocaleString(
"en-US",
)}`,
sender: user.username || "lst-system",
customerId: customerId,
positions: [],
};
// add the new forecast to the predefined data
let updatedPredefinedObject = {
...predefinedObject,
positions: [...predefinedObject.positions, ...posting],
};
const forecast: any = await postForecast(updatedPredefinedObject, user);
return {
success: forecast.success,
message: forecast.message,
data: forecast.data,
};
};

View File

@@ -1,12 +1,13 @@
import { addDays, addHours, isAfter, parse } from "date-fns";
import XLSX from "xlsx"; import XLSX from "xlsx";
import { excelDateStuff } from "../../../../utils/excelDateStuff.js";
import { tryCatch } from "../../../../../../globalUtils/tryCatch.js";
import { db } from "../../../../../../../database/dbclient.js"; import { db } from "../../../../../../../database/dbclient.js";
import { settings } from "../../../../../../../database/schema/settings.js"; import { settings } from "../../../../../../../database/schema/settings.js";
import { tryCatch } from "../../../../../../globalUtils/tryCatch.js";
import { query } from "../../../../../sqlServer/prodSqlServer.js"; import { query } from "../../../../../sqlServer/prodSqlServer.js";
import { bulkOrderArticleInfo } from "../../../../../sqlServer/querys/dm/bulkOrderArticleInfo.js"; import { bulkOrderArticleInfo } from "../../../../../sqlServer/querys/dm/bulkOrderArticleInfo.js";
import { addDays, addHours, isAfter, parse } from "date-fns";
import { orderState } from "../../../../../sqlServer/querys/dm/orderState.js"; import { orderState } from "../../../../../sqlServer/querys/dm/orderState.js";
import { excelDateStuff } from "../../../../utils/excelDateStuff.js";
import { abbottForecast } from "../../forecast/mappings/abbott.js";
import { postOrders } from "../postOrders.js"; import { postOrders } from "../postOrders.js";
// customeris/articles stuff will be in basis once we move to iowa // customeris/articles stuff will be in basis once we move to iowa
@@ -14,171 +15,170 @@ let customerID = 8;
let invoiceID = 9; let invoiceID = 9;
let articles = "118,120"; let articles = "118,120";
export const abbottOrders = async (data: any, user: any) => { export const abbottOrders = async (data: any, user: any) => {
/** /**
* Standard orders meaning that we get the standard file exported and fill it out and uplaod to lst. * Standard orders meaning that we get the standard file exported and fill it out and uplaod to lst.
*/ */
const { data: s, error: e } = await tryCatch(db.select().from(settings)); const { data: s, error: e } = await tryCatch(db.select().from(settings));
if (e) { if (e) {
return { return {
sucess: false, sucess: false,
message: `Error getting settings`, message: `Error getting settings`,
data: e, data: e,
}; };
} }
// articleInfo // articleInfo
const { data: article, error: ae } = await tryCatch( const { data: article, error: ae } = await tryCatch(
query( query(
bulkOrderArticleInfo.replace("[articles]", articles), bulkOrderArticleInfo.replace("[articles]", articles),
"Get Article data for bulk orders" "Get Article data for bulk orders",
) ),
); );
const a: any = article?.data; const a: any = article?.data;
if (ae) { if (ae) {
return { return {
sucess: false, sucess: false,
message: `Error getting article data`, message: `Error getting article data`,
data: ae, data: ae,
}; };
} }
// order state // order state
const { data: o, error: oe } = await tryCatch( const { data: o, error: oe } = await tryCatch(
query(orderState, "Gets the next 500 orders that have not been started") query(orderState, "Gets the next 500 orders that have not been started"),
); );
const openOrders: any = o?.data; const openOrders: any = o?.data;
if (oe) { if (oe) {
return { return {
sucess: false, sucess: false,
message: `Error getting article data`, message: `Error getting article data`,
data: oe, data: oe,
}; };
} }
const plantToken = s.filter((s) => s.name === "plantToken"); const plantToken = s.filter((s) => s.name === "plantToken");
const arrayBuffer = await data.arrayBuffer(); const arrayBuffer = await data.arrayBuffer();
const buffer = Buffer.from(arrayBuffer); const buffer = Buffer.from(arrayBuffer);
const workbook = XLSX.read(buffer, { type: "buffer" }); const workbook = XLSX.read(buffer, { type: "buffer" });
const sheetName = workbook.SheetNames[0]; const sheetName = workbook.SheetNames[0];
const sheet = workbook.Sheets[sheetName]; const sheet = workbook.Sheets[sheetName];
// Define custom headers abbottForecast(sheet, user);
const customHeaders = ["date", "time", "newton8oz", "newton10oz"]; // Define custom headers
const orderData = XLSX.utils.sheet_to_json(sheet, { const customHeaders = ["date", "time", "newton8oz", "newton10oz"];
range: 5, // Start at row 5 (index 4) const orderData = XLSX.utils.sheet_to_json(sheet, {
header: customHeaders, range: 5, // Start at row 5 (index 4)
defval: "", // Default value for empty cells header: customHeaders,
}); defval: "", // Default value for empty cells
});
// the base of the import // the base of the import
const predefinedObject = { const predefinedObject = {
receivingPlantId: plantToken[0].value, receivingPlantId: plantToken[0].value,
documentName: `OrdersFromLST-${new Date(Date.now()).toLocaleString( documentName: `OrdersFromLST-${new Date(Date.now()).toLocaleString(
"en-US" "en-US",
)}`, )}`,
sender: user.username || "lst-system", sender: user.username || "lst-system",
externalRefNo: `OrdersFromLST-${new Date(Date.now()).toLocaleString( externalRefNo: `OrdersFromLST-${new Date(Date.now()).toLocaleString(
"en-US" "en-US",
)}`, )}`,
orders: [], orders: [],
}; };
const oOrders: any = openOrders; const oOrders: any = openOrders;
let correctedOrders: any = orderData let correctedOrders: any = orderData
.filter( .filter(
(o: any) => (o: any) =>
(o.newton8oz && o.newton8oz.trim() !== "") || (o.newton8oz && o.newton8oz.trim() !== "") ||
(o.newton10oz && o.newton10oz.trim() !== "") (o.newton10oz && o.newton10oz.trim() !== ""),
) )
.map((o: any) => ({ .map((o: any) => ({
date: excelDateStuff(o.date, o.time), date: excelDateStuff(o.date, o.time),
po: po:
o.newton8oz.replace(/\s+/g, "") !== "" o.newton8oz.replace(/\s+/g, "") !== ""
? o.newton8oz.replace(/\s+/g, "") ? o.newton8oz.replace(/\s+/g, "")
: o.newton10oz.replace(/\s+/g, ""), : o.newton10oz.replace(/\s+/g, ""),
customerArticlenumber: customerArticlenumber:
o.newton8oz != "" o.newton8oz != ""
? a.filter((a: any) => a.av === 118)[0] ? a.filter((a: any) => a.av === 118)[0].CustomerArticleNumber
.CustomerArticleNumber : a.filter((a: any) => a.av === 120)[0].CustomerArticleNumber,
: a.filter((a: any) => a.av === 120)[0] qty:
.CustomerArticleNumber, o.newton8oz != ""
qty: ? a.filter((a: any) => a.av === 118)[0].totalTruckLoad
o.newton8oz != "" : a.filter((a: any) => a.av === 120)[0].totalTruckLoad,
? a.filter((a: any) => a.av === 118)[0].totalTruckLoad }));
: a.filter((a: any) => a.av === 120)[0].totalTruckLoad,
}));
// now we want to make sure we only correct orders that or after now // now we want to make sure we only correct orders that or after now
correctedOrders = correctedOrders.filter((o: any) => { correctedOrders = correctedOrders.filter((o: any) => {
const parsedDate = parse(o.date, "M/d/yyyy, h:mm:ss a", new Date()); const parsedDate = parse(o.date, "M/d/yyyy, h:mm:ss a", new Date());
return isAfter(o.date, new Date().toISOString()); return isAfter(o.date, new Date().toISOString());
}); });
// last map to remove orders that have already been started // last map to remove orders that have already been started
// correctedOrders = correctedOrders.filter((oo: any) => // correctedOrders = correctedOrders.filter((oo: any) =>
// oOrders.some((o: any) => o.CustomerOrderNumber === oo.po) // oOrders.some((o: any) => o.CustomerOrderNumber === oo.po)
// ); // );
let postedOrders: any = []; let postedOrders: any = [];
const filterOrders: any = correctedOrders; const filterOrders: any = correctedOrders;
filterOrders.forEach((oo: any) => { filterOrders.forEach((oo: any) => {
const isMatch = openOrders.some( const isMatch = openOrders.some(
(o: any) => String(o.po).trim() === String(oo.po).trim() (o: any) => String(o.po).trim() === String(oo.po).trim(),
); );
if (!isMatch) { if (!isMatch) {
//console.log(`ok to update: ${oo.po}`); //console.log(`ok to update: ${oo.po}`);
// oo = { // oo = {
// ...oo, // ...oo,
// CustomerOrderNumber: oo.CustomerOrderNumber.replace(" ", ""), // CustomerOrderNumber: oo.CustomerOrderNumber.replace(" ", ""),
// }; // };
postedOrders.push(oo); postedOrders.push(oo);
} else { } else {
// console.log(`Not valid order to update: ${oo.po}`); // console.log(`Not valid order to update: ${oo.po}`);
//console.log(oo) //console.log(oo)
} }
}); });
// Map Excel data to predefinedObject format // Map Excel data to predefinedObject format
const orders = filterOrders.map((o: any) => { const orders = filterOrders.map((o: any) => {
return { return {
customerId: customerID, customerId: customerID,
invoiceAddressId: invoiceID, invoiceAddressId: invoiceID,
customerOrderNo: o.po, customerOrderNo: o.po,
orderDate: new Date(Date.now()).toLocaleString("en-US"), orderDate: new Date(Date.now()).toLocaleString("en-US"),
positions: [ positions: [
{ {
deliveryAddressId: 8, deliveryAddressId: 8,
customerArticleNo: o.customerArticlenumber, customerArticleNo: o.customerArticlenumber,
quantity: o.qty, quantity: o.qty,
deliveryDate: addHours(addDays(o.date, 1), 1), // adding this in so we can over come the constant 1 day behind thing as a work around deliveryDate: addHours(addDays(o.date, 1), 1), // adding this in so we can over come the constant 1 day behind thing as a work around
customerLineItemNo: 1, // this is how it is currently sent over from abbott customerLineItemNo: 1, // this is how it is currently sent over from abbott
customerReleaseNo: 1, // same as above customerReleaseNo: 1, // same as above
}, },
], ],
}; };
}); });
// combine it all together. // combine it all together.
const updatedPredefinedObject = { const updatedPredefinedObject = {
...predefinedObject, ...predefinedObject,
orders: [...predefinedObject.orders, ...orders], orders: [...predefinedObject.orders, ...orders],
}; };
//console.log(updatedPredefinedObject); //console.log(updatedPredefinedObject);
// post the orders to the server // post the orders to the server
const posting = await postOrders(updatedPredefinedObject, user); const posting = await postOrders(updatedPredefinedObject, user);
//console.log(posting); //console.log(posting);
return { return {
success: posting?.success, success: posting?.success,
message: posting?.message, message: posting?.message,
data: posting, data: posting,
}; };
}; };