Compare commits

...

4 Commits

20 changed files with 5226 additions and 340 deletions

View File

@@ -0,0 +1,17 @@
CREATE TABLE "printers" (
"printer_id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"humanReadableId" text,
"name" text NOT NULL,
"ipAddress" text,
"port" numeric NOT NULL,
"status" text,
"statusText" text NOT NULL,
"lastTimePrinted" text,
"assigned" boolean DEFAULT false NOT NULL,
"remark" text,
"monitorState" boolean DEFAULT false NOT NULL,
"add_Date" timestamp DEFAULT now(),
"upd_date" timestamp DEFAULT now()
);
--> statement-breakpoint
CREATE UNIQUE INDEX "humanReadableId" ON "printers" USING btree ("name");

View File

@@ -0,0 +1,3 @@
ALTER TABLE "printers" ALTER COLUMN "statusText" DROP NOT NULL;--> statement-breakpoint
ALTER TABLE "printers" ALTER COLUMN "assigned" DROP NOT NULL;--> statement-breakpoint
ALTER TABLE "printers" ALTER COLUMN "monitorState" DROP NOT NULL;

View File

@@ -0,0 +1 @@
ALTER TABLE "printers" ALTER COLUMN "port" DROP NOT NULL;

View File

@@ -0,0 +1,2 @@
DROP INDEX "humanReadableId";--> statement-breakpoint
CREATE UNIQUE INDEX "humanReadableId" ON "printers" USING btree ("humanReadableId");

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -183,6 +183,34 @@
"when": 1742655504936, "when": 1742655504936,
"tag": "0025_amusing_sugar_man", "tag": "0025_amusing_sugar_man",
"breakpoints": true "breakpoints": true
},
{
"idx": 26,
"version": "7",
"when": 1742914066219,
"tag": "0026_daily_the_twelve",
"breakpoints": true
},
{
"idx": 27,
"version": "7",
"when": 1742917145140,
"tag": "0027_needy_sleepwalker",
"breakpoints": true
},
{
"idx": 28,
"version": "7",
"when": 1742917676211,
"tag": "0028_fast_wong",
"breakpoints": true
},
{
"idx": 29,
"version": "7",
"when": 1742917978318,
"tag": "0029_giant_blue_blade",
"breakpoints": true
} }
] ]
} }

View File

@@ -0,0 +1,42 @@
import {
text,
pgTable,
numeric,
index,
timestamp,
boolean,
uuid,
uniqueIndex,
} from "drizzle-orm/pg-core";
import { createInsertSchema, createSelectSchema } from "drizzle-zod";
import { z } from "zod";
export const printers = pgTable(
"printers",
{
printer_id: uuid("printer_id").defaultRandom().primaryKey(),
humanReadableId: text("humanReadableId"),
name: text("name").notNull(),
ipAddress: text("ipAddress"),
port: numeric("port"),
status: text("status"),
statusText: text("statusText"),
lastTimePrinted: text("lastTimePrinted"),
assigned: boolean("assigned").default(false),
remark: text("remark"),
monitorState: boolean("monitorState").default(false),
add_Date: timestamp("add_Date").defaultNow(),
upd_date: timestamp("upd_date").defaultNow(),
},
(table) => [
//uniqueIndex("emailUniqueIndex").on(sql`lower(${table.email})`),
uniqueIndex("humanReadableId").on(table.humanReadableId),
]
);
// Schema for inserting a user - can be used to validate API requests
// export const insertRolesSchema = createInsertSchema(roles, {
// name: z.string().min(3, {message: "Role name must be more than 3 letters"}),
// });
// Schema for selecting a Expenses - can be used to validate API responses
export const selectRolesSchema = createSelectSchema(printers);

View File

@@ -1,12 +1,12 @@
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
import { serve } from "@hono/node-server"; import { serve } from "@hono/node-server";
import { OpenAPIHono } from "@hono/zod-openapi"; import { OpenAPIHono } from "@hono/zod-openapi";
import { proxy } from "hono/proxy";
import { serveStatic } from "@hono/node-server/serve-static"; import { serveStatic } from "@hono/node-server/serve-static";
import { logger } from "hono/logger"; import { logger } from "hono/logger";
import { cors } from "hono/cors"; import { cors } from "hono/cors";
import { createLog } from "./services/logger/logger.js"; import { createLog } from "./services/logger/logger.js";
import { WebSocketServer } from "ws";
// custom routes // custom routes
import scalar from "./services/general/route/scalar.js"; import scalar from "./services/general/route/scalar.js";
import system from "./services/server/systemServer.js"; import system from "./services/server/systemServer.js";

View File

@@ -4,26 +4,12 @@ import { db } from "../../database/dbclient.js";
import { serverData } from "../../database/schema/serverData.js"; import { serverData } from "../../database/schema/serverData.js";
import { eq, sql } from "drizzle-orm"; import { eq, sql } from "drizzle-orm";
import { createLog } from "../services/logger/logger.js"; import { createLog } from "../services/logger/logger.js";
import { spawn } from "child_process";
import { getAppInfo } from "../globalUtils/appInfo.js";
import { db } from "../../database/dbclient.js";
import { serverData } from "../../database/schema/serverData.js";
import { eq, sql } from "drizzle-orm";
import { createLog } from "../services/logger/logger.js";
type UpdateServerResponse = { type UpdateServerResponse = {
success: boolean; success: boolean;
message: string; message: string;
success: boolean;
message: string;
}; };
export const updateServer = async (
devApp: string,
server: string | null
): Promise<UpdateServerResponse> => {
const app = await getAppInfo(devApp);
const serverInfo = await db
export const updateServer = async ( export const updateServer = async (
devApp: string, devApp: string,
server: string | null server: string | null
@@ -47,32 +33,7 @@ export const updateServer = async (
"Looks like you are missing the plant token or have entered an incorrect one please try again.", "Looks like you are missing the plant token or have entered an incorrect one please try again.",
}; };
} }
if (serverInfo.length === 0) {
createLog(
"error",
"lst",
"serverUpdater",
`Looks like you are missing the plant token or have entered an incorrect one please try again.`
);
return {
success: false,
message:
"Looks like you are missing the plant token or have entered an incorrect one please try again.",
};
}
if (serverInfo[0].isUpgrading) {
createLog(
"error",
"lst",
"serverUpdater",
`Looks like ${serverInfo[0].plantToken} is upgrading already you cant do this again.`
);
return {
success: false,
message: `Looks like ${serverInfo[0].plantToken} is upgrading already you cant do this again.`,
};
}
if (serverInfo[0].isUpgrading) { if (serverInfo[0].isUpgrading) {
createLog( createLog(
"error", "error",
@@ -116,15 +77,6 @@ export const updateServer = async (
, ,
]; ];
return new Promise(async (resolve, reject) => {
const process = spawn("powershell", args);
// change the server to upgradeing
await db
.update(serverData)
.set({ isUpgrading: true })
.where(eq(serverData.plantToken, server?.toLowerCase() ?? ""));
//let stdout = "";
//let stderr = "";
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
const process = spawn("powershell", args); const process = spawn("powershell", args);
// change the server to upgradeing // change the server to upgradeing
@@ -135,12 +87,6 @@ export const updateServer = async (
//let stdout = ""; //let stdout = "";
//let stderr = ""; //let stderr = "";
// Collect stdout data
process.stdout.on("data", (data) => {
const output = data.toString().trim();
createLog("info", "lst", "serverUpdater", `${output}`);
//onData(output);
});
// Collect stdout data // Collect stdout data
process.stdout.on("data", (data) => { process.stdout.on("data", (data) => {
const output = data.toString().trim(); const output = data.toString().trim();
@@ -148,12 +94,6 @@ export const updateServer = async (
//onData(output); //onData(output);
}); });
// Collect stderr data
process.stderr.on("data", (data) => {
const output = data.toString().trim();
createLog("info", "lst", "serverUpdater", `${output}`);
//onData(output);
});
// Collect stderr data // Collect stderr data
process.stderr.on("data", (data) => { process.stderr.on("data", (data) => {
const output = data.toString().trim(); const output = data.toString().trim();
@@ -161,13 +101,6 @@ export const updateServer = async (
//onData(output); //onData(output);
}); });
// Handle process close
process.on("close", async (code) => {
if (code === 0) {
// if (count >= servers) {
// //onClose(`Server completed with code: ${code}`);
// }
createLog("info", "lst", "serverUpdater", `${server}`);
// Handle process close // Handle process close
process.on("close", async (code) => { process.on("close", async (code) => {
if (code === 0) { if (code === 0) {
@@ -181,27 +114,12 @@ export const updateServer = async (
await db await db
.update(serverData) .update(serverData)
.set({ lastUpdated: sql`NOW()`, isUpgrading: false }) .set({ lastUpdated: sql`NOW()`, isUpgrading: false })
.where(eq(serverData.plantToken, server?.toLowerCase() ?? "")); .where(
createLog( eq(
"info", serverData.plantToken,
"lst", server?.toLowerCase() ?? ""
"serverUpdater", )
`${server?.toLowerCase()}, has been updated and can now be used again.`
); );
} catch (error) {
createLog(
"error",
"lst",
"serverUpdater",
`There was an error updating the last time the server was updated: ${error}`
);
}
//update the last build.
try {
await db
.update(serverData)
.set({ lastUpdated: sql`NOW()`, isUpgrading: false })
.where(eq(serverData.plantToken, server?.toLowerCase() ?? ""));
createLog( createLog(
"info", "info",
"lst", "lst",
@@ -217,12 +135,6 @@ export const updateServer = async (
); );
} }
resolve({
success: true,
message: `${server?.toLowerCase()}, has been updated and can now be used again.`,
});
} else {
const errorMessage = `Process exited with code ${code}`;
resolve({ resolve({
success: true, success: true,
message: `${server?.toLowerCase()}, has been updated and can now be used again.`, message: `${server?.toLowerCase()}, has been updated and can now be used again.`,
@@ -230,9 +142,6 @@ export const updateServer = async (
} else { } else {
const errorMessage = `Process exited with code ${code}`; const errorMessage = `Process exited with code ${code}`;
// if (count >= servers) {
// //onClose(code);
// }
// if (count >= servers) { // if (count >= servers) {
// //onClose(code); // //onClose(code);
// } // }
@@ -243,12 +152,6 @@ export const updateServer = async (
}); });
} }
}); });
reject({
success: false,
message: `${server?.toLowerCase()}, Has encounted an error while updating.`,
});
}
});
// Handle errors with the process itself // Handle errors with the process itself
process.on("error", (error) => { process.on("error", (error) => {
@@ -257,18 +160,10 @@ export const updateServer = async (
reject(error); reject(error);
}); });
}); });
// Handle errors with the process itself
process.on("error", (error) => {
//onError(err.message);
createLog("error", "lst", "serverUpdater", `${error}`);
reject(error);
});
});
}; };
export async function processAllServers(devApp: string) { export async function processAllServers(devApp: string) {
const servers = await db.select().from(serverData); const servers = await db.select().from(serverData);
const servers = await db.select().from(serverData);
createLog( createLog(
"info", "info",
@@ -279,20 +174,16 @@ export async function processAllServers(devApp: string) {
let count = 1; let count = 1;
for (const server of servers) { for (const server of servers) {
try { try {
const updateToServer = await updateServer(devApp, server.plantToken); const updateToServer = await updateServer(
createLog("info", "lst", "serverUpdater", `${server.sName} was updated.`); devApp,
count = count + 1; server.plantToken
);
createLog( createLog(
"info", "info",
"lst", "lst",
"serverUpdater", "serverUpdater",
`Running the update on all servers` `${server.sName} was updated.`
); );
let count = 1;
for (const server of servers) {
try {
const updateToServer = await updateServer(devApp, server.plantToken);
createLog("info", "lst", "serverUpdater", `${server.sName} was updated.`);
count = count + 1; count = count + 1;
//return {success: true, message: `${server.sName} was updated.`, data: updateToServer}; //return {success: true, message: `${server.sName} was updated.`, data: updateToServer};
@@ -306,15 +197,4 @@ export async function processAllServers(devApp: string) {
//return {success: false, message: `Error updating ${server.sName}: ${error.message}`}; //return {success: false, message: `Error updating ${server.sName}: ${error.message}`};
} }
} }
//return {success: true, message: `${server.sName} was updated.`, data: updateToServer};
} catch (error: any) {
createLog(
"info",
"lst",
"serverUpdater",
`Error updating ${server.sName}: ${error.message}`
);
//return {success: false, message: `Error updating ${server.sName}: ${error.message}`};
}
}
} }

View File

@@ -4,12 +4,6 @@ import { createSSCC } from "../../../globalUtils/createSSCC.js";
import { createLog } from "../../logger/logger.js"; import { createLog } from "../../logger/logger.js";
import { query } from "../../sqlServer/prodSqlServer.js"; import { query } from "../../sqlServer/prodSqlServer.js";
import { labelData } from "../../sqlServer/querys/materialHelpers/labelInfo.js"; import { labelData } from "../../sqlServer/querys/materialHelpers/labelInfo.js";
import { db } from "../../../../database/dbclient.js";
import { ocmeData } from "../../../../database/schema/ocme.js";
import { createSSCC } from "../../../globalUtils/createSSCC.js";
import { createLog } from "../../logger/logger.js";
import { query } from "../../sqlServer/prodSqlServer.js";
import { labelData } from "../../sqlServer/querys/materialHelpers/labelInfo.js";
export const postLabelData = async (data: any) => { export const postLabelData = async (data: any) => {
console.log(data); console.log(data);

View File

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

View File

@@ -1,20 +1,44 @@
import { db } from "../../../../database/dbclient.js"; import { db } from "../../../../database/dbclient.js";
import { manualPrinting } from "../../../../database/schema/ocpManualPrint.js"; import { manualPrinting } from "../../../../database/schema/ocpManualPrint.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
export const manualPrint = async (data: any) => { export const manualPrint = async (manualPrint: any) => {
/** /**
* add the reason we did a manual print. * add the reason we did a manual print.
*/ */
const manualPrintData = { const manualPrintData = {
line: data.line, line: manualPrint.line,
printReason: data.printReason, printReason: manualPrint.printReason,
initials: data.initials, initials: manualPrint.initials,
additionalComments: data?.additionalComments, additionalComments: manualPrint?.additionalComments,
add_user: "lst", add_user: "lst",
}; };
try { const { data, error } = await tryCatch(
const manualPrint = await db.insert(manualPrinting).values(manualPrintData); db
} catch (error) {} .insert(manualPrinting)
.values(manualPrintData)
.returning({
line: manualPrinting.line,
printReason: manualPrinting.printReason,
initials: manualPrinting.initials,
additionalComments: manualPrinting?.additionalComments,
add_user: manualPrinting.add_user,
})
);
if (error) {
return {
success: false,
message: "There was an error posting the manualPrintData",
data: error,
};
}
return {
success: true,
message: "There was an error posting the manualPrintData",
data,
};
}; };

View File

@@ -0,0 +1,84 @@
import { db } from "../../../../database/dbclient.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { printers } from "../../../../database/schema/printers.js";
import { settings } from "../../../../database/schema/settings.js";
import axios from "axios";
import { lstAuth } from "../../../index.js";
import { prodEndpointCreation } from "../../../globalUtils/createUrl.js";
import { createLog } from "../../logger/logger.js";
import { sql } from "drizzle-orm";
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) {
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,
};
const { data, error } = await tryCatch(
db
.insert(printers)
.values(printerStuff)
.onConflictDoUpdate({
target: printers.humanReadableId,
set: {
//humanReadableId: prodPrinterInfo[i].humanReadableId,
name: prodPrinterInfo[i].name,
ipAddress: prodPrinterInfo[i].ipAddress,
port: prodPrinterInfo[i].port,
remark: prodPrinterInfo[i].remark,
upd_date: sql`NOW()`,
},
})
);
if (error) {
createLog(
"error",
"lst",
"ocp",
`${
prodPrinterInfo[i].name
} encoutered and error adding/updating ${JSON.stringify(error)}`
);
}
createLog(
"info",
"lst",
"ocp",
`${prodPrinterInfo[i].name} were just added/updated.`
);
}
return { success: true, message: "Printers were just added or updated." };
};

View File

@@ -2,13 +2,20 @@ import {OpenAPIHono} from "@hono/zod-openapi";
// routes // routes
import manualLabelLog from "./routes/manualPrintLog.js"; import manualLabelLog from "./routes/manualPrintLog.js";
import getPrinters from "./routes/printers/getPritners.js";
import { db } from "../../../database/dbclient.js"; import { db } from "../../../database/dbclient.js";
import { settings } from "../../../database/schema/settings.js"; import { settings } from "../../../database/schema/settings.js";
import updateprinters from "./routes/printers/updatePrinters.js";
import { updatePrinters } from "./controller/updatePrinters.js";
const app = new OpenAPIHono(); const app = new OpenAPIHono();
const routes = [manualLabelLog] as const; const routes = [
manualLabelLog,
//printer
getPrinters,
updateprinters,
] as const;
const setting = await db.select().from(settings); const setting = await db.select().from(settings);
const appRoutes = routes.forEach((route) => { const appRoutes = routes.forEach((route) => {
@@ -16,7 +23,13 @@ const appRoutes = routes.forEach((route) => {
}); });
app.all("/ocp/*", (c) => { app.all("/ocp/*", (c) => {
return c.json({success: false, message: "You have encounters a ocp route that dose not exist."}); return c.json({
success: false,
message: "You have encounters a ocp route that dose not exist.",
});
}); });
// run the printer update on restart just to keep everything good
updatePrinters();
export default app; export default app;

View File

@@ -12,7 +12,10 @@ const CreateLog = z.object({
line: z.string().openapi({ example: "info" }), line: z.string().openapi({ example: "info" }),
initials: z.string().openapi({ example: "server" }), initials: z.string().openapi({ example: "server" }),
printReason: z.string().openapi({ example: "This is a new log posted" }), printReason: z.string().openapi({ example: "This is a new log posted" }),
additionalComments: z.string().optional().openapi({example: "Some reason why we did this."}), additionalComments: z
.string()
.optional()
.openapi({ example: "Some reason why we did this." }),
}); });
app.openapi( app.openapi(
@@ -31,25 +34,26 @@ app.openapi(
async (c) => { async (c) => {
const body = await c.req.json(); const body = await c.req.json();
apiHit(c, { endpoint: `api/logger/logs/id` }); apiHit(c, { endpoint: `api/logger/logs/id` });
// const authHeader = c.req.header("Authorization");
// const token = authHeader?.split("Bearer ")[1] || "";
// let user: User;
// try {
// const payload = await verify(token, process.env.JWT_SECRET!);
// user = payload.user as User;
// } catch (error) {
// console.log(error);
// return c.json({message: "Unauthorized"}, 401);
// }
try { try {
//const data = {...body, add_user: user.username}; //const data = {...body, add_user: user.username};
await manualPrint(body); const printLog: any = await manualPrint(body);
return c.json({success: true, message: "Manual Print was added.", data: []}, 200); return c.json(
{
success: printLog.success,
message: printLog.message,
data: printLog.data ?? [],
},
200
);
} catch (error) { } catch (error) {
return c.json({success: false, message: "There was an error clearing the log.", data: error}, 400); return c.json(
{
success: false,
message: "There was an error clearing the log.",
data: error,
},
400
);
} }
} }
); );

View File

@@ -0,0 +1,50 @@
// an external way to creating logs
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { getPrinters } from "../../controller/getPrinters.js";
const app = new OpenAPIHono({ strict: false });
const CreateLog = z.object({
line: z.string().openapi({ example: "info" }),
initials: z.string().openapi({ example: "server" }),
printReason: z.string().openapi({ example: "This is a new log posted" }),
additionalComments: z
.string()
.optional()
.openapi({ example: "Some reason why we did this." }),
});
app.openapi(
createRoute({
tags: ["ocp"],
summary: "Prints a label.",
method: "get",
path: "/getprinters",
//middleware: authMiddleware,
//description: "This might be a temp soltuin during the transtion between versions",
request: {
body: { content: { "application/json": { schema: CreateLog } } },
},
responses: responses(),
}),
async (c) => {
const { data: printData, error: printError } = await tryCatch(
getPrinters()
);
if (printError) {
return c.json({
success: false,
message: "There was an error getting the printers",
});
}
return c.json({
success: printData.success,
message: printData.message,
data: printData.data,
});
}
);
export default app;

View File

@@ -0,0 +1,51 @@
// an external way to creating logs
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { getPrinters } from "../../controller/getPrinters.js";
import { updatePrinters } from "../../controller/updatePrinters.js";
const app = new OpenAPIHono({ strict: false });
const CreateLog = z.object({
line: z.string().openapi({ example: "info" }),
initials: z.string().openapi({ example: "server" }),
printReason: z.string().openapi({ example: "This is a new log posted" }),
additionalComments: z
.string()
.optional()
.openapi({ example: "Some reason why we did this." }),
});
app.openapi(
createRoute({
tags: ["ocp"],
summary: "Prints a label.",
method: "get",
path: "/updateprinters",
//middleware: authMiddleware,
//description: "This might be a temp soltuin during the transtion between versions",
request: {
body: { content: { "application/json": { schema: CreateLog } } },
},
responses: responses(),
}),
async (c) => {
const { data: printData, error: printError } = await tryCatch(
updatePrinters()
);
if (printError) {
return c.json({
success: false,
message: "There was an error getting the printers",
});
}
return c.json({
success: printData.success,
message: printData.message,
data: printData.data,
});
}
);
export default app;