feat(labeling): added printers and machine and other data for preprinting

This commit is contained in:
2025-10-17 07:44:39 -05:00
parent c59b6a1ec2
commit 953af5e0fe
15 changed files with 1868 additions and 8 deletions

View File

@@ -7,5 +7,12 @@
"source.fixAll.biome": "explicit",
"source.organizeImports.biome": "explicit"
},
"cSpell.words": ["alpla", "alplamart", "alplaprod", "intiallally", "ppoo"]
"cSpell.words": [
"alpla",
"alplamart",
"alplaprod",
"intiallally",
"ppoo",
"prodlabels"
]
}

View File

@@ -18,7 +18,7 @@ body:json {
"printerId": 7, // 457=22, 458=23
"layoutId": 25,
"numberOfCopies": 0,
"qtyToPrint": 5
"qtyToPrint": 1
}
}

View File

@@ -1,5 +1,5 @@
vars {
url: https://usmcd1vms036.alpla.net
url: http://localhost:5500
session_cookie:
urlv2: http://usmcd1vms036:3000
jwtV2:

View File

@@ -8,10 +8,16 @@
* layout
*/
import { eq } from "drizzle-orm";
import type { Logger } from "pino";
import { db } from "../../../../pkg/db/db.js";
import { printers } from "../../../../pkg/db/schema/printers.js";
import { prodlabels } from "../../../../pkg/db/schema/prodLabels.js";
import { createLogger } from "../../../../pkg/logger/logger.js";
import { delay } from "../../../../pkg/utils/delay.js";
import { getMachineData } from "../../../../pkg/utils/getMachineInfo.js";
import { prodEndpoint } from "../../../../pkg/utils/prodEndpoint.js";
import type { returnFunc } from "../../../../pkg/utils/return.js";
import { tryCatch } from "../../../../pkg/utils/tryCatch.js";
export type Preprint = {
scannerId: number;
@@ -23,7 +29,49 @@ export type Preprint = {
qtyToPrint: number;
};
export const preprintLabels = async (preprint: Preprint) => {
const addProdLabel = async (
preprint: Preprint,
runningNr: number,
username: string,
log: Logger,
) => {
// get the printers
const printerName = await db
.select()
.from(printers)
.where(eq(printers.humanReadableId, preprint.printerId.toString()));
// get the machine data
const { data, error } = await tryCatch(getMachineData("all"));
if (error) {
log.error({ error: error }, "There was an error getting machine data");
}
const lineNumber = data.filter(
(n: any) => n.HumanReadableId === preprint.machineId,
);
const { data: prodLabel, error: prodLabelError } = await tryCatch(
db
.insert(prodlabels)
.values({
printerID: preprint.printerId,
printerName: printerName[0]?.name,
runningNr: runningNr,
status: "printed",
line: lineNumber[0]?.Location || 0,
add_user: username,
})
.onConflictDoNothing(),
);
if (prodLabelError) {
log.error({ error: error }, "Error adding the label");
}
};
export const preprintLabels = async (preprint: Preprint, username?: string) => {
const log = createLogger({
module: "logistics",
subModule: "preprint",
@@ -67,6 +115,13 @@ export const preprintLabels = async (preprint: Preprint) => {
};
}
labelsPrinted.push(parseInt(labels?.data.SSCC.slice(10, -1)));
// add the label to our label db for tracking purposes
addProdLabel(
preprint,
parseInt(labels?.data.SSCC.slice(10, -1)),
username || "lst",
log,
);
log.info(
{},
`Label just created ${parseInt(labels?.data.SSCC.slice(10, -1))} and printed, remaining to print ${preprint.qtyToPrint - x}`,
@@ -118,6 +173,12 @@ export const preprintLabels = async (preprint: Preprint) => {
}
labelsPrinted.push(parseInt(labels.data.SSCC.slice(10, -1)));
addProdLabel(
preprint,
parseInt(labels?.data.SSCC.slice(10, -1)),
username || "lst",
log,
);
log.info(
{},
`Label just created ${parseInt(labels.data.SSCC.slice(10, -1))} and printed`,

View File

@@ -1,8 +1,9 @@
import { Router } from "express";
import { requireAuth } from "../../../../pkg/middleware/authMiddleware.js";
import preprint from "./perprint.js";
const router = Router();
router.use("/", preprint);
router.use("/", requireAuth(), preprint);
export default router;

View File

@@ -17,7 +17,7 @@ const router = Router();
router.post("/preprint", async (req: Request, res: Response) => {
const parsed = Preprint.safeParse(req.body);
const print = await preprintLabels(req.body);
const print = await preprintLabels(req.body, req.user?.username || "");
res
.status(200)

View File

@@ -1 +1,7 @@
export const printers = () => {};
import { updatePrinters } from "./updatePrinters.js";
export const printers = () => {
setTimeout(() => {
updatePrinters();
}, 10 * 1000);
};

View File

@@ -0,0 +1,73 @@
import { sql } from "drizzle-orm";
import { db } from "../../../pkg/db/db.js";
import { printers } from "../../../pkg/db/schema/printers.js";
import { createLogger } from "../../../pkg/logger/logger.js";
import { prodEndpoint } from "../../../pkg/utils/prodEndpoint.js";
import { tryCatch } from "../../../pkg/utils/tryCatch.js";
export const updatePrinters = async () => {
const log = createLogger({
module: "ocp",
subModule: "update Printers",
});
const currentTime = new Date(Date.now());
const { data: prodPrinters, error: prodError } = await tryCatch(
prodEndpoint("GET", "/public/v1.0/Administration/Printers"),
);
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(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,
processes: prodPrinterInfo[i].processes,
upd_date: sql`NOW()`,
//printDelay: "90", // need to remove in a couple weeks
},
}),
);
if (error) {
log.error(
{ error: error },
`${
prodPrinterInfo[i].name
} encoutered and error adding/updating ${JSON.stringify(error)}`,
);
}
log.debug({}, `${prodPrinterInfo[i].name} were just added/updated.`);
}
//await assignedPrinters();
return { success: true, message: "Printers were just added or updated." };
};

View File

@@ -0,0 +1,34 @@
import {
boolean,
index,
jsonb,
numeric,
pgTable,
text,
timestamp,
uniqueIndex,
uuid,
} from "drizzle-orm/pg-core";
export const printers = pgTable(
"printers",
{
printer_id: uuid("printer_id").defaultRandom().primaryKey(),
humanReadableId: text("humanReadableId"),
name: text("name").notNull(),
ipAddress: text("ip_address"),
port: numeric("port"),
status: text("status"),
statusText: text("status_text"),
lastTimePrinted: timestamp("last_time_printed").notNull().defaultNow(),
assigned: boolean("assigned").default(false),
remark: text("remark"),
printDelay: numeric("print_delay").default("90"),
monitorState: boolean("monitor_state").default(false),
processes: jsonb("processes").default([]),
printDelayOverride: boolean("print_delay_override").default(false), // this will be more for if we have the lot time active but want to over ride this single line for some reason
add_Date: timestamp("add_Date").defaultNow(),
upd_date: timestamp("upd_date").defaultNow(),
},
(table) => [uniqueIndex("humanReadableId").on(table.humanReadableId)],
);

View File

@@ -0,0 +1,27 @@
import {
integer,
pgTable,
text,
timestamp,
uniqueIndex,
uuid,
} from "drizzle-orm/pg-core";
export const prodlabels = pgTable(
"prodlabels",
{
label_id: uuid("label_id").defaultRandom().primaryKey(),
printerID: integer("printerID"),
printerName: text("printerName"),
line: integer("line"),
runningNr: integer("runningNr").notNull(),
status: text("status"), // printed | bookedIn | delivered | booked out
add_user: text("add_user").default("lst"),
add_date: timestamp("add_date").defaultNow(),
upd_date: timestamp("upd_date").defaultNow(),
},
(table) => [
//uniqueIndex("emailUniqueIndex").on(sql`lower(${table.email})`),
uniqueIndex("runningNr").on(table.runningNr),
],
);

View File

@@ -0,0 +1,9 @@
export const machineCheck = `
SELECT [HumanReadableId]
,[Name]
,[Location]
,[Active]
,[ImportSource]
,[StagingMainMaterialMandatory]
FROM [test1_AlplaPROD2.0_Read].[masterData].[Machine] (nolock)
where Active = 1 and [Location] = [loc]`;

View File

@@ -0,0 +1,29 @@
import { createLogger } from "../logger/logger.js";
import { prodQuery } from "../prodSql/prodQuery.js";
import { machineCheck } from "../prodSql/querys/general/machineInfo.js";
export const getMachineData = async (machine: string) => {
const log = createLogger({
module: "logistics",
subModule: "preprint",
});
let updateQuery = machineCheck.replaceAll("[loc]", machine!);
if (machine === "all") {
updateQuery = machineCheck.replaceAll("and [Location] = [loc]", "");
}
// create blank lots in case there is an error and dose not work
let mac = [];
try {
const getMac: any = await prodQuery(updateQuery, "Machine id check");
mac = getMac.data;
// console.log("Machine data", mac); // removed due to swr being activated
} catch (err) {
log.error({ error: err }, `Error with Machine id Check query: ${err}`);
}
return mac;
};

View File

@@ -0,0 +1,33 @@
CREATE TABLE "printers" (
"printer_id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"humanReadableId" text,
"name" text NOT NULL,
"ip_address" text,
"port" numeric,
"status" text,
"status_text" text,
"last_time_printed" timestamp DEFAULT now() NOT NULL,
"assigned" boolean DEFAULT false,
"remark" text,
"print_delay" numeric DEFAULT '90',
"monitor_state" boolean DEFAULT false,
"processes" jsonb DEFAULT '[]'::jsonb,
"print_delay_override" boolean DEFAULT false,
"add_Date" timestamp DEFAULT now(),
"upd_date" timestamp DEFAULT now()
);
--> statement-breakpoint
CREATE TABLE "prodlabels" (
"label_id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"printerID" integer,
"printerName" text,
"line" integer,
"runningNr" integer NOT NULL,
"status" text,
"add_user" text DEFAULT 'lst',
"add_date" timestamp DEFAULT now(),
"upd_date" timestamp DEFAULT now()
);
--> statement-breakpoint
CREATE UNIQUE INDEX "humanReadableId" ON "printers" USING btree ("humanReadableId");--> statement-breakpoint
CREATE UNIQUE INDEX "runningNr" ON "prodlabels" USING btree ("runningNr");

File diff suppressed because it is too large Load Diff

View File

@@ -141,6 +141,13 @@
"when": 1760623729227,
"tag": "0019_bizarre_tarot",
"breakpoints": true
},
{
"idx": 20,
"version": "7",
"when": 1760703799708,
"tag": "0020_conscious_hairball",
"breakpoints": true
}
]
}