Compare commits

...

12 Commits

17 changed files with 396 additions and 18 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

@@ -35,7 +35,7 @@
}
},
"admConfig": {
"build": 307,
"build": 311,
"oldBuild": "backend-0.1.3.zip"
},
"devDependencies": {

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

@@ -44,7 +44,8 @@ export const getDeliveryByDateRange = async (data: any | null) => {
updatedQuery,
"Get Delivery by date range"
);
deliverys - res.data;
deliverys = res.data;
//console.log(res.data);
} catch (error) {
console.log(error);
return {

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

@@ -86,6 +86,14 @@ const current: any = [
"Returns all Deliverys in selected date range IE: 1/1/2025 to 1/31/2025",
criteria: "start,end", // uncomment this out once the improt process can be faster
},
{
name: "Fake Edi Update",
endpoint: "/api/datamart/fakeediupdate",
// description: "Returns all inventory, by default excludes running numebrs, also excludes inv locations.",
description:
"Returns all open orders to correct and resubmit, leaving blank will get everything putting an address only returns the specified address",
criteria: "address", // uncomment this out once the improt process can be faster
},
];
app.openapi(

View File

@@ -100,9 +100,9 @@ export const abbottOrders = async (data: any, user: any) => {
.map((o: any) => ({
date: excelDateStuff(o.date, o.time),
po:
o.newton8oz.replace(" ", "") !== ""
? o.newton8oz.replace(" ", "")
: o.newton10oz.replace(" ", ""),
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]
@@ -129,16 +129,18 @@ export const abbottOrders = async (data: any, user: any) => {
const filterOrders: any = correctedOrders;
filterOrders.forEach((oo: any) => {
const isMatch = openOrders.some(
(o: any) =>
String(o.CustomerOrderNumber).trim() ===
String(oo.CustomerOrderNumber).trim()
(o: any) => String(o.po).trim() === String(oo.po).trim()
);
if (!isMatch) {
console.log(`ok to update: ${oo.CustomerOrderNumber}`);
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.CustomerOrderNumber}`);
console.log(`Not valid order to update: ${oo.po}`);
//console.log(oo)
}
});
@@ -169,6 +171,7 @@ export const abbottOrders = async (data: any, user: any) => {
orders: [...predefinedObject.orders, ...orders],
};
console.log(updatedPredefinedObject);
// post the orders to the server
const posting = await postOrders(updatedPredefinedObject, user);

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

@@ -1,5 +1,6 @@
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) => {
@@ -44,6 +45,14 @@ export const ordersIn = async (data: any, user: any) => {
// 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,

View File

@@ -19,6 +19,6 @@ export const getStockSiloData = async () => {
return {
success: true,
message: "Current silo data from alplastock.",
data: data,
data: stockData,
};
};

View File

@@ -15,6 +15,7 @@ import postBulkOrders from "./route/dm/bulkOrdersIn.js";
import standardTemplate from "./route/dm/getStandardTemplate.js";
import standardForcasttemplate from "./route/dm/getStandardForecastTemplate.js";
import postForecast from "./route/dm/forecastIn.js";
import outbound from "./route/getOutbound.js";
const app = new OpenAPIHono();
@@ -37,6 +38,8 @@ const routes = [
standardTemplate,
postForecast,
standardForcasttemplate,
// outbound deliveries
outbound,
] as const;
// app.route("/server", modules);

View File

@@ -0,0 +1,45 @@
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { responses } from "../../../globalUtils/routeDefs/responses.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { getCycleCountCheck } from "../controller/warehouse/cycleCountChecks/getCycleCountCheck.js";
import { getPPOO } from "../controller/warehouse/ppoo/getPPOO.js";
const app = new OpenAPIHono();
// const Body = z
// .object({
// age: z.number().optional().openapi({ example: 90 }),
// //email: z.string().optional().openapi({example: "s.smith@example.com"}),
// type: z.string().optional().openapi({ example: "fg" }),
// })
// .openapi("User");
app.openapi(
createRoute({
tags: ["logistics"],
summary: "outbound delivery notes",
method: "post",
path: "/outbound",
// request: {
// body: {
// content: {
// "application/json": { schema: Body },
// },
// },
// },
// description:
// "Provided a running number and lot number you can consume material.",
responses: responses(),
}),
async (c: any) => {
//apiHit(c, { endpoint: "api/sqlProd/close" });
const body = await c.req.json();
return c.json({
success: true,
message: "testing",
data: [],
});
}
);
export default app;

View File

@@ -48,6 +48,7 @@ export default async function qualityBlockingMonitor(notifyData: any) {
query(blockingQuery, "Quality Blocking")
);
const blocking: any = b?.data as any;
if (blockingError) {
return {
success: false,
@@ -99,6 +100,7 @@ export default async function qualityBlockingMonitor(notifyData: any) {
])
);
console.log(uniqueOrders);
const { data, error } = await tryCatch(
db
.update(notifications)

View File

@@ -24,7 +24,7 @@ const newSubModules = [
description: "Bulk order and Forecast imports",
link: "/dm",
icon: "Truck",
role: ["systemAdmin"],
roles: ["technician", "supervisor", "manager", "admin", "systemAdmin"],
active: false,
subSubModule: [],
},
@@ -34,7 +34,7 @@ const newSubModules = [
description: "",
link: "#",
icon: "Truck",
role: ["systemAdmin"],
roles: ["systemAdmin"],
active: false,
subSubModule: [],
},
@@ -44,7 +44,7 @@ const newSubModules = [
description: "",
link: "/materialHelper/consumption",
icon: "Package",
role: ["technician", "supervisor", "manager", "admin", "systemAdmin"],
roles: ["technician", "supervisor", "manager", "admin", "systemAdmin"],
active: false,
subSubModule: [],
},
@@ -54,7 +54,7 @@ const newSubModules = [
description: "",
link: "/cyclecount",
icon: "Package",
role: ["technician", "supervisor", "manager", "admin", "systemAdmin"],
roles: ["technician", "supervisor", "manager", "admin", "systemAdmin"],
active: false,
subSubModule: [],
},
@@ -64,7 +64,7 @@ const newSubModules = [
description: "Open orders",
link: "/openOrders",
icon: "Truck",
role: [
roles: [
"viewer",
"technician",
"supervisor",
@@ -94,7 +94,7 @@ const newSubModules = [
link: "#", // when link is # this will mean its a button
icon: "ShieldCheck",
active: true,
roles: ["tester", "systemAdmin"],
roles: ["tester", "admin", "systemAdmin"],
subSubModule: [
{
name: "Settings",

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
`;

View File

@@ -4,7 +4,7 @@ x.IdArtikelVarianten AS article,
ArtikelVariantenAlias AS articleDescription,
IdAuftragsAbruf as releaseNumber,
AuftragsNummer AS header,
AuftragsNummer as customerLineItemNo,
PositionsNummer as customerLineItemNo,
AbrufNummer AS customerReleaseNumber,
AbrufMengeVPK AS pallets,
AbrufMenge AS qty,