feat(fakeedi): fake edi macro update implemented

This commit is contained in:
2025-04-29 17:07:15 -05:00
parent b3b6002d9a
commit 3e79017afc
6 changed files with 307 additions and 0 deletions

View File

@@ -8,6 +8,7 @@ export default function DMButtons() {
//console.log(plantToken);
return (
<div className="flex flex-row-reverse gap-1">
<OrderImport fileType={"macro"} name={"Macro Import"} />
{/* dev and testserver sees all */}
{testServers.includes(plantToken[0]?.value) && (
<div className="flex flex-row gap-2">

View File

@@ -0,0 +1,39 @@
import { createLog } from "../../logger/logger.js";
import { query } from "../../sqlServer/prodSqlServer.js";
import { fakeEDIUpdate } from "../../sqlServer/querys/dataMart/fakeEDIUpdate.js";
export const getFakeEDI = async (address: string) => {
let fakeEDI: any = [];
let updatedQuery = fakeEDIUpdate;
if (address) {
createLog(
"info",
"datamart",
"datamart",
"The user requested a specific address."
);
updatedQuery = fakeEDIUpdate.replace(
"--and IdAdresse = 14",
`and IdAdresse = ${address}`
);
}
try {
fakeEDI = await query(updatedQuery, "Gets fakeEDI orders to be fixed");
return {
success: true,
message: "Current open orders",
data: fakeEDI.data,
};
} catch (error) {
console.log(error);
return {
success: false,
message: "There was an error open orders",
data: error,
};
}
};

View File

@@ -5,6 +5,7 @@ import currentInv from "./route/getInventory.js";
import getCustomerInv from "./route/getCustomerInv.js";
import getOpenOrders from "./route/getOpenOrders.js";
import getDeliveryByDate from "./route/getDeliveryDateByRange.js";
import fakeEDI from "./route/fakeEDI.js";
const app = new OpenAPIHono();
@@ -15,6 +16,7 @@ const routes = [
getCustomerInv,
getOpenOrders,
getDeliveryByDate,
fakeEDI,
] as const;
const appRoutes = routes.forEach((route) => {

View File

@@ -0,0 +1,53 @@
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { responses } from "../../../globalUtils/routeDefs/responses.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { getINV } from "../controller/getinventory.js";
import { getFakeEDI } from "../controller/fakeEDIUpdate.js";
const app = new OpenAPIHono({ strict: false });
const Body = z.object({
address: z.string().openapi({ example: "x" }),
});
app.openapi(
createRoute({
tags: ["dataMart"],
summary: "Returns all open orders that need to be updated in fake edi.",
method: "get",
path: "/fakeediupdate",
request: {
body: {
content: {
"application/json": { schema: Body },
},
},
},
responses: responses(),
}),
async (c) => {
const address: string = c.req.query("address") ?? "";
// make sure we have a vaid user being accessed thats really logged in
//apiHit(c, { endpoint: `api/logger/logs/id` });
const { data, error } = await tryCatch(
getFakeEDI(address.toString() ?? "")
);
if (error) {
return c.json(
{
success: false,
message: "There was an error getting the inv.",
data: error,
},
400
);
}
return c.json({
success: data.success,
message: data.message,
data: data.data,
});
}
);
export default app;

View File

@@ -0,0 +1,195 @@
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) =>
String(o.CustomerOrderNumber).trim() ===
String(oo.CustomerOrderNumber).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
},
],
};
});
// 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,
};
};

View File

@@ -0,0 +1,17 @@
export const fakeEDIUpdate = `
Select LEFT(ArtikelVariantenAlias, charindex(' ', ArtikelVariantenAlias) - 1) CustomerArticleNumber,
AuftragsNummer AS CustomerOrderNumber,
PositionsNummer as CustomerLineNumber,
AbrufNummer AS CustomerRealeaseNumber,
AbrufMenge AS Quantity,
' ' AS DeliveryDate,
IdAdresse AS CustomerID,
' ' AS Remark
--,*
FROM AlplaPROD_test1.dbo.V_TrackerAuftragsAbrufe
WHERE AbrufStatus = 1
--AND AbrufLiefertermin > DATEADD(d, -1, getdate())
AND GelieferteMenge = 0
--and IdAdresse = 14
ORDER BY AbrufLiefertermin
`;