feat(lstv2 move): moved lstv2 into this app to keep them combined and easier to maintain
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
import * as XLSX from "xlsx";
|
||||
|
||||
export const standardTemplate = async () => {
|
||||
/**
|
||||
* Creates the standard Template for bulk orders in
|
||||
*/
|
||||
|
||||
const headers = [
|
||||
[
|
||||
"CustomerArticleNumber",
|
||||
"CustomerOrderNumber",
|
||||
"CustomerLineNumber",
|
||||
"CustomerRealeaseNumber",
|
||||
"Quantity",
|
||||
"DeliveryDate",
|
||||
"CustomerID",
|
||||
"Remark",
|
||||
// "InvoiceID",
|
||||
],
|
||||
];
|
||||
|
||||
// create a new workbook
|
||||
const wb = XLSX.utils.book_new();
|
||||
const ws = XLSX.utils.aoa_to_sheet(headers);
|
||||
//const ws2 = XLSX.utils.aoa_to_sheet(headers2);
|
||||
|
||||
const columnWidths = headers[0].map((header) => ({
|
||||
width: header.length + 2,
|
||||
}));
|
||||
|
||||
ws["!cols"] = columnWidths;
|
||||
|
||||
// append the worksheet to the workbook
|
||||
XLSX.utils.book_append_sheet(wb, ws, `Sheet1`);
|
||||
//XLSX.utils.book_append_sheet(wb, ws2, `Sheet2`);
|
||||
|
||||
// Write the excel file and trigger the download'
|
||||
XLSX.writeFile(wb, "BulkOrdersTemplate");
|
||||
|
||||
// Write the workbook to a buffer and return it
|
||||
const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "buffer" });
|
||||
|
||||
return excelBuffer;
|
||||
};
|
||||
@@ -0,0 +1,184 @@
|
||||
import XLSX from "xlsx";
|
||||
import { excelDateStuff } from "../../../../utils/excelDateStuff.js";
|
||||
import { tryCatch } from "../../../../../../globalUtils/tryCatch.js";
|
||||
import { db } from "../../../../../../../database/dbclient.js";
|
||||
import { settings } from "../../../../../../../database/schema/settings.js";
|
||||
import { query } from "../../../../../sqlServer/prodSqlServer.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 { postOrders } from "../postOrders.js";
|
||||
|
||||
// customeris/articles stuff will be in basis once we move to iowa
|
||||
let customerID = 8;
|
||||
let invoiceID = 9;
|
||||
let articles = "118,120";
|
||||
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.
|
||||
*/
|
||||
|
||||
const { data: s, error: e } = await tryCatch(db.select().from(settings));
|
||||
|
||||
if (e) {
|
||||
return {
|
||||
sucess: false,
|
||||
message: `Error getting settings`,
|
||||
data: e,
|
||||
};
|
||||
}
|
||||
|
||||
// articleInfo
|
||||
const { data: article, error: ae } = await tryCatch(
|
||||
query(
|
||||
bulkOrderArticleInfo.replace("[articles]", articles),
|
||||
"Get Article data for bulk orders"
|
||||
)
|
||||
);
|
||||
const a: any = article?.data;
|
||||
if (ae) {
|
||||
return {
|
||||
sucess: false,
|
||||
message: `Error getting article data`,
|
||||
data: ae,
|
||||
};
|
||||
}
|
||||
|
||||
// order state
|
||||
const { data: o, error: oe } = await tryCatch(
|
||||
query(orderState, "Gets the next 500 orders that have not been started")
|
||||
);
|
||||
|
||||
const openOrders: any = o?.data;
|
||||
|
||||
if (oe) {
|
||||
return {
|
||||
sucess: false,
|
||||
message: `Error getting article data`,
|
||||
data: oe,
|
||||
};
|
||||
}
|
||||
|
||||
const plantToken = s.filter((s) => s.name === "plantToken");
|
||||
|
||||
const arrayBuffer = await data.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
|
||||
const workbook = XLSX.read(buffer, { type: "buffer" });
|
||||
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
|
||||
// Define custom headers
|
||||
const customHeaders = ["date", "time", "newton8oz", "newton10oz"];
|
||||
const orderData = XLSX.utils.sheet_to_json(sheet, {
|
||||
range: 5, // Start at row 5 (index 4)
|
||||
header: customHeaders,
|
||||
defval: "", // Default value for empty cells
|
||||
});
|
||||
|
||||
// the base of the import
|
||||
const predefinedObject = {
|
||||
receivingPlantId: plantToken[0].value,
|
||||
documentName: `OrdersFromLST-${new Date(Date.now()).toLocaleString(
|
||||
"en-US"
|
||||
)}`,
|
||||
sender: user.username || "lst-system",
|
||||
externalRefNo: `OrdersFromLST-${new Date(Date.now()).toLocaleString(
|
||||
"en-US"
|
||||
)}`,
|
||||
orders: [],
|
||||
};
|
||||
const oOrders: any = openOrders;
|
||||
|
||||
let correctedOrders: any = orderData
|
||||
.filter(
|
||||
(o: any) =>
|
||||
(o.newton8oz && o.newton8oz.trim() !== "") ||
|
||||
(o.newton10oz && o.newton10oz.trim() !== "")
|
||||
)
|
||||
.map((o: any) => ({
|
||||
date: excelDateStuff(o.date, o.time),
|
||||
po:
|
||||
o.newton8oz.replace(/\s+/g, "") !== ""
|
||||
? o.newton8oz.replace(/\s+/g, "")
|
||||
: o.newton10oz.replace(/\s+/g, ""),
|
||||
customerArticlenumber:
|
||||
o.newton8oz != ""
|
||||
? a.filter((a: any) => a.av === 118)[0]
|
||||
.CustomerArticleNumber
|
||||
: a.filter((a: any) => a.av === 120)[0]
|
||||
.CustomerArticleNumber,
|
||||
qty:
|
||||
o.newton8oz != ""
|
||||
? 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
|
||||
correctedOrders = correctedOrders.filter((o: any) => {
|
||||
const parsedDate = parse(o.date, "M/d/yyyy, h:mm:ss a", new Date());
|
||||
return isAfter(o.date, new Date().toISOString());
|
||||
});
|
||||
|
||||
// last map to remove orders that have already been started
|
||||
// correctedOrders = correctedOrders.filter((oo: any) =>
|
||||
// oOrders.some((o: any) => o.CustomerOrderNumber === oo.po)
|
||||
// );
|
||||
let postedOrders: any = [];
|
||||
const filterOrders: any = correctedOrders;
|
||||
filterOrders.forEach((oo: any) => {
|
||||
const isMatch = openOrders.some(
|
||||
(o: any) => String(o.po).trim() === String(oo.po).trim()
|
||||
);
|
||||
if (!isMatch) {
|
||||
//console.log(`ok to update: ${oo.po}`);
|
||||
|
||||
// oo = {
|
||||
// ...oo,
|
||||
// CustomerOrderNumber: oo.CustomerOrderNumber.replace(" ", ""),
|
||||
// };
|
||||
postedOrders.push(oo);
|
||||
} else {
|
||||
// console.log(`Not valid order to update: ${oo.po}`);
|
||||
//console.log(oo)
|
||||
}
|
||||
});
|
||||
|
||||
// Map Excel data to predefinedObject format
|
||||
const orders = filterOrders.map((o: any) => {
|
||||
return {
|
||||
customerId: customerID,
|
||||
invoiceAddressId: invoiceID,
|
||||
customerOrderNo: o.po,
|
||||
orderDate: new Date(Date.now()).toLocaleString("en-US"),
|
||||
positions: [
|
||||
{
|
||||
deliveryAddressId: 8,
|
||||
customerArticleNo: o.customerArticlenumber,
|
||||
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
|
||||
customerLineItemNo: 1, // this is how it is currently sent over from abbott
|
||||
customerReleaseNo: 1, // same as above
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
|
||||
// combine it all together.
|
||||
const updatedPredefinedObject = {
|
||||
...predefinedObject,
|
||||
orders: [...predefinedObject.orders, ...orders],
|
||||
};
|
||||
|
||||
//console.log(updatedPredefinedObject);
|
||||
// post the orders to the server
|
||||
const posting = await postOrders(updatedPredefinedObject, user);
|
||||
//console.log(posting);
|
||||
|
||||
return {
|
||||
success: posting?.success,
|
||||
message: posting?.message,
|
||||
data: posting,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,172 @@
|
||||
import XLSX from "xlsx";
|
||||
import { tryCatch } from "../../../../../../globalUtils/tryCatch.js";
|
||||
import { db } from "../../../../../../../database/dbclient.js";
|
||||
import { settings } from "../../../../../../../database/schema/settings.js";
|
||||
import { query } from "../../../../../sqlServer/prodSqlServer.js";
|
||||
import { orderState } from "../../../../../sqlServer/querys/dm/orderState.js";
|
||||
import { excelDateStuff } from "../../../../utils/excelDateStuff.js";
|
||||
import { invoiceAddress } from "../../../../../sqlServer/querys/dm/invoiceAddress.js";
|
||||
import { postOrders } from "../postOrders.js";
|
||||
|
||||
export const energizerOrders = async (data: any, user: any) => {
|
||||
/**
|
||||
* 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));
|
||||
|
||||
if (e) {
|
||||
return {
|
||||
sucess: false,
|
||||
message: `Error getting settings`,
|
||||
data: e,
|
||||
};
|
||||
}
|
||||
|
||||
// order state
|
||||
const { data: o, error: oe } = await tryCatch(
|
||||
query(orderState, "Gets the next 500 orders that have not been started")
|
||||
);
|
||||
|
||||
const openOrders: any = o?.data;
|
||||
|
||||
if (oe) {
|
||||
return {
|
||||
sucess: false,
|
||||
message: `Error getting article data`,
|
||||
data: oe,
|
||||
};
|
||||
}
|
||||
|
||||
// order state
|
||||
const { data: invoice, error: ie } = await tryCatch(
|
||||
query(invoiceAddress, "Gets invoices addresses")
|
||||
);
|
||||
const i: any = invoice?.data;
|
||||
|
||||
if (ie) {
|
||||
return {
|
||||
sucess: false,
|
||||
message: `Error getting invoice address data`,
|
||||
data: ie,
|
||||
};
|
||||
}
|
||||
const plantToken = s.filter((s) => s.name === "plantToken");
|
||||
|
||||
const arrayBuffer = await data.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
|
||||
const workbook = XLSX.read(buffer, { type: "buffer" });
|
||||
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
|
||||
// define custom headers
|
||||
const headers = [
|
||||
"ITEM",
|
||||
"PO",
|
||||
"ReleaseNo",
|
||||
"QTY",
|
||||
"DELDATE",
|
||||
"COMMENTS",
|
||||
"What changed",
|
||||
"CUSTOMERID",
|
||||
"Remark",
|
||||
];
|
||||
const orderData = XLSX.utils.sheet_to_json(sheet, {
|
||||
defval: "",
|
||||
header: headers,
|
||||
range: 1,
|
||||
});
|
||||
|
||||
// the base of the import
|
||||
const predefinedObject = {
|
||||
receivingPlantId: plantToken[0].value,
|
||||
documentName: `OrdersFromLST-${new Date(Date.now()).toLocaleString(
|
||||
"en-US"
|
||||
)}`,
|
||||
sender: user.username || "lst-system",
|
||||
externalRefNo: `OrdersFromLST-${new Date(Date.now()).toLocaleString(
|
||||
"en-US"
|
||||
)}`,
|
||||
orders: [],
|
||||
};
|
||||
|
||||
let newOrders: any = orderData;
|
||||
|
||||
// filter out the orders that have already been started just to reduce the risk of errors.
|
||||
newOrders.filter((oo: any) =>
|
||||
openOrders.some(
|
||||
(o: any) => o.CustomerOrderNumber === oo.CustomerOrderNumber
|
||||
)
|
||||
);
|
||||
|
||||
// filter out the blanks
|
||||
newOrders = newOrders.filter((z: any) => z.ITEM !== "");
|
||||
|
||||
// let postedOrders: any = [];
|
||||
// for (const [customerID, orders] of Object.entries(orderData)) {
|
||||
// // console.log(`Running for Customer ID: ${customerID}`);
|
||||
// const newOrders: any = orderData;
|
||||
|
||||
// // filter out the orders that have already been started just to reduce the risk of errors.
|
||||
// newOrders.filter((oo: any) =>
|
||||
// openOrders.some(
|
||||
// (o: any) => o.CustomerOrderNumber === oo.CustomerOrderNumber
|
||||
// )
|
||||
// );
|
||||
|
||||
// // map everything out for each order
|
||||
const nOrder = newOrders.map((o: any) => {
|
||||
const invoice = i.filter(
|
||||
(i: any) => i.deliveryAddress === parseInt(o.CUSTOMERID)
|
||||
);
|
||||
if (!invoice) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
customerId: parseInt(o.CUSTOMERID),
|
||||
invoiceAddressId: invoice[0].invoiceAddress, // matched to the default invoice address
|
||||
customerOrderNo: o.PO,
|
||||
orderDate: new Date(Date.now()).toLocaleString("en-US"),
|
||||
positions: [
|
||||
{
|
||||
deliveryAddressId: parseInt(o.CUSTOMERID),
|
||||
customerArticleNo: o.ITEM,
|
||||
quantity: parseInt(o.QTY),
|
||||
deliveryDate: o.DELDATE, //excelDateStuff(o.DELDATE),
|
||||
customerLineItemNo: o.ReleaseNo, // this is how it is currently sent over from abbott
|
||||
customerReleaseNo: o.ReleaseNo, // same as above
|
||||
remark: o.remark === "" ? null : o.remark,
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
|
||||
// // do that fun combining thing
|
||||
const updatedPredefinedObject = {
|
||||
...predefinedObject,
|
||||
orders: [...predefinedObject.orders, ...nOrder],
|
||||
};
|
||||
|
||||
// //console.log(updatedPredefinedObject);
|
||||
|
||||
// // post the orders to the server
|
||||
const posting: any = await postOrders(updatedPredefinedObject, user);
|
||||
|
||||
return {
|
||||
customer: nOrder[0].CUSTOMERID,
|
||||
//totalOrders: orders?.length(),
|
||||
success: posting.success,
|
||||
message: posting.message,
|
||||
data: posting.data,
|
||||
};
|
||||
// }
|
||||
|
||||
// return {
|
||||
// success: true,
|
||||
// message:
|
||||
// "Standard Template was just processed successfully, please check AlplaProd 2.0 to confirm no errors. ",
|
||||
// data: nOrder,
|
||||
// };
|
||||
};
|
||||
@@ -0,0 +1,200 @@
|
||||
import { delay } from "../../../../../../globalUtils/delay.js";
|
||||
import XLSX from "xlsx";
|
||||
import { tryCatch } from "../../../../../../globalUtils/tryCatch.js";
|
||||
import { db } from "../../../../../../../database/dbclient.js";
|
||||
import { settings } from "../../../../../../../database/schema/settings.js";
|
||||
import { query } from "../../../../../sqlServer/prodSqlServer.js";
|
||||
import { orderState } from "../../../../../sqlServer/querys/dm/orderState.js";
|
||||
import { excelDateStuff } from "../../../../utils/excelDateStuff.js";
|
||||
import { invoiceAddress } from "../../../../../sqlServer/querys/dm/invoiceAddress.js";
|
||||
import { postOrders } from "../postOrders.js";
|
||||
|
||||
export const macroImportOrders = async (data: any, user: any) => {
|
||||
/**
|
||||
* 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));
|
||||
|
||||
if (e) {
|
||||
return {
|
||||
sucess: false,
|
||||
message: `Error getting settings`,
|
||||
data: e,
|
||||
};
|
||||
}
|
||||
|
||||
// order state
|
||||
const { data: o, error: oe } = await tryCatch(
|
||||
query(orderState, "Gets the next 500 orders that have not been started")
|
||||
);
|
||||
|
||||
const openOrders: any = o?.data;
|
||||
|
||||
if (oe) {
|
||||
return {
|
||||
sucess: false,
|
||||
message: `Error getting article data`,
|
||||
data: oe,
|
||||
};
|
||||
}
|
||||
|
||||
// order state
|
||||
const { data: invoice, error: ie } = await tryCatch(
|
||||
query(invoiceAddress, "Gets invoices addresses")
|
||||
);
|
||||
const i: any = invoice?.data;
|
||||
if (ie) {
|
||||
return {
|
||||
sucess: false,
|
||||
message: `Error getting invoice address data`,
|
||||
data: ie,
|
||||
};
|
||||
}
|
||||
const plantToken = s.filter((s) => s.name === "plantToken");
|
||||
|
||||
const arrayBuffer = await data.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
|
||||
const workbook = XLSX.read(buffer, { type: "buffer" });
|
||||
|
||||
//const sheetName = workbook.SheetNames[0];
|
||||
const sheet = workbook.Sheets["Data"];
|
||||
|
||||
// define custom headers
|
||||
const headers = [
|
||||
"CustomerArticleNumber",
|
||||
"CustomerOrderNumber",
|
||||
"CustomerLineNumber",
|
||||
"CustomerRealeaseNumber",
|
||||
"Quantity",
|
||||
"DeliveryDate",
|
||||
"CustomerID",
|
||||
"Remark",
|
||||
];
|
||||
const orderData = XLSX.utils.sheet_to_json(sheet, {
|
||||
defval: "",
|
||||
header: headers,
|
||||
range: 5,
|
||||
});
|
||||
|
||||
// the base of the import
|
||||
const predefinedObject = {
|
||||
receivingPlantId: plantToken[0].value,
|
||||
documentName: `OrdersFromLST-${new Date(Date.now()).toLocaleString(
|
||||
"en-US"
|
||||
)}`,
|
||||
sender: user.username || "lst-system",
|
||||
externalRefNo: `OrdersFromLST-${new Date(Date.now()).toLocaleString(
|
||||
"en-US"
|
||||
)}`,
|
||||
orders: [],
|
||||
};
|
||||
|
||||
const removeBlanks = orderData.filter(
|
||||
(n: any) => n.CustomerArticleNumber != ""
|
||||
);
|
||||
|
||||
console.log(removeBlanks);
|
||||
const groupedByCustomer: any = removeBlanks.reduce(
|
||||
(acc: any, item: any) => {
|
||||
const id = item.CustomerID;
|
||||
if (!acc[id]) {
|
||||
acc[id] = [];
|
||||
}
|
||||
acc[id].push(item);
|
||||
return acc;
|
||||
},
|
||||
{}
|
||||
);
|
||||
|
||||
let postedOrders: any = [];
|
||||
for (const [customerID, orders] of Object.entries(groupedByCustomer)) {
|
||||
// console.log(`Running for Customer ID: ${customerID}`);
|
||||
const filterOrders: any = orders;
|
||||
const newOrders: any = [];
|
||||
//newOrders.filter((oo) => openOrders.some((o) => String(o.CustomerOrderNumber) === String(oo.CustomerOrderNumber)));
|
||||
//console.log(newOrders)
|
||||
filterOrders.forEach((oo: any) => {
|
||||
const isMatch = openOrders.some(
|
||||
(o: any) =>
|
||||
// check the header
|
||||
String(o.CustomerOrderNumber).trim() ===
|
||||
String(oo.CustomerOrderNumber).trim() &&
|
||||
// and check the customer release is not in here.
|
||||
String(o.CustomerRealeaseNumber).trim() ===
|
||||
String(oo.CustomerRealeaseNumber).trim()
|
||||
);
|
||||
if (!isMatch) {
|
||||
console.log(`ok to update: ${oo.CustomerOrderNumber}`);
|
||||
|
||||
newOrders.push(oo);
|
||||
} else {
|
||||
console.log(
|
||||
`Not valid order to update: ${oo.CustomerOrderNumber}`
|
||||
);
|
||||
//console.log(oo)
|
||||
}
|
||||
});
|
||||
|
||||
// filter out the orders that have already been started just to reduce the risk of errors.
|
||||
newOrders.filter((oo: any) =>
|
||||
openOrders.some(
|
||||
(o: any) => o.CustomerOrderNumber === oo.CustomerOrderNumber
|
||||
)
|
||||
);
|
||||
|
||||
// map everything out for each order
|
||||
const nOrder = newOrders.map((o: any) => {
|
||||
const invoice = i.filter(
|
||||
(i: any) => i.deliveryAddress === parseInt(customerID)
|
||||
);
|
||||
if (!invoice) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
customerId: parseInt(customerID),
|
||||
invoiceAddressId: invoice[0]?.invoiceAddress, // matched to the default invoice address
|
||||
customerOrderNo: o.CustomerOrderNumber,
|
||||
orderDate: new Date(Date.now()).toLocaleString("en-US"),
|
||||
positions: [
|
||||
{
|
||||
deliveryAddressId: parseInt(customerID),
|
||||
customerArticleNo: o.CustomerArticleNumber,
|
||||
quantity: parseInt(o.Quantity),
|
||||
deliveryDate: excelDateStuff(o.DeliveryDate),
|
||||
customerLineItemNo: o.CustomerLineNumber, // this is how it is currently sent over from abbott
|
||||
customerReleaseNo: o.CustomerRealeaseNumber, // same as above
|
||||
remark: o.remark === "" ? null : o.remark,
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
|
||||
// do that fun combining thing
|
||||
const updatedPredefinedObject = {
|
||||
...predefinedObject,
|
||||
orders: [...predefinedObject.orders, ...nOrder],
|
||||
};
|
||||
|
||||
//console.log(updatedPredefinedObject);
|
||||
|
||||
// post the orders to the server
|
||||
const posting: any = await postOrders(updatedPredefinedObject, user);
|
||||
|
||||
postedOrders.push({
|
||||
customer: customerID,
|
||||
//totalOrders: orders?.length(),
|
||||
success: posting.success,
|
||||
message: posting.message,
|
||||
data: posting.data,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message:
|
||||
"Standard Template was just processed successfully, please check AlplaProd 2.0 to confirm no errors. ",
|
||||
data: postedOrders,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,192 @@
|
||||
import { delay } from "../../../../../../globalUtils/delay.js";
|
||||
import XLSX from "xlsx";
|
||||
import { tryCatch } from "../../../../../../globalUtils/tryCatch.js";
|
||||
import { db } from "../../../../../../../database/dbclient.js";
|
||||
import { settings } from "../../../../../../../database/schema/settings.js";
|
||||
import { query } from "../../../../../sqlServer/prodSqlServer.js";
|
||||
import { orderState } from "../../../../../sqlServer/querys/dm/orderState.js";
|
||||
import { excelDateStuff } from "../../../../utils/excelDateStuff.js";
|
||||
import { invoiceAddress } from "../../../../../sqlServer/querys/dm/invoiceAddress.js";
|
||||
import { postOrders } from "../postOrders.js";
|
||||
|
||||
export const standardOrders = async (data: any, user: any) => {
|
||||
/**
|
||||
* 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));
|
||||
|
||||
if (e) {
|
||||
return {
|
||||
sucess: false,
|
||||
message: `Error getting settings`,
|
||||
data: e,
|
||||
};
|
||||
}
|
||||
|
||||
// order state
|
||||
const { data: o, error: oe } = await tryCatch(
|
||||
query(orderState, "Gets the next 500 orders that have not been started")
|
||||
);
|
||||
|
||||
const openOrders: any = o?.data;
|
||||
|
||||
if (oe) {
|
||||
return {
|
||||
sucess: false,
|
||||
message: `Error getting article data`,
|
||||
data: oe,
|
||||
};
|
||||
}
|
||||
|
||||
// order state
|
||||
const { data: invoice, error: ie } = await tryCatch(
|
||||
query(invoiceAddress, "Gets invoices addresses")
|
||||
);
|
||||
const i: any = invoice?.data;
|
||||
if (ie) {
|
||||
return {
|
||||
sucess: false,
|
||||
message: `Error getting invoice address data`,
|
||||
data: ie,
|
||||
};
|
||||
}
|
||||
const plantToken = s.filter((s) => s.name === "plantToken");
|
||||
|
||||
const arrayBuffer = await data.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
|
||||
const workbook = XLSX.read(buffer, { type: "buffer" });
|
||||
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
|
||||
// define custom headers
|
||||
const headers = [
|
||||
"CustomerArticleNumber",
|
||||
"CustomerOrderNumber",
|
||||
"CustomerLineNumber",
|
||||
"CustomerRealeaseNumber",
|
||||
"Quantity",
|
||||
"DeliveryDate",
|
||||
"CustomerID",
|
||||
"Remark",
|
||||
];
|
||||
const orderData = XLSX.utils.sheet_to_json(sheet, {
|
||||
defval: "",
|
||||
header: headers,
|
||||
range: 1,
|
||||
});
|
||||
|
||||
// the base of the import
|
||||
const predefinedObject = {
|
||||
receivingPlantId: plantToken[0].value,
|
||||
documentName: `OrdersFromLST-${new Date(Date.now()).toLocaleString(
|
||||
"en-US"
|
||||
)}`,
|
||||
sender: user.username || "lst-system",
|
||||
externalRefNo: `OrdersFromLST-${new Date(Date.now()).toLocaleString(
|
||||
"en-US"
|
||||
)}`,
|
||||
orders: [],
|
||||
};
|
||||
|
||||
const groupedByCustomer: any = orderData.reduce((acc: any, item: any) => {
|
||||
const id = item.CustomerID;
|
||||
if (!acc[id]) {
|
||||
acc[id] = [];
|
||||
}
|
||||
acc[id].push(item);
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
let postedOrders: any = [];
|
||||
for (const [customerID, orders] of Object.entries(groupedByCustomer)) {
|
||||
// console.log(`Running for Customer ID: ${customerID}`);
|
||||
const filterOrders: any = orders;
|
||||
const newOrders: any = [];
|
||||
//newOrders.filter((oo) => openOrders.some((o) => String(o.CustomerOrderNumber) === String(oo.CustomerOrderNumber)));
|
||||
//console.log(newOrders)
|
||||
filterOrders.forEach((oo: any) => {
|
||||
const isMatch = openOrders.some(
|
||||
(o: any) =>
|
||||
// check the header
|
||||
String(o.CustomerOrderNumber).trim() ===
|
||||
String(oo.CustomerOrderNumber).trim() &&
|
||||
// and check the customer release is not in here.
|
||||
String(o.CustomerRealeaseNumber).trim() ===
|
||||
String(oo.CustomerRealeaseNumber).trim()
|
||||
);
|
||||
if (!isMatch) {
|
||||
console.log(`ok to update: ${oo.CustomerOrderNumber}`);
|
||||
|
||||
newOrders.push(oo);
|
||||
} else {
|
||||
console.log(
|
||||
`Not valid order to update: ${oo.CustomerOrderNumber}`
|
||||
);
|
||||
//console.log(oo)
|
||||
}
|
||||
});
|
||||
|
||||
// filter out the orders that have already been started just to reduce the risk of errors.
|
||||
newOrders.filter((oo: any) =>
|
||||
openOrders.some(
|
||||
(o: any) => o.CustomerOrderNumber === oo.CustomerOrderNumber
|
||||
)
|
||||
);
|
||||
|
||||
// map everything out for each order
|
||||
const nOrder = newOrders.map((o: any) => {
|
||||
const invoice = i.filter(
|
||||
(i: any) => i.deliveryAddress === parseInt(customerID)
|
||||
);
|
||||
if (!invoice) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
customerId: parseInt(customerID),
|
||||
invoiceAddressId: invoice[0]?.invoiceAddress, // matched to the default invoice address
|
||||
customerOrderNo: o.CustomerOrderNumber,
|
||||
orderDate: new Date(Date.now()).toLocaleString("en-US"),
|
||||
positions: [
|
||||
{
|
||||
deliveryAddressId: parseInt(customerID),
|
||||
customerArticleNo: o.CustomerArticleNumber,
|
||||
quantity: parseInt(o.Quantity),
|
||||
deliveryDate: excelDateStuff(o.DeliveryDate),
|
||||
customerLineItemNo: o.CustomerLineNumber, // this is how it is currently sent over from abbott
|
||||
customerReleaseNo: o.CustomerRealeaseNumber, // same as above
|
||||
remark: o.Remark === "" ? null : o.Remark,
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
|
||||
// do that fun combining thing
|
||||
const updatedPredefinedObject = {
|
||||
...predefinedObject,
|
||||
orders: [...predefinedObject.orders, ...nOrder],
|
||||
};
|
||||
|
||||
//console.log(updatedPredefinedObject.orders[0]);
|
||||
|
||||
// post the orders to the server
|
||||
const posting: any = await postOrders(updatedPredefinedObject, user);
|
||||
|
||||
postedOrders.push({
|
||||
customer: customerID,
|
||||
//totalOrders: orders?.length(),
|
||||
success: posting.success,
|
||||
message: posting.message,
|
||||
data: posting.data,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message:
|
||||
"Standard Template was just processed successfully, please check AlplaProd 2.0 to confirm no errors. ",
|
||||
data: postedOrders,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
import { abbottOrders } from "./mappings/abbottTruckList.js";
|
||||
import { energizerOrders } from "./mappings/energizerOrdersIn.js";
|
||||
import { macroImportOrders } from "./mappings/macroImport.js";
|
||||
import { standardOrders } from "./mappings/standardOrders.js";
|
||||
|
||||
export const ordersIn = async (data: any, user: any) => {
|
||||
/**
|
||||
* Bulk orders in, and custom file parsing.
|
||||
*/
|
||||
|
||||
let success = true;
|
||||
let message = "";
|
||||
let orderData: any = [];
|
||||
|
||||
// what type of order are we dealing with?
|
||||
if (data["fileType"] === "standard") {
|
||||
// run the standard orders in
|
||||
const standard = await standardOrders(data["postOrders"], user);
|
||||
success = standard.success ?? false;
|
||||
message = standard.message ?? "Error posting Standard Orders";
|
||||
orderData = standard.data;
|
||||
}
|
||||
|
||||
if (data["fileType"] === "abbott") {
|
||||
// orders in
|
||||
const abbott = await abbottOrders(data["postOrders"], user);
|
||||
success = abbott.success ?? false;
|
||||
message = abbott.message ?? "Error posting Abbott Orders";
|
||||
orderData = abbott.data;
|
||||
}
|
||||
|
||||
if (data["fileType"] === "energizer") {
|
||||
// orders in
|
||||
const energizer = await energizerOrders(data["postOrders"], user);
|
||||
success = energizer.success ?? false;
|
||||
message = energizer.message ?? "Error posting Energizer Orders";
|
||||
orderData = energizer.data;
|
||||
}
|
||||
|
||||
if (data["fileType"] === "loreal") {
|
||||
// orders in
|
||||
}
|
||||
|
||||
if (data["fileType"] === "pg") {
|
||||
// orders in
|
||||
}
|
||||
|
||||
if (data["fileType"] === "macro") {
|
||||
// orders in
|
||||
const macro = await macroImportOrders(data["postOrders"], user);
|
||||
success = macro.success ?? false;
|
||||
message = macro.message ?? "Error posting Macro Orders";
|
||||
orderData = macro.data;
|
||||
}
|
||||
|
||||
return {
|
||||
success,
|
||||
message,
|
||||
data: orderData,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,62 @@
|
||||
import axios from "axios";
|
||||
import { prodEndpointCreation } from "../../../../../globalUtils/createUrl.js";
|
||||
import { createLog } from "../../../../logger/logger.js";
|
||||
|
||||
export const postOrders = async (data: any, user: any) => {
|
||||
let endpoint = await prodEndpointCreation(
|
||||
"/public/v1.0/DemandManagement/ORDERS"
|
||||
);
|
||||
|
||||
try {
|
||||
const results = await axios({
|
||||
url: endpoint,
|
||||
method: "POST",
|
||||
headers: {
|
||||
"X-API-Key": process.env.TEC_API_KEY || "",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
// if a body is sent over it would be like below
|
||||
data: data,
|
||||
});
|
||||
|
||||
//console.log(results.status);
|
||||
if (results.data.errors) {
|
||||
createLog(
|
||||
"error",
|
||||
user.username,
|
||||
"logisitcs",
|
||||
results.data.errors[0].message
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
message: "Error processing orders",
|
||||
data: results.data.errors[0].message,
|
||||
};
|
||||
}
|
||||
|
||||
if (results.status === 200) {
|
||||
createLog(
|
||||
"info",
|
||||
user.username,
|
||||
"logisitcs",
|
||||
"Orders were processed please check 2.0 for validation and errors"
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
message: "Success on posting orders",
|
||||
data: data,
|
||||
};
|
||||
}
|
||||
} catch (error: any) {
|
||||
//console.log(`There is an error`, error);
|
||||
if (error) {
|
||||
//console.log(error.response.data);
|
||||
createLog("error", user.username, "logisitcs", error.response.data);
|
||||
return {
|
||||
success: false,
|
||||
message: "There was an error processing data",
|
||||
data: error.response.data,
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user