feat(lstv2 move): moved lstv2 into this app to keep them combined and easier to maintain

This commit is contained in:
2025-09-19 22:22:05 -05:00
parent caf2315191
commit e4477402ad
847 changed files with 165801 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
import { db } from "../../../../../database/dbclient.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { printerData } from "../../../../../database/schema/printers.js";
export const getPrinters = async () => {
const { data: printers, error: printerError } = await tryCatch(
db.select().from(printerData).orderBy(printerData.name)
);
if (printerError) {
return {
success: false,
message: "there was an error getting the printers",
data: printerError,
};
}
return { success: true, message: "Printers", data: printers };
};

View File

@@ -0,0 +1,113 @@
import { eq } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { settings } from "../../../../../database/schema/settings.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../logger/logger.js";
import { getPrinters } from "./getPrinters.js";
import { autoLabelingStats, printerStatus } from "./printerStatus.js";
let isPrinterCycling = false;
let actualPrinterCycle: any;
export const printerCycle = async () => {
/**
* We will cycle through the printers to check there states.
*/
if (isPrinterCycling)
return {
success: false,
message: "Printers are already being cycled.",
};
createLog("info", "ocp", "ocp", "Printer cycle has started.");
// get the printers
const { data: s, error: se } = await tryCatch(
db.select().from(settings).where(eq(settings.name, "ocpCycleDelay"))
);
if (se) {
createLog(
"error",
"ocp",
"ocp",
"There was an error getting the ocpCycleDelay."
);
return {
success: false,
message: "Error getting printers.",
};
}
const ocpDelay: any = s;
isPrinterCycling = true;
// start the actual printer cycle
actualPrinterCycle = setInterval(async () => {
const { data, error } = await tryCatch(getPrinters());
if (error) {
createLog(
"error",
"ocp",
"ocp",
"There was an error getting the printers."
);
return {
success: false,
message: "Error getting printers.",
};
}
let printers: any = data.data;
// only keep the assigned ones
printers = printers.filter((p: any) => p.assigned === true);
// for printers we want to ignore there must be a remark stateing to ignore.
printers = printers.filter((p: any) => !p.remark.includes("ignore"));
printers.forEach(async (p: any) => {
/**
* if the last timeprinted would be greater than x well just change the status to idle and extended based on the 2 times.
*
* to get a printer going again label will need to come from the front end as that will just unpause the printer and start the labeling, or the api for manual print
* well need to adjust this to actually print the label then unpause it.
*
* it will be
*
* less than x since time printed run the printer status
* greater than x but less than y change the status to idle, but ping to make sure its online,
* if greater than y change to extended idle but stil also ping to make sure its online.
*/
// ignore pdf printer as we want it here for testing purposes
if (p.name.toLowerCase() === "pdf24") {
return;
}
if (p.name === "Autolabeler") {
//await autoLabelingStats(p);
return;
}
// for all other printers
await printerStatus(p);
});
}, parseInt(ocpDelay[0]?.value) * 1000);
return { success: true, message: "Printer cycle has been started." };
};
export const stopPrinterCycle = async () => {
/**
* We will stop the print cylce this is more an emergancy thing.
*/
if (actualPrinterCycle && !actualPrinterCycle._destroyed) {
createLog("info", "ocp", "ocp", "Printer cycle is being stopped.");
clearInterval(actualPrinterCycle);
isPrinterCycling = false;
return { success: true, message: "Printer cycle has been stopped." };
} else {
createLog("info", "ocp", "ocp", "Printer cycle is already stopped.");
isPrinterCycling = false;
return { success: true, message: "Printer cycle is already Stopped." };
}
};

View File

@@ -0,0 +1,121 @@
import { eq } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { settings } from "../../../../../database/schema/settings.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../logger/logger.js";
import { getPrinters } from "./getPrinters.js";
import { autoLabelingStats } from "./printerStatus.js";
let isPrinterCycling = false;
let actualPrinterCycle: any;
export const printerCycleAutoLabelers = async () => {
/**
* Will only check the auto labelers for status updates.
*/
if (isPrinterCycling)
return {
success: false,
message: "Printers are already being cycled.",
};
createLog("info", "ocp", "ocp", "AutoLabeling cycle has started.");
// get the printers
const { data: s, error: se } = await tryCatch(
db.select().from(settings).where(eq(settings.name, "ocpCycleDelay"))
);
if (se) {
createLog(
"error",
"ocp",
"ocp",
"There was an error getting the ocpCycleDelay."
);
return {
success: false,
message: "Error getting printers.",
};
}
const ocpDelay: any = s;
isPrinterCycling = true;
// start the actual printer cycle
actualPrinterCycle = setInterval(async () => {
const { data, error } = await tryCatch(getPrinters());
if (error) {
createLog(
"error",
"ocp",
"ocp",
"There was an error getting the printers."
);
return {
success: false,
message: "Error getting printers.",
};
}
let printers: any = data.data;
// only keep the assigned ones
printers = printers.filter((p: any) => p.assigned === true);
// for printers we want to ignore there must be a remark stateing to ignore.
printers = printers.filter((p: any) => !p.remark.includes("ignore"));
printers.forEach(async (p: any) => {
/**
* if the last timeprinted would be greater than x well just change the status to idle and extended based on the 2 times.
*
* to get a printer going again label will need to come from the front end as that will just unpause the printer and start the labeling, or the api for manual print
* well need to adjust this to actually print the label then unpause it.
*
* it will be
*
* less than x since time printed run the printer status
* greater than x but less than y change the status to idle, but ping to make sure its online,
* if greater than y change to extended idle but stil also ping to make sure its online.
*/
// ignore pdf printer as we want it here for testing purposes
if (p.name.toLowerCase() === "pdf24") {
return;
}
if (p.name === "Autolabeler") {
await autoLabelingStats(p);
return;
}
});
}, parseInt(ocpDelay[0]?.value) * 2 * 1000);
return { success: true, message: "AutoLabeling cycle has been started." };
};
export const stopPrinterCycle = async () => {
/**
* We will stop the print cylce this is more an emergancy thing.
*/
if (actualPrinterCycle && !actualPrinterCycle._destroyed) {
createLog("info", "ocp", "ocp", "AutoLabeling cycle is being stopped.");
clearInterval(actualPrinterCycle);
isPrinterCycling = false;
return {
success: true,
message: "AutoLabeling cycle has been stopped.",
};
} else {
createLog(
"info",
"ocp",
"ocp",
"AutoLabeling cycle is already stopped."
);
isPrinterCycling = false;
return {
success: true,
message: "AutoLabeling cycle is already Stopped.",
};
}
};

View File

@@ -0,0 +1,66 @@
import { eq, sql } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { printerData } from "../../../../../database/schema/printers.js";
import { createLog } from "../../../logger/logger.js";
export const printStatus = [
{ code: 1, text: "Printing" },
{ code: 2, text: "Pending labels" },
{ code: 3, text: "Printing to fast" },
{ code: 4, text: "Creating label" },
{ code: 5, text: "Waiting" },
{ code: 6, text: "Printer Paused" },
{ code: 7, text: "Printer error" },
{
code: 8,
text: "First time printing",
},
{
code: 9,
text: "Offline",
},
];
export const printerUpdate = async (printer: any, status: any) => {
/**
* Updates the status of the printer.
*/
// get current time
let pd = {};
const currentTime = sql`NOW()`;
if (status === 3) {
pd = {
status: status,
statusText: printStatus.filter((c) => c.code === status)[0]?.text,
};
} else if (status === 6) {
pd = {
status: status,
statusText: printStatus.filter((c) => c.code === status)[0]?.text,
};
} else {
pd = {
lastTimePrinted: currentTime,
status: status,
statusText: printStatus.filter((c) => c.code === status)[0]?.text,
};
}
if (printer.humanReadableId) {
try {
await db
.update(printerData)
.set(pd)
.where(
eq(printerData.humanReadableId, printer.humanReadableId)
);
} catch (error) {
createLog("error", "ocp", "ocp", `Error updating printer state`);
}
}
// console.log(printerUpdate.name);
return;
};

View File

@@ -0,0 +1,285 @@
import net from "net";
import { pausePrinter } from "../../utils/pausePrinter.js";
import { addHours, differenceInSeconds } from "date-fns";
import { printerUpdate } from "./printerStatUpdate.js";
import { createLog } from "../../../logger/logger.js";
import { unPausePrinter } from "../../utils/unpausePrinter.js";
import { labelingProcess } from "../labeling/labelProcess.js";
import { timeZoneFix } from "../../../../globalUtils/timeZoneFix.js";
import { autoLabelCreated } from "../labeling/labelRatio.js";
let logLevel: string = process.env.LOG_LEVEL || "info";
let errorCheck = false;
export const printerStatus = async (p: any) => {
/**
* Checks each printer to see what the current state is
*/
createLog("debug", "ocp", "ocp", `Printer cycling`);
const printer = new net.Socket();
return new Promise((resolve) => {
// connect to the printer, and check its status
printer.connect(p.port, p.ipAddress, async () => {
// write the message to the printer below gives us a feedback of the printer
printer.write("~HS");
});
// read the data from the printer
printer.on("data", async (data) => {
const res = data.toString();
// turn the data into an array to make it more easy to deal with
const tmp = res.split(",");
//--------------- time stuff-----------------------------------------------------------------
// get last time printed
const lastTime = new Date(p.lastTimePrinted).toISOString();
// console.log(lastTime);
// current time?
/**
*
* add the time zone to the settings db
*/
// const currentTime = addHours(
// new Date(Date.now()),
// -6
// ).toISOString();
const currentTime = timeZoneFix();
let timeBetween = 0;
// if this is our first time printing pause the printer to start the timer, else we just update the time between timer
if (lastTime === undefined) {
printer.end();
printerUpdate(p, 8);
pausePrinter(p);
resolve({ success: true, message: "First Time printing" });
} else {
timeBetween = differenceInSeconds(currentTime, lastTime);
}
// --- end time ---
// --- printer logic ---
createLog(
"debug",
"ocp",
"ocp",
`${p.name}: timeBetween: ${timeBetween}, delay ${parseInt(
p.printDelay
)}, ${currentTime}... ${lastTime}`
);
if (tmp[2] === "0" && tmp[4] !== "000") {
// unpaused and printing labels - reset timer
createLog(
"debug",
"ocp",
"ocp",
`Unpaused and printing labels, time remaing ${differenceInSeconds(
parseInt(p.printDelay),
timeBetween
)}`
);
// update last time printed in the array
printerUpdate(p, 1);
} else if (tmp[2] === "1" && tmp[4] !== "000") {
// was paused or label sent from somewhere else
createLog(
"info",
"ocp",
"ocp",
`${
p.name
} paused to soon, unpausing, remaining time: ${differenceInSeconds(
parseInt(p.printDelay),
timeBetween
)}`
);
// reset the timer for this printer as well other labels shouldnt be sent but if we send them ok
printerUpdate(p, 2);
unPausePrinter(p);
} else if (tmp[2] === "0" && timeBetween < parseInt(p.printDelay)) {
// was unpaused to soon so repause it
createLog(
"debug",
"ocp",
"ocp",
`${p.name} Unpaused before the time allowed, time left ${
differenceInSeconds(parseInt(p.printDelay), timeBetween) //seconds
}`
);
printerUpdate(p, 3);
pausePrinter(p);
} else if (tmp[2] === "0" && timeBetween > parseInt(p.printDelay)) {
// its been long enough we can print a label
createLog(
"debug",
"ocp",
"ocp",
`${p.name} Allowed time passed and printing new label`
);
// update last time printed in the array
printerUpdate(p, 4);
// sending over for labeling.
labelingProcess({ printer: p });
autoLabelCreated();
} else if (tmp[2] === "0") {
// printer was unpaused for the first time or made it here
createLog(
"debug",
"ocp",
"ocp",
`${p.name} Frist time printing`
);
// add the time and printer
printerUpdate(p, 4);
// sending over for labeling.
labelingProcess({ printer: p });
autoLabelCreated();
} else if (tmp[2] === "1") {
// printer is paused and waiting
createLog(
"debug",
"ocp",
"ocp",
`${p.name} paused and waiting`
);
printerUpdate(p, 6);
}
printer.end();
resolve({ success: true, message: "Print cycle completed." });
});
// 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);
});
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.",
});
}
});
});
};
export const autoLabelingStats = async (p: any) => {
/**
* Checks autolabeling printers just to see what they are doing.
*/
createLog("debug", "ocp", "ocp", `Printer cycling`);
const printer = new net.Socket();
return new Promise((resolve) => {
// connect to the printer, and check its status
printer.connect(p.port, p.ipAddress, async () => {
// write the message to the printer below gives us a feedback of the printer
printer.write("~HS");
});
// read the data from the printer
printer.on("data", async (data) => {
const res = data.toString();
// turn the data into an array to make it more easy to deal with
const tmp = res.split(",");
if (tmp[4] !== "000") {
// unpaused and printing labels - reset timer
createLog("debug", "ocp", "ocp", `Printing Labels`);
// update last time printed in the array
printerUpdate(p, 1);
}
if (tmp[4] === "000") {
// unpaused and printing labels - reset timer
createLog("debug", "ocp", "ocp", `Printing Labels`);
// update last time printed in the array
printerUpdate(p, 5);
}
});
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}`
);
}
await printerUpdate(p, 7);
errorCheck = true;
// send log data
// fake line
printer.end();
resolve({
success: false,
message: "There was an error with the printer.",
});
});
});
};

View File

@@ -0,0 +1,89 @@
import axios from "axios";
import { printerData } from "../../../../../database/schema/printers.js";
import { sql } from "drizzle-orm";
import { prodEndpointCreation } from "../../../../globalUtils/createUrl.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { lstAuth } from "../../../../index.js";
import { db } from "../../../../../database/dbclient.js";
import { createLog } from "../../../logger/logger.js";
import { assignedPrinters } from "../../utils/checkAssignments.js";
export const updatePrinters = async () => {
const currentTime = new Date(Date.now());
// get the printers from prod
let url = await prodEndpointCreation(
"/public/v1.0/Administration/Printers"
);
const { data: prodPrinters, error: prodError } = await tryCatch(
axios.get(url, {
headers: {
Authorization: `Basic ${lstAuth}`,
"Content-Type": "application/json",
},
})
);
if (prodError || prodPrinters?.data.length > 10000) {
//console.log(prodError);
return {
success: false,
message: "there was an error getting the printers.",
data: prodError,
};
}
// do the printer update into our db
const prodPrinterInfo = prodPrinters?.data;
for (let i = 0; i < prodPrinterInfo.length; i++) {
const printerStuff: any = {
humanReadableId: prodPrinterInfo[i].humanReadableId,
name: prodPrinterInfo[i].name,
ipAddress: prodPrinterInfo[i].ipAddress,
port: prodPrinterInfo[i].port,
remark: prodPrinterInfo[i].remark,
processes: prodPrinterInfo[i].processes,
};
const { data, error } = await tryCatch(
db
.insert(printerData)
.values(printerStuff)
.onConflictDoUpdate({
target: printerData.humanReadableId,
set: {
//humanReadableId: prodPrinterInfo[i].humanReadableId,
name: prodPrinterInfo[i].name,
ipAddress: prodPrinterInfo[i].ipAddress,
port: prodPrinterInfo[i].port,
remark: prodPrinterInfo[i].remark,
processes: prodPrinterInfo[i].processes,
upd_date: sql`NOW()`,
//printDelay: "90", // need to remove in a couple weeks
},
})
);
if (error) {
createLog(
"error",
"lst",
"ocp",
`${
prodPrinterInfo[i].name
} encoutered and error adding/updating ${JSON.stringify(error)}`
);
}
createLog(
"debug",
"lst",
"ocp",
`${prodPrinterInfo[i].name} were just added/updated.`
);
}
await assignedPrinters();
return { success: true, message: "Printers were just added or updated." };
};