refactor(ocp): change the way logs are brought in and other changes to clean the code up

This commit is contained in:
2025-04-09 17:49:03 -05:00
parent bad390ec17
commit 2e2699ab3c
20 changed files with 307 additions and 124 deletions

View File

@@ -12,23 +12,28 @@ import {
TableRow,
} from "../ui/table";
import { toast } from "sonner";
import { getOcmeInfo } from "@/utils/querys/production/getOcmeInfo";
import { useQuery } from "@tanstack/react-query";
import { format } from "date-fns";
import { Trash } from "lucide-react";
const currentPallets = [
{ key: "line", label: "Line" },
{ key: "runningNr", label: "Running #" },
{ key: "runningNumber", label: "Running #" },
{ key: "upd_date", label: "Date Scanned" },
{ key: "waitingfor", label: "Waiting For" },
{ key: "clear", label: "Clear" },
];
const currentTags = [
{ key: "line", label: "Line" },
{ key: "printerName", label: "Printer" },
{ key: "runningNr", label: "Running #" },
{ key: "upd_date", label: "Label date" },
{ key: "status", label: "Label Status" },
];
// const currentTags = [
// { key: "line", label: "Line" },
// { key: "printerName", label: "Printer" },
// { key: "runningNr", label: "Running #" },
// { key: "upd_date", label: "Label date" },
// { key: "status", label: "Label Status" },
// ];
export default function WrapperManualTrigger() {
const { data, isError, isLoading } = useQuery(getOcmeInfo());
const cameraTrigger = async () => {
try {
const res = await axios.get("/ocme/api/v1/manualCameraTrigger");
@@ -46,6 +51,42 @@ export default function WrapperManualTrigger() {
//stoast.success(error.data.message);
}
};
const clearLabel = async (d: any) => {
const data = {
runningNr: d.runningNr,
};
try {
const res = await axios.patch("/ocme/api/v1/pickedUp", data);
if (res.data.success) {
toast.success(
`${d.runningNr} was just removed from being picked up.`
);
return;
}
if (!res.data.success) {
toast.error(res.data.message);
}
} catch (error) {
console.log(error);
//stoast.success(error.data.message);
}
};
if (isError) {
return (
<div>
<p className="text-center text-pretty">
There was an error getting wrapper scans
</p>
</div>
);
}
const info = data?.filter((r: any) => r.areaFrom === "wrapper_1");
return (
<LstCard className="m-2 p-2">
<ScrollArea className="max-h-[200px]">
@@ -59,71 +100,66 @@ export default function WrapperManualTrigger() {
))}
</TableRow>
</TableHeader>
<TableBody>
{Array(3)
.fill(0)
.map((_, i) => (
<TableRow key={i}>
{isLoading ? (
<TableBody>
{Array(3)
.fill(0)
.map((_, i) => (
<TableRow key={i}>
<TableCell className="font-medium">
<Skeleton className="h-4" />
</TableCell>
<TableCell>
<Skeleton className="h-4" />
</TableCell>
<TableCell>
<Skeleton className="h-4" />
</TableCell>
<TableCell>
<Skeleton className="h-4" />
</TableCell>
<TableCell>
<Skeleton className="h-4" />
</TableCell>
</TableRow>
))}
</TableBody>
) : (
<TableBody>
{info.map((i: any) => (
<TableRow key={i.runningNr}>
<TableCell className="font-medium">
<Skeleton className="h-4" />
{i.lineNum}
</TableCell>
<TableCell>{i.runningNr}</TableCell>
<TableCell>
<Skeleton className="h-4" />
{format(
i?.upd_date.replace("Z", ""),
"M/d/yyyy hh:mm"
)}
</TableCell>
<TableCell>{i.waitingFor}</TableCell>
<TableCell>
<Skeleton className="h-4" />
</TableCell>
<TableCell>
<Skeleton className="h-4" />
</TableCell>
<TableCell>
<Skeleton className="h-4" />
<Button
variant="destructive"
size="icon"
onClick={() => clearLabel(i)}
>
<Trash />
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</ScrollArea>
<ScrollArea className="max-h-[200px]">
<Table>
<TableHeader>
<TableRow>
{currentTags.map((l) => (
<TableHead key={l.key}>{l.label}</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{Array(3)
.fill(0)
.map((_, i) => (
<TableRow key={i}>
<TableCell className="font-medium">
<Skeleton className="h-4" />
</TableCell>
<TableCell>
<Skeleton className="h-4" />
</TableCell>
<TableCell>
<Skeleton className="h-4" />
</TableCell>
<TableCell>
<Skeleton className="h-4" />
</TableCell>
<TableCell>
<Skeleton className="h-4" />
</TableCell>
</TableRow>
))}
</TableBody>
</TableBody>
)}
</Table>
</ScrollArea>
<div>
<hr />
<p className="text-center mb-3">Manual Triggers</p>
<p className="text-center mb-3">Manual Trigger</p>
<div className="flex flex-row justify-between">
<Button onClick={cameraTrigger}>Camera</Button>
<Button>Rfid</Button>
</div>
</div>
</LstCard>

View File

@@ -184,7 +184,7 @@ export default function OcmeCycleCount() {
{data.map((i: any) => {
let classname = ``;
if (
i.info === "Quality Check Required"
i.info === "Validate pallet is ok."
) {
classname = `bg-red-500`;
}

View File

@@ -5,7 +5,6 @@ import {
Table,
TableBody,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
@@ -26,17 +25,13 @@ const labelLogs = [
];
export default function LabelLog() {
const { data, isError, isLoading } = useQuery(getlabels("4"));
//const {user} = useSessionStore();
//const {settings} = useSettingStore();
//const server = settings.filter((n) => n.name === "server")[0]?.value || "";
//const roles = ["admin", "manager", "operator"];
if (isError) {
return (
<div className="m-2 p-2 min-h-2/5">
<LstCard>
<p className="text-center">Labels for the last 2 hours</p>
<Table>
<TableHeader>
<TableRow>
@@ -77,7 +72,13 @@ export default function LabelLog() {
const labelData = data ? data : [];
return (
<LstCard className="m-2 p-2 min-h-2/5">
<p className="text-center">Labels for the last 2 hours</p>
<p className="text-center">
{labelData.length === 0 ? (
<span>No labels have been printed in the last 2 hours</span>
) : (
<span>Labels for the last 2 hours</span>
)}
</p>
<Table>
<TableHeader>
<TableRow>
@@ -115,7 +116,7 @@ export default function LabelLog() {
) : (
<TableBody>
{labelData.map((label: any) => (
<TableRow key={label.runningNr}>
<TableRow key={label.label_id}>
<TableCell className="font-medium">
{label.line}
</TableCell>
@@ -139,15 +140,15 @@ export default function LabelLog() {
</TableBody>
)}
<TableFooter>
{/* <TableFooter>
{labelData.length === 0 && (
<div>
<div className="flex justify-center">
<h2 className="text-center text-2xl">
No labels have been printed in the last 2 hours
</h2>
</div>
)}
</TableFooter>
</TableFooter> */}
</Table>
</LstCard>
);

View File

@@ -1,31 +1,43 @@
import {Button} from "@/components/ui/button";
import {useSessionStore} from "@/lib/store/sessionStore";
import { Button } from "@/components/ui/button";
import { useSessionStore } from "@/lib/store/sessionStore";
//import {useSettingStore} from "@/lib/store/useSettings";
import {LotType} from "@/types/lots";
import {Tag} from "lucide-react";
import {toast} from "sonner";
import {manualPrintLabels} from "./ManualPrintLabel";
import { LotType } from "@/types/lots";
import { Tag } from "lucide-react";
import { toast } from "sonner";
import { manualPrintLabels } from "./ManualPrintLabel";
import { useState } from "react";
export default function ManualPrint({lot}: {lot: LotType}) {
const {user} = useSessionStore();
export default function ManualPrint({ lot }: { lot: LotType }) {
const { user } = useSessionStore();
const [printing, setPrinting] = useState(false);
//const {settings} = useSettingStore();
//const server = settings.filter((n) => n.name === "server")[0]?.value;
//const serverPort = settings.filter((n) => n.name === "serverPort")[0]?.value;
//const serverUrl = `http://${server}:${serverPort}`;
const handlePrintLabel = async (lot: LotType) => {
//console.log(lot);
const labels: any = await manualPrintLabels(lot, user);
if (labels.success) {
toast.success(labels.message);
setTimeout(() => {
setPrinting(false);
}, 5 * 1000);
setPrinting(true);
} else {
toast.error(labels.message);
setTimeout(() => {
setPrinting(false);
}, 5 * 1000);
}
};
return (
<Button variant="outline" size="icon" onClick={() => handlePrintLabel(lot)}>
<Button
variant="outline"
size="icon"
onClick={() => handlePrintLabel(lot)}
disabled={printing}
>
<Tag className="h-[16px] w-[16px]" />
</Button>
);

View File

@@ -86,7 +86,13 @@ export default function OcpLogs() {
return (
<LstCard className="m-2 p-2 min-h-2/5">
<p className="text-center">Labels for the last 2 hours</p>
<p className="text-center">
{data?.length === 0 ? (
<span>No errors in the last 4 hours</span>
) : (
<span>Logs for the last 4 hours</span>
)}
</p>
<Table>
<TableHeader>
<TableRow>

View File

@@ -1,19 +1,19 @@
import WrapperManualTrigger from "@/components/ocme/WrapperCard";
import LabelLog from "./LabelLog";
import Lots from "./Lots";
import OcpLogs from "./OcpLogs";
import PrinterStatus from "./PrinterStatus";
import { useSettingStore } from "@/lib/store/useSettings";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import LabelLog from "./LabelLog";
export default function OCPPage() {
const { settings } = useSettingStore();
const server = settings.filter((n) => n.plantToken === "usday1");
console.log(server);
let server = settings.filter((n) => n.name === "server");
return (
<div className="h-screen w-full ">
<div className="flex flex-wrap gap-2">
<div className="flex flex-row gap-2">
<div className="flex flex-col w-4/5 h-dvh">
<div className="">
<Lots />
@@ -33,15 +33,18 @@ export default function OCPPage() {
</div>
</TabsContent>
<TabsContent value="labels">
<div className="w-full">
<LabelLog />
</div>
<LabelLog />
</TabsContent>
</Tabs>
</div>
</div>
<div className="w-1/6 flex flex-col">
{server.length >= 1 && (
<div className="flex flex-col">
{server[0].value === "usday1vms006" && (
<div>
<WrapperManualTrigger />
</div>
)}
{server[0].value === "localhost" && (
<div>
<WrapperManualTrigger />
</div>

View File

@@ -81,7 +81,7 @@ export default function PrinterStatus() {
<TableHead key={l.key}>{l.label}</TableHead>
))}
</TableRow>
</TableHeader>{" "}
</TableHeader>
{isLoading ? (
<TableBody>
{Array(5)

View File

@@ -0,0 +1,19 @@
import { queryOptions } from "@tanstack/react-query";
import axios from "axios";
export function getOcmeInfo() {
return queryOptions({
queryKey: ["ocmeInfo"],
queryFn: () => fetchSettings(),
staleTime: 1000,
refetchInterval: 2 * 2000,
refetchOnWindowFocus: true,
});
}
const fetchSettings = async () => {
const { data } = await axios.get(`/ocme/api/v1/getInfo`);
// if we are not localhost ignore the devDir setting.
//const url: string = window.location.host.split(":")[0];
return data.data ?? [];
};

View File

@@ -6,7 +6,7 @@ export function getlabels(hours: string) {
queryKey: ["labels"],
queryFn: () => fetchSettings(hours),
staleTime: 1000,
//staleTime: 1000,
refetchInterval: 2 * 2000,
refetchOnWindowFocus: true,
});

View File

@@ -14,7 +14,7 @@ export function getOcpLogs(hours: string) {
const fetchSettings = async (hours: string) => {
const { data } = await axios.get(
`/api/logger/logs?service=ocp&service=rfid&level=error&level=warn&hours=${hours}`
`/api/logger/logs?service=ocp&service=rfid&service=dyco&level=error&level=warn&hours=${hours}`
);
// if we are not localhost ignore the devDir setting.
//const url: string = window.location.host.split(":")[0];

View File

@@ -1,7 +1,7 @@
import {eq, sql} from "drizzle-orm";
import {db} from "../../../../database/dbclient.js";
import {logs} from "../../../../database/schema/logs.js";
import {createLog} from "../logger.js";
import { eq, sql } from "drizzle-orm";
import { db } from "../../../../database/dbclient.js";
import { logs } from "../../../../database/schema/logs.js";
import { createLog } from "../logger.js";
export const clearLog = async (id: string) => {
/**
@@ -10,13 +10,21 @@ export const clearLog = async (id: string) => {
try {
const clear = await db
.update(logs)
.set({checked: true, checkedAt: sql`NOW()`})
.where(eq(logs.log_id, id));
.update(logs)
.set({ checked: true, created_at: sql`NOW()` })
.where(eq(logs.log_id, id));
createLog("info", "lst", "logger", "Log just cleared.");
return {success: true, message: "Log was just cleared."};
return { success: true, message: "Log was just cleared." };
} catch (error) {
createLog("error", "lst", "logger", "There was an error clearing the log.");
return {success: false, message: "There was an error clearing the log."};
createLog(
"error",
"lst",
"logger",
"There was an error clearing the log."
);
return {
success: false,
message: "There was an error clearing the log.",
};
}
};

View File

@@ -1,4 +1,4 @@
import { and, eq, gte, inArray, lte, sql } from "drizzle-orm";
import { and, desc, eq, gte, inArray, lte, sql } from "drizzle-orm";
import { db } from "../../../../database/dbclient.js";
import { logs } from "../../../../database/schema/logs.js";
import { createLog } from "../logger.js";
@@ -21,7 +21,8 @@ export const getLogs = async (data: any) => {
inArray(logs.level, data.level),
eq(logs.checked, checked)
)
);
)
.orderBy(desc(logs.created_at));
return { success: true, message: "logs returned", data: logData };
} catch (error) {

View File

@@ -3,6 +3,7 @@ import { ocmeData } from "../../../../database/schema/ocme.js";
import { differenceInMinutes } from "date-fns";
import { createLog } from "../../logger/logger.js";
import { eq } from "drizzle-orm";
import { timeZoneFix } from "../../../globalUtils/timeZoneFix.js";
export const getInfo = async () => {
let ocmeInfo: any = [];
@@ -16,7 +17,7 @@ export const getInfo = async () => {
ocmeInfo = ocmeInfo.map((o: any) => {
const now = new Date(Date.now());
//const strippedDate = o.add_Date.replace("Z", "");
const diff = differenceInMinutes(now, o.add_Date);
const diff = differenceInMinutes(timeZoneFix(), o.add_Date);
return { ...o, waitingFor: diff };
});
createLog(

View File

@@ -60,11 +60,11 @@ export const labelingProcess = async ({
"error",
"labeling",
"ocp",
`There is not a lot assigned to ${macId[0]?.Name}.`
`There is not a lot assigned to ${line}.`
);
return {
success: false,
message: `There is not a lot assigned to ${macId[0]?.Name}.`,
message: `There is not a lot assigned to ${line}.`,
};
}
}
@@ -128,7 +128,7 @@ export const labelingProcess = async ({
}
// if there are more than 2 lots it might be an auto labeler, autolabeler will be defined by its id for now only dayton
if (filteredLot.length > 2 && plantToken[0].value !== "usday1") {
if (filteredLot?.length > 2 && plantToken[0].value !== "usday1") {
createLog(
"error",
"labeling",
@@ -214,15 +214,15 @@ export const labelingProcess = async ({
// create the label
const label = await createLabel(filteredLot[0], userPrinted);
if (!label.success) {
createLog(
"error",
"labeling",
"ocp",
`There was an error creating the label: ${label.message}`
);
return { sucess: false, message: label.message, data: label.data };
}
// if (!label.success) {
// createLog(
// "error",
// "labeling",
// "ocp",
// `There was an error creating the label: ${label.message}`
// );
// return { sucess: false, message: label.message, data: label.data };
// }
// send over to be booked in if we can do it.
const bookin = settingData.filter((s) => s.name === "bookin");

View File

@@ -75,8 +75,16 @@ export const labelerTagRead = async (tagData: any) => {
// check if we need to manual check due to 20 pallets.
if (currentPalletCheck <= cameraPalletCheck) {
currentPalletCheck = currentPalletCheck + 1;
currentPalletCheck++;
labelingProcess({ line: numericString });
createLog(
"info",
"dyco",
"ocp",
`You have printed ${currentPalletCheck} pallets, remaining until ${
cameraPalletCheck - currentPalletCheck
}.`
);
} else {
currentPalletCheck = 0;
createLog(

View File

@@ -17,6 +17,9 @@ import { assignedPrinters } from "./utils/checkAssignments.js";
import { printerCycle } from "./controller/printers/printerCycle.js";
import stopPrinterCycle from "./routes/printers/stopCycle.js";
import startPrinterCycle from "./routes/printers/startCycle.js";
import { printerCycleAutoLabelers } from "./controller/printers/printerCycleAutoLabelers.js";
import AutostartPrinterCycle from "./routes/printers/autoLabelerStart.js";
import AutostopPrinterCycle from "./routes/printers/autoLabelerStop.js";
const app = new OpenAPIHono();
@@ -27,6 +30,8 @@ const routes = [
updateprinters,
startPrinterCycle,
stopPrinterCycle,
AutostartPrinterCycle,
AutostopPrinterCycle,
// lots
getLots,
// labeling
@@ -76,6 +81,7 @@ setTimeout(async () => {
await updatePrinters();
await assignedPrinters();
printerCycle();
printerCycleAutoLabelers();
}
}, 10 * 1000);

View File

@@ -0,0 +1,41 @@
// an external way to creating logs
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { authMiddleware } from "../../../auth/middleware/authMiddleware.js";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { printerCycle } from "../../controller/printers/printerCycle.js";
const app = new OpenAPIHono({ strict: false });
app.openapi(
createRoute({
tags: ["ocp:printers"],
summary: "starts the printers cycling.",
method: "get",
path: "/startsprintercycle",
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, error } = await tryCatch(printerCycle());
const dataError: any = error;
if (error) {
return c.json({
success: false,
message: "Error in stopping the printer cycle",
data: dataError?.data,
});
}
const getData: any = data;
return c.json({
success: getData?.success,
message: getData?.message,
data: getData.data ?? [],
});
}
);
export default app;

View File

@@ -0,0 +1,41 @@
// an external way to creating logs
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { authMiddleware } from "../../../auth/middleware/authMiddleware.js";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { stopPrinterCycle } from "../../controller/printers/printerCycle.js";
const app = new OpenAPIHono({ strict: false });
app.openapi(
createRoute({
tags: ["ocp:printers"],
summary: "Stops the printers cycling.",
method: "get",
path: "/stopprintercycle",
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, error } = await tryCatch(stopPrinterCycle());
const dataError: any = error;
if (error) {
return c.json({
success: false,
message: "Error in stopping the printer cycle",
data: dataError?.data,
});
}
const getData: any = data;
return c.json({
success: getData?.success,
message: getData?.message,
data: getData.data ?? [],
});
}
);
export default app;

View File

@@ -49,7 +49,7 @@ app.openapi(
return c.json({
success: getData?.success,
message: getData?.message,
data: getData.data ?? [],
data: getData?.data ?? [],
});
}
);

View File

@@ -28,8 +28,8 @@ export const assignedPrinters = async () => {
};
}
const printers: any = print.data;
const lots: any = l.data;
const printers: any = print.data ?? [];
const lots: any = l.data ?? [];
for (let i = 0; i < printers.length; i++) {
// is the printer assinged in alplalabel online?