refactor(sql): improved the return function to show data [] when not connected, prevents crashes

This commit is contained in:
2025-04-24 21:24:39 -05:00
parent 3573fd1a5b
commit ead63d4b41
36 changed files with 323 additions and 141 deletions

View File

@@ -1,24 +1,38 @@
import {eq} from "drizzle-orm";
import {db} from "../../database/dbclient.js";
import {settings} from "../../database/schema/settings.js";
import {query} from "../services/sqlServer/prodSqlServer.js";
import {plantInfo} from "../services/sqlServer/querys/dataMart/plantInfo.js";
import {createLog} from "../services/logger/logger.js";
import { eq } from "drizzle-orm";
import { db } from "../../database/dbclient.js";
import { settings } from "../../database/schema/settings.js";
import { query } from "../services/sqlServer/prodSqlServer.js";
import { plantInfo } from "../services/sqlServer/querys/dataMart/plantInfo.js";
import { createLog } from "../services/logger/logger.js";
export const createSSCC = async (runningNumber: number) => {
// get the token
const plantToken = await db.select().from(settings).where(eq(settings.name, "plantToken"));
let global; // get from plant address in basis enter the entire string here.
const plantToken = await db
.select()
.from(settings)
.where(eq(settings.name, "plantToken"));
let global: any = []; // get from plant address in basis enter the entire string here.
try {
global = await query(plantInfo.replaceAll("[token]", plantToken[0].value), "plantInfo");
const res: any = await query(
plantInfo.replaceAll("[token]", plantToken[0].value),
"plantInfo"
);
global = res.data;
} catch (error) {
createLog("error", "lst", "globalUtils", `There was an error getting the GLN: Error: ${error}`);
createLog(
"error",
"lst",
"globalUtils",
`There was an error getting the GLN: Error: ${error}`
);
}
// create the sscc without the check diget and make sure we have it all correct
let step1SSCC = global[0].gln.toString().slice(0, 7).padStart(10, "0") + runningNumber.toString().padStart(9, "0");
let step1SSCC =
global[0].gln.toString().slice(0, 7).padStart(10, "0") +
runningNumber.toString().padStart(9, "0");
let sum = 0;
for (let i = 0; i < step1SSCC.length; i++) {

View File

@@ -4,7 +4,8 @@ import { activeArticle } from "../../sqlServer/querys/dataMart/article.js";
export const getActiveAv = async () => {
let articles: any = [];
try {
articles = await query(activeArticle, "Get active articles");
const res = await query(activeArticle, "Get active articles");
articles = res?.data;
} catch (error) {
articles = error;
}

View File

@@ -12,12 +12,15 @@ export const getCurrentCustomerInv = async (customer: any | null) => {
);
}
try {
const inventory = await query(updatedQuery, "Get active inventory");
const inventory: any = await query(
updatedQuery,
"Get active inventory"
);
return {
success: true,
message: "All customer inventory minus holds",
data: inventory,
data: inventory.data,
};
} catch (error) {
return {

View File

@@ -17,7 +17,7 @@ export const getDeliveryByDateRange = async (data: any | null) => {
data: plantError,
};
}
let deliverys = [];
let deliverys: any = [];
let updatedQuery = deliveryByDateRange;
@@ -40,7 +40,11 @@ export const getDeliveryByDateRange = async (data: any | null) => {
}
try {
deliverys = await query(updatedQuery, "Get Delivery by date range");
const res: any = await query(
updatedQuery,
"Get Delivery by date range"
);
deliverys - res.data;
} catch (error) {
console.log(error);
return {

View File

@@ -16,7 +16,7 @@ export const getOpenOrders = async (data: any | null) => {
data: plantError,
};
}
let orders = [];
let orders: any = [];
let updatedQuery = openOrders;
@@ -37,7 +37,11 @@ export const getOpenOrders = async (data: any | null) => {
try {
orders = await query(updatedQuery, "Get active openorders");
} catch (error) {
return { success: false, message: "Current open orders", data: orders };
return {
success: false,
message: "Current open orders",
data: orders.data,
};
}
// add plant token in

View File

@@ -22,7 +22,7 @@ export const getINV = async (rn: boolean) => {
try {
inventory = await query(updatedQuery, "Gets Curruent inv");
return { success: true, message: "Current inv", data: inventory };
return { success: true, message: "Current inv", data: inventory.data };
} catch (error) {
console.log(error);
return {

View File

@@ -29,13 +29,13 @@ export const abbottOrders = async (data: any, user: any) => {
}
// articleInfo
const { data: a, error: ae } = await tryCatch(
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,
@@ -45,10 +45,12 @@ export const abbottOrders = async (data: any, user: any) => {
}
// order state
const { data: openOrders, error: oe } = await tryCatch(
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,

View File

@@ -24,10 +24,12 @@ export const energizerOrders = async (data: any, user: any) => {
}
// order state
const { data: openOrders, error: oe } = await tryCatch(
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,
@@ -37,9 +39,10 @@ export const energizerOrders = async (data: any, user: any) => {
}
// order state
const { data: i, error: ie } = await tryCatch(
const { data: invoice, error: ie } = await tryCatch(
query(invoiceAddress, "Gets invoices addresses")
);
const i: any = invoice?.data;
if (ie) {
return {

View File

@@ -25,10 +25,12 @@ export const standardOrders = async (data: any, user: any) => {
}
// order state
const { data: openOrders, error: oe } = await tryCatch(
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,
@@ -38,10 +40,10 @@ export const standardOrders = async (data: any, user: any) => {
}
// order state
const { data: i, error: ie } = await tryCatch(
const { data: invoice, error: ie } = await tryCatch(
query(invoiceAddress, "Gets invoices addresses")
);
const i: any = invoice?.data;
if (ie) {
return {
sucess: false,

View File

@@ -19,7 +19,8 @@ export const consumeMaterial = async (data: Data, prod: any) => {
let barcode;
// get the barcode from the running number
try {
barcode = await query(rnReplace, "labelData");
const r: any = await query(rnReplace, "labelData");
barcode = r?.data;
} catch (error) {
console.log(error);
createLog(

View File

@@ -20,7 +20,8 @@ export const returnMaterial = async (data: Data, prod: any) => {
let barcode;
// get the barcode from the running number
try {
barcode = await query(rnReplace, "labelData");
const r: any = await query(rnReplace, "labelData");
barcode = r?.data;
} catch (error) {
console.log(error);
createLog(
@@ -31,10 +32,10 @@ export const returnMaterial = async (data: Data, prod: any) => {
);
}
const { data: laneData, error: laneError } = await tryCatch(
const { data: l, error: laneError } = await tryCatch(
query(laneQuery, "laneInfo")
);
const laneData: any = l?.data;
if (laneError) {
return {
success: false,

View File

@@ -31,7 +31,7 @@ export const createSiloAdjustment = async (
}
// getting stock data first so we have it prior to the adjustment
const { data: stock, error: stockError } = await tryCatch(
const { data: s, error: stockError } = await tryCatch(
query(siloQuery, "Silo data Query")
);
@@ -42,7 +42,7 @@ export const createSiloAdjustment = async (
data: stockError,
};
}
const stock: any = s?.data as any;
const { data: a, error: errorAdj } = await tryCatch(
postAdjustment(data, user.prod)
);

View File

@@ -15,7 +15,7 @@ export const getStockSiloData = async () => {
message: "There was a n error getting the silo data.",
};
}
const stockData: any = data?.data;
return {
success: true,
message: "Current silo data from alplastock.",

View File

@@ -17,7 +17,7 @@ export const getLanesToCycleCount = async () => {
createLog("info", "warehouse", "logistics", "Lane triggered update.");
lastCheck = currentTime;
const ageQuery = cycleCountCheck.replaceAll("[ageOfRow]", "90");
const { data: prodLanes, error: pl } = await tryCatch(
const { data: p, error: pl } = await tryCatch(
query(ageQuery, "Get Stock lane date.")
);
@@ -31,6 +31,8 @@ export const getLanesToCycleCount = async () => {
return;
}
const prodLanes: any = p?.data;
// run the update on the lanes
for (let i = 0; i < prodLanes.length; i++) {
const createLane = {

View File

@@ -81,11 +81,11 @@ export default async function reprintLabelMonitor(notifyData: any) {
`;
//console.log(query);
let downTime: any; //DownTime[];
let downTime: any = []; //DownTime[];
try {
downTime = await query(dQuery, "downTimeCheck");
const res: any = await query(dQuery, "downTimeCheck");
//console.log(labels.length);
downTime = res.data;
if (
downTime.length > 0 &&
downTime[0]?.downTimeId > notifyData.notifiySettings.prodID

View File

@@ -76,7 +76,8 @@ export default async function reprintLabelMonitor(notifyData: any) {
let prod: PPOO[];
try {
prod = await query(notifyQuery, "Label Reprints");
const res: any = await query(notifyQuery, "Label Reprints");
prod = res.data;
//console.log(labels.length);
// const now = Date.now()
if (prod.length > 0) {

View File

@@ -44,10 +44,10 @@ export default async function qualityBlockingMonitor(notifyData: any) {
blockingOrders
);
const { data: blocking, error: blockingError } = await tryCatch(
const { data: b, error: blockingError } = await tryCatch(
query(blockingQuery, "Quality Blocking")
);
const blocking: any = b?.data as any;
if (blockingError) {
return {
success: false,

View File

@@ -64,10 +64,10 @@ const notification = async (notifyData: any) => {
//let labels: Labels[];
const { data: labels, error: labelError } = await tryCatch(
const { data: l, error: labelError } = await tryCatch(
query(reprintQuery, "Label Reprints")
);
const labels: any = l?.data as any;
if (labelError) {
createLog(
"error",

View File

@@ -69,7 +69,8 @@ export default async function reprintLabelMonitor(notifyData: any) {
let stage: PPOO[];
try {
stage = await query(noteQuery, "Staging checks");
const res = await query(noteQuery, "Staging checks");
stage = res?.data as any;
//console.log(labels.length);
// const now = Date.now()
if (stage.length > 0) {

View File

@@ -77,9 +77,11 @@ export const tiImport = async () => {
.replaceAll("[exclude]", releaseString);
// get the headers pending
const { data: header, error: headerError } = await tryCatch(
const { data: h, error: headerError } = await tryCatch(
query(orders, "Ti get open headers")
);
const header: any = h?.data as any;
if (headerError) {
createLog(
"error",
@@ -127,9 +129,11 @@ export const tiImport = async () => {
.replaceAll("[to]", notiSet[0].notifiySettings.end);
// get the headers pending
const { data: orderData, error: ordersError } = await tryCatch(
const { data: o, error: ordersError } = await tryCatch(
query(orderToSend, "Ti get open headers")
);
const orderData: any = o?.data as any;
if (ordersError)
return {
success: false,

View File

@@ -7,15 +7,21 @@ import { ocmeCycleCounts } from "../../../../database/schema/ocmeCycleCounts.js"
import { db } from "../../../../database/dbclient.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { createLog } from "../../logger/logger.js";
import { prodEndpointCreation } from "../../../globalUtils/createUrl.js";
export const prepareLane =
"https://usday1prod.alpla.net/application/public/v1.1/Warehousing/PrepareLaneForInventory";
export const openLane =
"https://usday1prod.alpla.net/application/public/v1.0/Warehousing/InventoryOpen";
export const closeLane =
"https://usday1prod.alpla.net/application/public/v1.0/Warehousing/InventoryClose";
export const releaseLane =
"https://usday1prod.alpla.net/application/public/v1.1/Warehousing/ReleaseLaneFromInventory";
export const prepareLane = await prodEndpointCreation(
"/public/v1.1/Warehousing/PrepareLaneForInventory"
);
export const openLane = await prodEndpointCreation(
"/public/v1.0/Warehousing/InventoryOpen"
);
export const closeLane = await prodEndpointCreation(
"/public/v1.0/Warehousing/InventoryClose"
);
export const releaseLane = await prodEndpointCreation(
"/public/v1.1/Warehousing/ReleaseLaneFromInventory"
);
export const scannerID = 500;
export const cycleCount = async (lane: any, user: User) => {
/**
@@ -27,7 +33,7 @@ export const cycleCount = async (lane: any, user: User) => {
const ocme = await ocmeInv(lane);
// get alpla stock data
const alplaStock = await alplaStockInv(ocme[0].alpla_laneID);
const alplaStock: any = await alplaStockInv(ocme[0].alpla_laneID);
// create a new array that has the merge happen.
const mergeOcmeData = ocme.map((d: any) => {

View File

@@ -1,5 +1,5 @@
import {query} from "../../../sqlServer/prodSqlServer.js";
import {alplaStock} from "../../../sqlServer/querys/ocme/alplaStockInvByID.js";
import { query } from "../../../sqlServer/prodSqlServer.js";
import { alplaStock } from "../../../sqlServer/querys/ocme/alplaStockInvByID.js";
export const alplaStockInv = async (laneID: string) => {
/**
@@ -9,8 +9,8 @@ export const alplaStockInv = async (laneID: string) => {
const stock = alplaStock.replaceAll("[laneID]", `${laneID}`);
try {
const stockData = await query(stock, "Stock Data");
return stockData;
const stockData: any = await query(stock, "Stock Data");
return stockData.data;
} catch (error) {
console.log(error);
return [];

View File

@@ -1,13 +1,18 @@
// full lane count
import axios from "axios";
import {delay} from "../../../../globalUtils/delay.js";
import {createLog} from "../../../logger/logger.js";
import {openLane, prepareLane, scannerID} from "../cycleCount.js";
import type {User} from "../../../../types/users.js";
import { delay } from "../../../../globalUtils/delay.js";
import { createLog } from "../../../logger/logger.js";
import { openLane, prepareLane, scannerID } from "../cycleCount.js";
import type { User } from "../../../../types/users.js";
import { prodEndpointCreation } from "../../../../globalUtils/createUrl.js";
let delayTime = 100;
export const fullLaneCount = async (user: User, lane: string, ocmeLanes: any) => {
export const fullLaneCount = async (
user: User,
lane: string,
ocmeLanes: any
) => {
// prepare the lane.
try {
const openlane = await axios({
@@ -59,7 +64,9 @@ export const fullLaneCount = async (user: User, lane: string, ocmeLanes: any) =>
try {
const openLane = await axios({
method: "POST",
url: "https://usday1prod.alpla.net/application/public/v1.0/Warehousing/InventoryCount",
url: await prodEndpointCreation(
"/public/v1.0/Warehousing/InventoryCount"
),
headers: {
Authorization: `Basic ${user.prod}`,
"Content-Type": "application/json",
@@ -84,7 +91,9 @@ export const fullLaneCount = async (user: User, lane: string, ocmeLanes: any) =>
try {
const openLane = await axios({
method: "POST",
url: "https://usday1prod.alpla.net/application/public/v1.0/Warehousing/InventoryClose",
url: await prodEndpointCreation(
"/public/v1.0/Warehousing/InventoryClose"
),
headers: {
Authorization: `Basic ${user.prod}`,
"Content-Type": "application/json",
@@ -103,7 +112,9 @@ export const fullLaneCount = async (user: User, lane: string, ocmeLanes: any) =>
try {
const openLane = await axios({
method: "POST",
url: "https://usday1prod.alpla.net/application/public/v1.1/Warehousing/ReleaseLaneFromInventory",
url: await prodEndpointCreation(
"/public/v1.1/Warehousing/ReleaseLaneFromInventory"
),
headers: {
Authorization: `Basic ${user.prod}`,
"Content-Type": "application/json",
@@ -113,7 +124,12 @@ export const fullLaneCount = async (user: User, lane: string, ocmeLanes: any) =>
},
});
createLog("info", user.username!, "ocme-count", openLane.data.message);
createLog(
"info",
user.username!,
"ocme-count",
openLane.data.message
);
} catch (error) {
createLog("error", user.username!, "ocme-count", `${error}`);
}
@@ -122,5 +138,5 @@ export const fullLaneCount = async (user: User, lane: string, ocmeLanes: any) =>
createLog("error", user.username!, "ocme-count", `${error}`);
}
return {success: true, message: `Lane completed`};
return { success: true, message: `Lane completed` };
};

View File

@@ -1,11 +1,11 @@
import axios from "axios";
import {createLog} from "../../logger/logger.js";
import {shipmentPallets} from "../../sqlServer/querys/ocme/shipmentPallets.js";
import {getShipmentData} from "./getShipmentData.js";
import {query} from "../../sqlServer/prodSqlServer.js";
import {db} from "../../../../database/dbclient.js";
import {settings} from "../../../../database/schema/settings.js";
import {lotRestriction} from "./lotrestriction.js";
import { createLog } from "../../logger/logger.js";
import { shipmentPallets } from "../../sqlServer/querys/ocme/shipmentPallets.js";
import { getShipmentData } from "./getShipmentData.js";
import { query } from "../../sqlServer/prodSqlServer.js";
import { db } from "../../../../database/dbclient.js";
import { settings } from "../../../../database/schema/settings.js";
import { lotRestriction } from "./lotrestriction.js";
export const getShipmentPallets = async (shipmentID: any) => {
let ocmeLanes: any = [];
@@ -23,43 +23,65 @@ export const getShipmentPallets = async (shipmentID: any) => {
const shipments = await getShipmentData();
// filter the shipment so we can get the correct data from it.
const filteredShipment = shipments.data.filter((order: any) => order.LoadingOrderId === parseInt(shipmentID));
const filteredShipment = shipments.data.filter(
(order: any) => order.LoadingOrderId === parseInt(shipmentID)
);
// getting the criteria we want to look at.
let tmpCheck: any = [];
if (filteredShipment.length === 0) {
createLog("error", "ocme", "ocme", "Invalid shipment id was provided and cant do anything else.");
createLog(
"error",
"ocme",
"ocme",
"Invalid shipment id was provided and cant do anything else."
);
return {
success: false,
message: "Invalid shipmentID sent over please try again",
};
} else {
tmpCheck = filteredShipment[0].Remark.split(",")
.map((item: any) => item.trim()) // removes accedental spaces if there are any
.map((i: any) => i.toLowerCase());
.map((item: any) => item.trim()) // removes accedental spaces if there are any
.map((i: any) => i.toLowerCase());
}
// removing the agv out of the array
let checks = tmpCheck.filter((i: any) => i !== "agv");
let shipmentQ = shipmentPallets
.replaceAll("[article]", filteredShipment[0].LoadingPlan[0].ArticleVariantId)
.replaceAll("[fifo]", setting.filter((n) => n.name === "fifoCheck")[0].value);
.replaceAll(
"[article]",
filteredShipment[0].LoadingPlan[0].ArticleVariantId
)
.replaceAll(
"[fifo]",
setting.filter((n) => n.name === "fifoCheck")[0].value
);
const addressCheck = setting.filter((n) => n.name === "monitorAddress");
if (parseInt(addressCheck[0].value) === filteredShipment[0].LoadingPlan[0].AddressId) {
if (
parseInt(addressCheck[0].value) ===
filteredShipment[0].LoadingPlan[0].AddressId
) {
// if there really ends up being more than 5000 pallets then well we need to fix this later, also an insane issue to have this many that would need to be monitored
shipmentQ = shipmentQ.replaceAll("[totalPallets]", "5000");
} else {
shipmentQ = shipmentQ.replaceAll("[totalPallets]", filteredShipment[0].LoadingPlan[0].PackagingQuantity);
shipmentQ = shipmentQ.replaceAll(
"[totalPallets]",
filteredShipment[0].LoadingPlan[0].PackagingQuantity
);
}
// temp situation only getting the lanes we want to look in
// Convert laneArray to a comma-separated string with each value quoted
let noBlock;
if (checks.includes("all")) {
noBlock = shipmentQ.replaceAll("and GesperrtAktivSum in (0) ", "--and GesperrtAktivSum in (0) ");
noBlock = shipmentQ.replaceAll(
"and GesperrtAktivSum in (0) ",
"--and GesperrtAktivSum in (0) "
);
} else {
noBlock = shipmentQ;
}
@@ -78,13 +100,19 @@ export const getShipmentPallets = async (shipmentID: any) => {
let shipmentLane = shipmentQ.replaceAll("[lanes]", laneString);
let shipmentPals = [];
let shipmentPals: any = [];
//console.log(shipmentLane);
try {
shipmentPals = await query(shipmentLane, "Get shipmentPals");
const res: any = await query(shipmentLane, "Get shipmentPals");
shipmentPals = res.data;
} catch (err) {
createLog("error", "ocme", "ocme", `Error from running the shippment pallets query: ${err}`);
return {success: false, message: err, data: []};
createLog(
"error",
"ocme",
"ocme",
`Error from running the shippment pallets query: ${err}`
);
return { success: false, message: err, data: [] };
}
let filteredPallets = shipmentPals;
@@ -94,7 +122,10 @@ export const getShipmentPallets = async (shipmentID: any) => {
return {
success: true,
message: `There are a total of ${filteredPallets.length} pallet(s) that are in this shipment.`,
data: filteredPallets.splice(0, filteredShipment[0].LoadingPlan[0].PackagingQuantity),
data: filteredPallets.splice(
0,
filteredShipment[0].LoadingPlan[0].PackagingQuantity
),
};
}
@@ -112,21 +143,35 @@ export const getShipmentPallets = async (shipmentID: any) => {
return {
success: true,
message: `There are a total of ${filteredPallets.length} pallet(s) that are in this shipment.`,
data: filteredPallets.splice(0, filteredShipment[0].LoadingPlan[0].PackagingQuantity),
data: filteredPallets.splice(
0,
filteredShipment[0].LoadingPlan[0].PackagingQuantity
),
};
}
// for "what ever case" follow the logic. to check addresses and resitrions
if (parseInt(addressCheck[0].value) === filteredShipment[0].LoadingPlan[0].AddressId) {
if (
parseInt(addressCheck[0].value) ===
filteredShipment[0].LoadingPlan[0].AddressId
) {
createLog(
"info",
"ocme",
"ocme",
"This shipment has restrictions on it and will go throught the lots filtering process"
);
filteredPallets = await lotRestriction(shipmentPals, filteredShipment[0].LoadingPlan[0].PackagingQuantity);
filteredPallets = await lotRestriction(
shipmentPals,
filteredShipment[0].LoadingPlan[0].PackagingQuantity
);
} else {
createLog("info", "ocme", "ocme", "This shipment is cleared to send what ever.");
createLog(
"info",
"ocme",
"ocme",
"This shipment is cleared to send what ever."
);
}
return {

View File

@@ -25,10 +25,11 @@ export const postLabelData = async (data: any) => {
data: [],
};
}
let label;
let label: any = [];
const filterQuery = labelData.replaceAll("[rn]", newData.runningNr);
try {
label = await query(filterQuery, "Label data");
const res: any = await query(filterQuery, "Label data");
label = res.data;
} catch (error) {
createLog(
"error",

View File

@@ -2,12 +2,20 @@ import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { query } from "../../../sqlServer/prodSqlServer.js";
import { lotQuery } from "../../../sqlServer/querys/ocp/lots.js";
type LotInfo = {
success: boolean;
message: string;
data: any[];
};
export const getLots = async () => {
const { data: lotInfo, error: lotError } = await tryCatch(
const { data: l, error: lotError } = await tryCatch(
query(lotQuery, "Alplalabel online lots")
);
const lotInfo = l as LotInfo;
if (lotError) {
console.log("lot error", lotError);
return {
success: false,
message: "There was an error getting the lots",
@@ -15,9 +23,17 @@ export const getLots = async () => {
};
}
return {
success: true,
message: "Current active lots that are technically released.",
data: lotInfo,
};
if (lotInfo.success) {
return {
success: true,
message: "Current active lots that are technically released.",
data: lotInfo,
};
} else {
return {
success: true,
message: `Error getting lot info due to: ${lotInfo.message}.`,
data: [],
};
}
};

View File

@@ -42,7 +42,8 @@ export const prolinkCheck = async (lot: any) => {
// run the query
try {
const prolink = await query(prolinkQuery, "Prolink Checks");
const p: any = await query(prolinkQuery, "Prolink Checks");
const prolink = p.data;
// filter out the lot
const filterdLot = prolink.filter(
(p: any) => p.AlplaLabelOnline === lot

View File

@@ -14,7 +14,9 @@ export const isMainMatStaged = async (lot: any) => {
const updateQuery = mmQuery.replaceAll("[lotNumber]", lot.lot);
try {
const res = await query(updateQuery, "Main Material Check");
const r: any = await query(updateQuery, "Main Material Check");
const res: any = r.data;
createLog(
"info",

View File

@@ -15,6 +15,10 @@ export const printStatus = [
code: 8,
text: "First time printing",
},
{
code: 9,
text: "Offline",
},
];
export const printerUpdate = async (printer: any, status: any) => {

View File

@@ -163,28 +163,55 @@ export const printerStatus = async (p: any) => {
resolve({ success: true, message: "Print cycle completed." });
});
printer.on("error", async (error) => {
// just going to say theres an error with the printer
// as a safety destory it if its still there
printer.on("end", () => {
setTimeout(() => {
if (!printer.destroyed) {
createLog(
"info",
"printerState",
"ocp",
`${p.name}: was force closed, during normal cycle counting`
);
printer.destroy();
}
}, 1000);
});
if (!errorCheck) {
printer.on("error", async (error: any) => {
// just going to say theres an error with the printer
//console.log(error.code);
if (error.code.includes("ETIMEDOUT") && !errorCheck) {
createLog("error", "ocp", "ocp", `${p.name} is offline`);
await printerUpdate(p, 9);
errorCheck = true;
printer.end();
resolve({
success: false,
message: "The printer is offline.",
});
}
if (!error.code.includes("ETIMEDOUT") && !errorCheck) {
createLog(
"error",
"ocp",
"ocp",
`${p.name} encountered an error: ${error}`
);
await printerUpdate(p, 7);
errorCheck = true;
// send log data
// fake line
printer.end();
resolve({
success: false,
message: "There was an error with the printer.",
});
}
await printerUpdate(p, 7);
errorCheck = true;
// send log data
// fake line
printer.end();
resolve({
success: false,
message: "There was an error with the printer.",
});
});
});
};
@@ -230,13 +257,13 @@ export const autoLabelingStats = async (p: any) => {
printer.on("error", async (error) => {
// just going to say theres an error with the printer
console.log(error);
if (!errorCheck) {
createLog(
"error",
"ocp",
"ocp",
`${p.name} encountered an error: ${error}`
`${p.name}, encountered an error: ${error}`
);
}

View File

@@ -38,8 +38,8 @@ export const dualPrintingProcess = async (lotInfo: any) => {
try {
// get what was last printed
const result = await query(printedQuery, "Last Printed Query");
lastPrinted = result[0].IdMaschine;
const result: any = await query(printedQuery, "Last Printed Query");
lastPrinted = result.data[0].IdMaschine;
} catch (err) {
createLog(
"error",
@@ -51,8 +51,8 @@ export const dualPrintingProcess = async (lotInfo: any) => {
try {
// get if if running or down
const first = await query(fisrtLineDT, "First line DT Check");
firstLine = first[0].LineCheck;
const first: any = await query(fisrtLineDT, "First line DT Check");
firstLine = first.data[0].LineCheck;
} catch (err) {
createLog(
"error",
@@ -63,8 +63,8 @@ export const dualPrintingProcess = async (lotInfo: any) => {
}
try {
const second = await query(secondLineDT, "Second line DT Check");
secondLine = second[0].LineCheck;
const second: any = await query(secondLineDT, "Second line DT Check");
secondLine = second.data[0].LineCheck;
} catch (err) {
createLog(
"error",

View File

@@ -9,8 +9,8 @@ import { createLog } from "../../logger/logger.js";
export const assignedPrinters = async () => {
createLog("debug", "ocp", "ocp", "Lot assignment check");
const { data: l, error: lotError } = await tryCatch(getLots());
const { data: lot, error: lotError } = await tryCatch(getLots());
const l: any = lot;
if (lotError) {
return {
success: false,
@@ -43,7 +43,7 @@ export const assignedPrinters = async () => {
}
const printers: any = print.data ?? [];
const lots: any = l?.data.length === 0 ? null : l?.data;
const lots: any = l?.data.length === 0 ? [] : l?.data;
//console.log(lots);

View File

@@ -9,7 +9,9 @@ export const getMac = async (machine: string) => {
let mac = [];
try {
mac = await query(updateQuery, "Machine id check");
const getMac: any = await query(updateQuery, "Machine id check");
mac = getMac.data;
// console.log("Machine data", mac); // removed due to swr being activated
} catch (err) {
createLog(

View File

@@ -50,10 +50,10 @@ export const addNewPallet = async (data: any, user: string) => {
if (palletData.length > 0) {
try {
// get the pallet info from stock
const { data: p, error: pe } = await tryCatch(
const { data: pa, error: pe } = await tryCatch(
query(updateQuery, "quality request")
);
const p: any = pa;
if (pe) {
return {
success: false,
@@ -108,10 +108,10 @@ export const addNewPallet = async (data: any, user: string) => {
// add new pallet
try {
const { data: p, error: pe } = await tryCatch(
const { data: px, error: pe } = await tryCatch(
query(updateQuery, "quality request")
);
const p: any = px;
if (p.length === 0) {
return {
success: false,

View File

@@ -53,9 +53,13 @@ export const qualityCycle = async () => {
"[runningNumber]",
lstQData[i].runningNr
);
let prodData: any = [];
prodData = await query(qPalletNumber, "Quality update check");
const queryData: any = await query(
qPalletNumber,
"Quality update check"
);
let prodData: any =
queryData?.data.length === 0 ? [] : queryData.data;
if (
lstQData[i]?.locationAtRequest != prodData[0]?.locationAtRequest

View File

@@ -164,6 +164,7 @@ export async function query(queryToRun: string, name: string) {
return {
success: false,
message: `The sql ${dbServer[0].value} is not not connected`,
data: [],
};
}
/**
@@ -178,7 +179,11 @@ export async function query(queryToRun: string, name: string) {
try {
const result = await pool.request().query(query);
return result.recordset;
return {
success: true,
message: `Query results for: ${name}`,
data: result.recordset,
};
} catch (error: any) {
if (error.code === "ETIMEOUT") {
createLog(
@@ -189,13 +194,23 @@ export async function query(queryToRun: string, name: string) {
error
)}, ${name} did not run due to a timeout.`
);
throw new Error(`${name} query did not run due to a timeout.`);
//throw new Error(`${name} query did not run due to a timeout.`);
return {
success: false,
message: `${name} query did not run due to a timeout.`,
data: [],
};
}
if (error.code === "EREQUEST") {
throw new Error(
`${name} encoutnered an error ${error.originalError.info.message}`
);
// throw new Error(
// `${name} encoutnered an error ${error.originalError.info.message}`
// );
return {
success: false,
message: `${name} encoutnered an error ${error.originalError.info.message}`,
data: [],
};
}
//console.log(error.originalError.info.message);