Compare commits

..

36 Commits

Author SHA1 Message Date
04eb2e3e14 refactor(tcpserver): just the tcp server doing something 2025-03-25 07:58:37 -05:00
90fb0d364d Merge branch 'main' of https://git.tuffraid.net/cowch/lstV2 2025-03-25 07:57:55 -05:00
e6e1cecce3 refactor(ocme): corrections to endpoints to work with ocnme as intneeded 2025-03-25 07:54:58 -05:00
73aa95a693 refactor(ocme): cleaup on pickedup 2025-03-25 07:54:22 -05:00
b9f19095cb refactor(ocme): clean up on the getInfo endpoint 2025-03-25 07:54:00 -05:00
dcb56d4274 fix(ocme): corrections to posting data for the response was added 2025-03-25 07:53:30 -05:00
bc1821132e feat(ocme): manual camera trigger for the wrapper added 2025-03-25 07:52:40 -05:00
2551d6c907 refactor(updateserver): removed ocme from starting back up as it was migrated 2025-03-25 07:41:10 -05:00
adf0880659 refactor(server): changed to log only when in dev, and removed the redirect of the url 2025-03-25 07:40:15 -05:00
5149de3199 ci(lst): changes made to the settings file to work across all pvs 2025-03-25 07:39:32 -05:00
c71b514d9a refactor(frontend): prettier change to formatting 2025-03-25 07:27:45 -05:00
9254e52808 chore(release): bump build number to 76 2025-03-25 06:17:31 -05:00
b8c028a6c1 chore(release): bump build number to 75 2025-03-24 20:20:55 -05:00
529e922485 chore(release): bump build number to 74 2025-03-24 20:13:07 -05:00
5201012235 chore(release): bump build number to 73 2025-03-24 20:08:59 -05:00
abe53b8f5d chore(release): bump build number to 72 2025-03-24 20:06:15 -05:00
836f3e294b chore(release): bump build number to 71 2025-03-24 19:56:03 -05:00
96abef762b chore(release): bump build number to 70 2025-03-24 19:40:39 -05:00
2c227f9428 chore(release): bump build number to 69 2025-03-24 18:33:12 -05:00
46647687dc chore(release): bump build number to 68 2025-03-24 18:23:24 -05:00
cb01ef1af1 chore(release): bump build number to 67 2025-03-24 17:16:23 -05:00
b3b5fcec65 chore(release): bump build number to 66 2025-03-24 17:14:25 -05:00
3a4dc47a36 chore(release): bump build number to 65 2025-03-24 17:06:23 -05:00
63177b523e chore(release): bump build number to 64 2025-03-24 17:00:20 -05:00
e1cad027d2 chore(release): bump build number to 63 2025-03-24 16:42:53 -05:00
c1cc355f4f chore(release): bump build number to 62 2025-03-24 16:40:50 -05:00
5ed67f3fc0 chore(release): bump build number to 61 2025-03-24 16:28:32 -05:00
57e82d2360 chore(release): bump build number to 60 2025-03-24 16:26:04 -05:00
9395ec6cd4 chore(release): bump build number to 59 2025-03-24 15:50:29 -05:00
0475bb30f9 chore(release): bump build number to 58 2025-03-24 15:49:37 -05:00
6843368c36 chore(release): bump build number to 57 2025-03-24 15:47:16 -05:00
335ea2deca chore(release): bump build number to 56 2025-03-24 15:39:33 -05:00
96814c1115 Merge branch 'main' of https://git.tuffraid.net/cowch/lstV2 2025-03-24 15:31:35 -05:00
6dd9ed848b test(ocme): lots of changes to get it working in production 2025-03-24 15:31:31 -05:00
0c5fc1dfb0 chore(release): bump build number to 55 2025-03-24 15:28:10 -05:00
5886bea85d chore(release): bump build number to 52 2025-03-24 11:43:52 -05:00
21 changed files with 1294 additions and 842 deletions

View File

@@ -1,6 +1,8 @@
{ {
"editor.defaultFormatter": "esbenp.prettier-vscode", "editor.defaultFormatter": "esbenp.prettier-vscode",
"workbench.colorTheme": "Default Dark+",
"prettier.tabWidth": 4,
"terminal.integrated.env.windows": {},
"editor.formatOnSave": true, "editor.formatOnSave": true,
"[javascript]": { "[javascript]": {
"editor.formatOnSave": true "editor.formatOnSave": true

View File

@@ -1,14 +1,27 @@
import {toast} from "sonner"; import { toast } from "sonner";
import {LstCard} from "../extendedUI/LstCard"; import { LstCard } from "../extendedUI/LstCard";
import {Button} from "../ui/button"; import { Button } from "../ui/button";
import {Input} from "../ui/input"; import { Input } from "../ui/input";
import {Table, TableBody, TableCell, TableHead, TableHeader, TableRow} from "../ui/table"; import {
import {Skeleton} from "../ui/skeleton"; Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../ui/table";
import { Skeleton } from "../ui/skeleton";
//import CycleCountLog from "./CycleCountLog"; //import CycleCountLog from "./CycleCountLog";
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "../ui/select"; import {
import {Controller, useForm} from "react-hook-form"; Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "../ui/select";
import { Controller, useForm } from "react-hook-form";
import axios from "axios"; import axios from "axios";
import {useState} from "react"; import { useState } from "react";
export default function OcmeCycleCount() { export default function OcmeCycleCount() {
const token = localStorage.getItem("auth_token"); const token = localStorage.getItem("auth_token");
@@ -18,7 +31,7 @@ export default function OcmeCycleCount() {
register, register,
handleSubmit, handleSubmit,
//watch, //watch,
formState: {errors}, formState: { errors },
reset, reset,
control, control,
} = useForm(); } = useForm();
@@ -29,7 +42,7 @@ export default function OcmeCycleCount() {
toast.success(`Cycle count started`); toast.success(`Cycle count started`);
try { try {
const res = await axios.post("/ocme/api/v1/cyclecount", data, { const res = await axios.post("/ocme/api/v1/cyclecount", data, {
headers: {Authorization: `Bearer ${token}`}, headers: { Authorization: `Bearer ${token}` },
}); });
toast.success(res.data.message); toast.success(res.data.message);
setData(res.data.data); setData(res.data.data);
@@ -45,20 +58,25 @@ export default function OcmeCycleCount() {
<div className="flex flex-row w-screen"> <div className="flex flex-row w-screen">
<div className="m-2 w-5/6"> <div className="m-2 w-5/6">
<LstCard> <LstCard>
<p className="ml-2">Please enter the name or laneID you want to cycle count.</p> <p className="ml-2">
Please enter the name or laneID you want to cycle count.
</p>
<div> <div>
<form onSubmit={handleSubmit(onSubmit)}> <form onSubmit={handleSubmit(onSubmit)}>
<div className="flex justify-between"> <div className="flex justify-between">
<div className="m-2 flex flex-row"> <div className="m-2 flex flex-row">
<Input <Input
placeholder="enter lane: L064" placeholder="enter lane: L064"
className={errors.lane ? "border-red-500" : ""} className={
errors.lane ? "border-red-500" : ""
}
aria-invalid={!!errors.lane} aria-invalid={!!errors.lane}
{...register("lane", { {...register("lane", {
required: true, required: true,
minLength: { minLength: {
value: 3, value: 3,
message: "The lane is too short!", message:
"The lane is too short!",
}, },
})} })}
/> />
@@ -68,25 +86,39 @@ export default function OcmeCycleCount() {
name="laneType" name="laneType"
defaultValue={""} defaultValue={""}
render={({ render={({
field: {onChange}, field: { onChange },
fieldState: {}, fieldState: {},
//formState, //formState,
}) => ( }) => (
<Select onValueChange={onChange}> <Select
onValueChange={onChange}
>
<SelectTrigger className="w-[180px]"> <SelectTrigger className="w-[180px]">
<SelectValue placeholder="Select name or id" /> <SelectValue placeholder="Select name or id" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="name">Name</SelectItem> <SelectItem value="name">
<SelectItem value="laneId">Lane ID</SelectItem> Name
</SelectItem>
<SelectItem value="laneId">
Lane ID
</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
)} )}
/> />
</div> </div>
</div> </div>
<Button className="m-2" type="submit" disabled={counting}> <Button
{counting ? <span>Counting...</span> : <span>CycleCount</span>} className="m-2"
type="submit"
disabled={counting}
>
{counting ? (
<span>Counting...</span>
) : (
<span>CycleCount</span>
)}
</Button> </Button>
</div> </div>
</form> </form>
@@ -142,7 +174,9 @@ export default function OcmeCycleCount() {
<> <>
{data.map((i: any) => { {data.map((i: any) => {
let classname = ``; let classname = ``;
if (i.info === "Quality Check Required") { if (
i.info === "Quality Check Required"
) {
classname = `bg-red-500`; classname = `bg-red-500`;
} }
if (i.info === "Sent to Inv") { if (i.info === "Sent to Inv") {
@@ -150,24 +184,46 @@ export default function OcmeCycleCount() {
} }
return ( return (
<TableRow key={i.runningNumber}> <TableRow key={i.runningNumber}>
<TableCell className={`font-medium ${classname}`}> <TableCell
className={`font-medium ${classname}`}
>
{i.alpla_laneID} {i.alpla_laneID}
</TableCell> </TableCell>
<TableCell className={`font-medium ${classname}`}> <TableCell
className={`font-medium ${classname}`}
>
{i.alpla_laneDescription} {i.alpla_laneDescription}
</TableCell> </TableCell>
<TableCell className={`font-medium ${classname}`}> <TableCell
className={`font-medium ${classname}`}
>
{i.Article} {i.Article}
</TableCell> </TableCell>
<TableCell className={`font-medium ${classname}`}> <TableCell
className={`font-medium ${classname}`}
>
{i.alpla_laneDescription} {i.alpla_laneDescription}
</TableCell> </TableCell>
<TableCell className={`font-medium ${classname}`}> <TableCell
className={`font-medium ${classname}`}
>
{i.runningNumber} {i.runningNumber}
</TableCell> </TableCell>
<TableCell className={`font-medium ${classname}`}>{i.ocme}</TableCell> <TableCell
<TableCell className={`font-medium ${classname}`}>{i.stock}</TableCell> className={`font-medium ${classname}`}
<TableCell className={`font-medium ${classname}`}>{i.info}</TableCell> >
{i.ocme}
</TableCell>
<TableCell
className={`font-medium ${classname}`}
>
{i.stock}
</TableCell>
<TableCell
className={`font-medium ${classname}`}
>
{i.info}
</TableCell>
</TableRow> </TableRow>
); );
})} })}

View File

@@ -21,7 +21,7 @@
"deploy": "standard-version --conventional-commits && npm run prodBuild", "deploy": "standard-version --conventional-commits && npm run prodBuild",
"zipServer": "dotenvx run -f .env -- tsx server/scripts/zipUpBuild.ts \"C:\\Users\\matthes01\\Documents\\lstv2\"", "zipServer": "dotenvx run -f .env -- tsx server/scripts/zipUpBuild.ts \"C:\\Users\\matthes01\\Documents\\lstv2\"",
"v1Build": "cd C:\\Users\\matthes01\\Documents\\logisticsSupportTool && npm run oldBuilder", "v1Build": "cd C:\\Users\\matthes01\\Documents\\logisticsSupportTool && npm run oldBuilder",
"prodBuild": "npm run v1Build && powershell -ExecutionPolicy Bypass -File server/scripts/build.ps1 -dir \"C:\\Users\\matthes01\\Documents\\lstv2\" && npm run zipServer", "prodBuild": "npm run v1Build && powershell -ExecutionPolicy Bypass -File server/scripts/build.ps1 -dir \"C:\\Users\\matthes01\\Documents\\lstv2-dev\" && npm run zipServer",
"commit": "cz", "commit": "cz",
"prodinstall": "npm i --omit=dev && npm run db:migrate", "prodinstall": "npm i --omit=dev && npm run db:migrate",
"checkupdates": "npx npm-check-updates" "checkupdates": "npx npm-check-updates"
@@ -32,7 +32,7 @@
} }
}, },
"admConfig": { "admConfig": {
"build": 50, "build": 76,
"oldBuild": "backend-0.1.3.zip" "oldBuild": "backend-0.1.3.zip"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -39,7 +39,10 @@ createLog("info", "LST", "server", `Server is installed: ${installed}`);
const app = new OpenAPIHono({ strict: false }); const app = new OpenAPIHono({ strict: false });
// middle ware // middle ware
app.use("*", logger()); if (process.env.NODE_ENV === "development") {
app.use("*", logger());
}
app.use( app.use(
"*", "*",
cors({ cors({
@@ -53,17 +56,17 @@ app.use(
); );
// Middleware to normalize route case // Middleware to normalize route case
app.use("*", async (c, next) => { // app.use("*", async (c, next) => {
const lowercasedUrl = c.req.url.toLowerCase(); // // const lowercasedUrl = c.req.url.toLowerCase();
//console.log("Incoming Request:", c.req.url, c.req.method); // console.log("Incoming Request:", c.req.url, c.req.method);
// If the URL is already lowercase, continue as usual // // // If the URL is already lowercase, continue as usual
if (c.req.url === lowercasedUrl) { // // if (c.req.url === lowercasedUrl) {
return next(); // await next();
} // // }
// Otherwise, re-route internally // // // Otherwise, re-route internally
return c.redirect(lowercasedUrl, 308); // 308 preserves the HTTP method // // return c.redirect(lowercasedUrl, 308); // 308 preserves the HTTP method
}); // });
app.doc("/api/ref", { app.doc("/api/ref", {
openapi: "3.0.0", openapi: "3.0.0",

View File

@@ -415,10 +415,10 @@ try {
Start-Service -DisplayName $serviceLstV2 Start-Service -DisplayName $serviceLstV2
Start-Sleep -Seconds 1 Start-Sleep -Seconds 1
Write-Host "$($server) finished updating" Write-Host "$($server) finished updating"
if($token -eq "usday1"){ # if($token -eq "usday1"){
Write-Host "Starting $($serviceOcme)" # Write-Host "Starting $($serviceOcme)"
Start-Service -DisplayName $serviceOcme # Start-Service -DisplayName $serviceOcme
} # }
} }
Invoke-Command -ComputerName $server -ScriptBlock $plantFunness -ArgumentList $server, $token, $location, $buildZip, $buildLoc, $obslst, $obsBuild -Credential $credentials Invoke-Command -ComputerName $server -ScriptBlock $plantFunness -ArgumentList $server, $token, $location, $buildZip, $buildLoc, $obslst, $obsBuild -Credential $credentials

View File

@@ -1,16 +1,33 @@
import {spawn} from "child_process"; import { spawn } from "child_process";
import {getAppInfo} from "../globalUtils/appInfo.js"; import { getAppInfo } from "../globalUtils/appInfo.js";
import {db} from "../../database/dbclient.js"; 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> => { export const updateServer = async (
devApp: string,
server: string | null
): Promise<UpdateServerResponse> => {
const app = await getAppInfo(devApp);
const serverInfo = await db
export const updateServer = async (
devApp: string,
server: string | null
): Promise<UpdateServerResponse> => {
const app = await getAppInfo(devApp); const app = await getAppInfo(devApp);
const serverInfo = await db const serverInfo = await db
.select() .select()
@@ -26,10 +43,36 @@ export const updateServer = async (devApp: string, server: string | null): Promi
); );
return { return {
success: false, success: false,
message: "Looks like you are missing the plant token or have entered an incorrect one please try again.", message:
"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",
@@ -78,11 +121,26 @@ export const updateServer = async (devApp: string, server: string | null): Promi
// change the server to upgradeing // change the server to upgradeing
await db await db
.update(serverData) .update(serverData)
.set({isUpgrading: true}) .set({ isUpgrading: true })
.where(eq(serverData.plantToken, server?.toLowerCase() ?? ""));
//let stdout = "";
//let stderr = "";
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() ?? "")); .where(eq(serverData.plantToken, server?.toLowerCase() ?? ""));
//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();
@@ -90,6 +148,12 @@ export const updateServer = async (devApp: string, server: string | null): Promi
//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();
@@ -97,6 +161,13 @@ export const updateServer = async (devApp: string, server: string | null): Promi
//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) {
@@ -109,7 +180,27 @@ export const updateServer = async (devApp: string, server: string | null): Promi
try { try {
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() ?? ""));
createLog(
"info",
"lst",
"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() ?? "")); .where(eq(serverData.plantToken, server?.toLowerCase() ?? ""));
createLog( createLog(
"info", "info",
@@ -126,6 +217,12 @@ export const updateServer = async (devApp: string, server: string | null): Promi
); );
} }
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.`,
@@ -133,6 +230,9 @@ export const updateServer = async (devApp: string, server: string | null): Promi
} 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);
// } // }
@@ -143,6 +243,12 @@ export const updateServer = async (devApp: string, server: string | null): Promi
}); });
} }
}); });
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) => {
@@ -151,12 +257,37 @@ export const updateServer = async (devApp: string, server: string | null): Promi
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("info", "lst", "serverUpdater", `Running the update on all servers`); createLog(
"info",
"lst",
"serverUpdater",
`Running the update on all servers`
);
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;
createLog(
"info",
"lst",
"serverUpdater",
`Running the update on all servers`
);
let count = 1; let count = 1;
for (const server of servers) { for (const server of servers) {
try { try {
@@ -166,7 +297,23 @@ export async function processAllServers(devApp: string) {
//return {success: true, message: `${server.sName} was updated.`, data: updateToServer}; //return {success: true, message: `${server.sName} was updated.`, data: updateToServer};
} catch (error: any) { } catch (error: any) {
createLog("info", "lst", "serverUpdater", `Error updating ${server.sName}: ${error.message}`); createLog(
"info",
"lst",
"serverUpdater",
`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}`}; //return {success: false, message: `Error updating ${server.sName}: ${error.message}`};
} }
} }

View File

@@ -99,7 +99,7 @@ const updateBuildNumber = (appLock: string) => {
// Auto-commit changes // Auto-commit changes
execSync("git add package.json"); execSync("git add package.json");
execSync( execSync(
`git commit -m "build: bump build number to ${pkgJson.admConfig.build}"` `git commit -m "chore(release): bump build number to ${pkgJson.admConfig.build}"`
); );
} else { } else {
createLog( createLog(

View File

@@ -3,9 +3,14 @@ import axios from "axios";
export const ocmeInv = async (data: any) => { export const ocmeInv = async (data: any) => {
try { try {
const res = await axios.post( const res = await axios.post(
"http://usday1vms010:3250/api/v1/getLaneData", "http://usday1vms010:3250/api/v1/getlanedata",
{lane: data.lane, laneType: data.laneType}, { lane: data.lane, laneType: data.laneType },
{headers: {"Content-Type": "application/json", Connection: "keep-alive"}} {
headers: {
"Content-Type": "application/json",
Connection: "keep-alive",
},
}
); );
// console.log(res.data.data); // console.log(res.data.data);

View File

@@ -1,23 +1,37 @@
import {db} from "../../../../database/dbclient.js"; import { db } from "../../../../database/dbclient.js";
import {ocmeData} from "../../../../database/schema/ocme.js"; import { ocmeData } from "../../../../database/schema/ocme.js";
import {differenceInMinutes} from "date-fns"; import { differenceInMinutes } from "date-fns";
import {createLog} from "../../logger/logger.js"; import { createLog } from "../../logger/logger.js";
import {eq} from "drizzle-orm"; import { eq } from "drizzle-orm";
export const getInfo = async () => { export const getInfo = async () => {
let ocmeInfo: any = []; let ocmeInfo: any = [];
try { try {
ocmeInfo = await db.select().from(ocmeData).where(eq(ocmeData.pickedUp, false)); ocmeInfo = await db
.select()
.from(ocmeData)
.where(eq(ocmeData.pickedUp, false));
// add in the time difference // add in the time difference
ocmeInfo = ocmeInfo.map((o: any) => { ocmeInfo = ocmeInfo.map((o: any) => {
const now = new Date(Date.now()); const now = new Date(Date.now());
const diff = differenceInMinutes(now, o.add_Date!); //const strippedDate = o.add_Date.replace("Z", "");
return {...o, waitingFor: diff}; const diff = differenceInMinutes(now, o.add_Date);
return { ...o, waitingFor: diff };
}); });
createLog("info", "ocme", "ocme", `There are ${ocmeInfo.length} pallet(s) to be picked up.`); createLog(
"info",
"ocme",
"ocme",
`There are ${ocmeInfo.length} pallet(s) to be picked up.`
);
} catch (error) { } catch (error) {
createLog("error", "ocme", "ocme", "There was an error trying to retrive the ocmeInfo."); createLog(
"error",
"ocme",
"ocme",
"There was an error trying to retrive the ocmeInfo."
);
throw Error("There was an error trying to retrive the."); throw Error("There was an error trying to retrive the.");
} }

View File

@@ -1,43 +1,82 @@
import {db} from "../../../../database/dbclient.js"; import { db } from "../../../../database/dbclient.js";
import {ocmeData} from "../../../../database/schema/ocme.js"; import { ocmeData } from "../../../../database/schema/ocme.js";
import {createSSCC} from "../../../globalUtils/createSSCC.js"; 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) => {
// if we have sscc we will do everything here and ignore the rn even it its sent over console.log(data);
if (data.sscc && !data.runningNr) { let newData = data;
data.runningNr = data.sscc.slice(10, -1); if (Array.isArray(data)) {
newData = {
sscc: data[1],
areaFrom: data[0],
completed: true,
};
} }
if (!data.sscc && !data.runningNr) { if (newData.sscc && !newData.runningNr) {
// data.runningNr = data.sscc.slice(10, -1); newData.runningNr = newData.sscc.slice(10, -1);
return {success: false, message: "Missing data please try again", data: []}; }
if (!newData.sscc && !newData.runningNr) {
return {
success: false,
message: "Missing data please try again",
data: [],
};
} }
let label; let label;
const filterQuery = labelData.replaceAll("[rn]", data.runningNr); const filterQuery = labelData.replaceAll("[rn]", newData.runningNr);
try { try {
label = await query(filterQuery, "Label data"); label = await query(filterQuery, "Label data");
} catch (error) { } catch (error) {
createLog("error", "ocme", "ocme", "There was an error getting the labelData"); createLog(
"error",
"ocme",
"ocme",
"There was an error getting the labelData"
);
} }
const newPost = { const newPost = {
sscc: data.sscc ? data.sscc : await createSSCC(data.runningNr), sscc: newData.sscc ? newData.sscc : await createSSCC(newData.runningNr),
runningNr: data.runningNr, runningNr: newData.runningNr,
completed: data.completed, completed: newData.completed ? newData.completed : true,
lineNum: label[0].machineLocation, lineNum: label[0]?.machineLocation,
areaFrom: data.areaFrom, areaFrom: newData.areaFrom,
pickedUp: false, pickedUp: false,
}; };
try { try {
const enterNewData = await db.insert(ocmeData).values(newPost).returning({sscc: ocmeData.sscc}); const enterNewData = await db
return {success: true, message: "Data was posted to ocme info", data: enterNewData}; .insert(ocmeData)
.values(newPost)
.returning({
sscc: ocmeData.sscc,
runningNr: ocmeData.runningNr,
areaFrom: ocmeData.areaFrom,
lineNum: ocmeData.lineNum,
completed: ocmeData.completed,
pickedUp: ocmeData.pickedUp,
});
//console.log(enterNewData);
return {
success: true,
message: "Data was posted to ocme info",
data: enterNewData,
};
} catch (error) { } catch (error) {
console.log(error); //console.log(error);
return {success: false, message: "Data was posted to ocme info", data: newPost}; return {
success: false,
message: "Data was posted to ocme info",
data: [],
};
} }
}; };

View File

@@ -0,0 +1,49 @@
import net from "net";
import { db } from "../../../../database/dbclient.js";
import { settings } from "../../../../database/schema/settings.js";
import { eq } from "drizzle-orm";
import { createLog } from "../../logger/logger.js";
export const triggerScanner = async () => {
const camera = new net.Socket();
let setting = await db
.select()
.from(settings)
.where(eq(settings.name, "zebraScanners"));
if (setting.length === 0) {
return {
success: false,
message: "Looks like the setting is missing.",
};
}
const scannerData = JSON.parse(setting[0]?.value);
let data = scannerData.filter((n: any) => n.name === "wrapper1");
let port = data[0].port;
console.log(data);
createLog(
"info",
"wrapperScanner",
"ocme",
`End of line Camera was triggered`
);
return new Promise((resolve, reject) => {
camera.connect(port, data[0].ip, async () => {
createLog("info", "wrapperScanner", "ocme", `Triggered`);
camera.write("TRIGGER", "utf8");
camera.end();
resolve({ success: true, message: "Camera was triggered." });
});
camera.on("error", (error) => {
createLog("error", "wrapperScanner", "ocme", `${error}`);
resolve({
success: false,
message: `There was an error triggering the camera: ${JSON.stringify(
error
)}`,
});
});
resolve({ success: true, message: "Camera was triggered." });
});
};

View File

@@ -1,4 +1,4 @@
import {OpenAPIHono} from "@hono/zod-openapi"; import { OpenAPIHono } from "@hono/zod-openapi";
// routes // routes
import getInfo from "./route/getInfo.js"; import getInfo from "./route/getInfo.js";
@@ -7,14 +7,23 @@ import pickedup from "./route/pickedUp.js";
import postsscc from "./route/postSSCC.js"; import postsscc from "./route/postSSCC.js";
import getShipments from "./route/getShipmentPallets.js"; import getShipments from "./route/getShipmentPallets.js";
import cycleCount from "./route/cycleCount.js"; import cycleCount from "./route/cycleCount.js";
import {serve} from "@hono/node-server"; import { serve } from "@hono/node-server";
import {createLog} from "../logger/logger.js"; import { createLog } from "../logger/logger.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 manualTrigger from "./route/triggerCamera.js";
const app = new OpenAPIHono(); const app = new OpenAPIHono();
const port = process.env.OCME_PORT; const port = process.env.OCME_PORT;
const routes = [getInfo, postRunningNr, postsscc, pickedup, getShipments, cycleCount] as const; const routes = [
getInfo,
postRunningNr,
postsscc,
pickedup,
getShipments,
cycleCount,
manualTrigger,
] as const;
const setting = await db.select().from(settings); const setting = await db.select().from(settings);
const isActive = setting.filter((n) => n.name === "ocmeService"); const isActive = setting.filter((n) => n.name === "ocmeService");
@@ -23,7 +32,10 @@ const appRoutes = routes.forEach((route) => {
}); });
app.all("/api/v1/*", (c) => { app.all("/api/v1/*", (c) => {
return c.json({success: false, message: "you have encounted an ocme route that dose not exist."}); return c.json({
success: false,
message: "you have encounted an ocme route that dose not exist.",
});
}); });
if (port && isActive[0]?.value === "1") { if (port && isActive[0]?.value === "1") {
serve( serve(
@@ -33,7 +45,12 @@ if (port && isActive[0]?.value === "1") {
hostname: "0.0.0.0", hostname: "0.0.0.0",
}, },
(info) => { (info) => {
createLog("info", "LST", "server", `Ocme section is listening on http://${info.address}:${info.port}`); createLog(
"info",
"LST",
"server",
`Ocme section is listening on http://${info.address}:${info.port}`
);
} }
); );
} }

View File

@@ -1,16 +1,16 @@
import {createRoute, OpenAPIHono, z} from "@hono/zod-openapi"; import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import {apiHit} from "../../../globalUtils/apiHits.js"; import { apiHit } from "../../../globalUtils/apiHits.js";
import {responses} from "../../../globalUtils/routeDefs/responses.js"; import { responses } from "../../../globalUtils/routeDefs/responses.js";
import {authMiddleware} from "../../auth/middleware/authMiddleware.js"; import { authMiddleware } from "../../auth/middleware/authMiddleware.js";
import {cycleCount} from "../controller/cycleCount.js"; import { cycleCount } from "../controller/cycleCount.js";
import type {User} from "../../../types/users.js"; import type { User } from "../../../types/users.js";
import {verify} from "hono/jwt"; import { verify } from "hono/jwt";
const app = new OpenAPIHono({strict: false}); const app = new OpenAPIHono({ strict: false });
const AddSetting = z.object({ const AddSetting = z.object({
lane: z.string().openapi({example: "L064"}), lane: z.string().openapi({ example: "L064" }),
}); });
app.openapi( app.openapi(
@@ -18,19 +18,19 @@ app.openapi(
tags: ["ocme"], tags: ["ocme"],
summary: "Cycle counts a lane based on the lane Alias", summary: "Cycle counts a lane based on the lane Alias",
method: "post", method: "post",
path: "/cyclecount", path: "/cycleCount",
middleware: authMiddleware, middleware: authMiddleware,
request: { request: {
body: { body: {
content: { content: {
"application/json": {schema: AddSetting}, "application/json": { schema: AddSetting },
}, },
}, },
}, },
responses: responses(), responses: responses(),
}), }),
async (c) => { async (c) => {
apiHit(c, {endpoint: "api/auth/register"}); apiHit(c, { endpoint: "api/auth/register" });
// make sure we have a vaid user being accessed thats really logged in // make sure we have a vaid user being accessed thats really logged in
const body = await c.req.json(); const body = await c.req.json();
@@ -43,15 +43,26 @@ app.openapi(
const payload = await verify(token, process.env.JWT_SECRET!); const payload = await verify(token, process.env.JWT_SECRET!);
user = payload.user as User; user = payload.user as User;
} catch (error) { } catch (error) {
return c.json({message: "Unauthorized"}, 401); return c.json({ message: "Unauthorized" }, 401);
} }
try { try {
const cycleData = await cycleCount(body, user); const cycleData = await cycleCount(body, user);
return c.json({success: true, message: `${body.lane} was just cycle counted.`, data: cycleData}, 200); return c.json(
{
success: true,
message: `${body.lane} was just cycle counted.`,
data: cycleData,
},
200
);
} catch (error) { } catch (error) {
return c.json( return c.json(
{success: false, message: `There was an error cycle counting ${body.lane}`, data: error}, {
success: false,
message: `There was an error cycle counting ${body.lane}`,
data: error,
},
400 400
); );
} }

View File

@@ -1,80 +1,36 @@
import {createRoute, OpenAPIHono, z} from "@hono/zod-openapi"; import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import {getInfo} from "../controller/getInfo.js"; import { getInfo } from "../controller/getInfo.js";
import {apiHit} from "../../../globalUtils/apiHits.js"; import { apiHit } from "../../../globalUtils/apiHits.js";
import { responses } from "../../../globalUtils/routeDefs/responses.js";
const app = new OpenAPIHono({strict: false}); const app = new OpenAPIHono({ strict: false });
const AddSetting = z.object({
name: z.string().openapi({example: "server"}),
value: z.string().openapi({example: "localhost"}),
description: z.string().openapi({example: "The server we are going to connect to"}),
roles: z.string().openapi({example: "admin"}),
module: z.string().openapi({example: "production"}),
});
app.openapi( app.openapi(
createRoute({ createRoute({
tags: ["ocme"], tags: ["ocme"],
summary: "Get all current info", summary: "Get all current info",
method: "get", method: "get",
path: "/getinfo", path: "/getInfo",
request: {
body: { responses: responses(),
content: {
"application/json": {schema: AddSetting},
},
},
},
responses: {
200: {
content: {
"application/json": {
schema: z.object({
success: z.boolean().openapi({example: true}),
message: z.string().openapi({example: "Starter"}),
data: z.array(z.object({})).optional().openapi({example: []}),
}),
},
},
description: "Response message",
},
400: {
content: {
"application/json": {
schema: z.object({
success: z.boolean().openapi({example: false}),
message: z.string().optional().openapi({example: "Internal Server error"}),
data: z.array(z.object({})).optional().openapi({example: []}),
}),
},
},
description: "Internal Server Error",
},
// 401: {
// content: {
// "application/json": {
// schema: z.object({message: z.string().optional().openapi({example: "Unauthenticated"})}),
// },
// },
// description: "Unauthorized",
// },
// 500: {
// content: {
// "application/json": {
// schema: z.object({message: z.string().optional().openapi({example: "Internal Server error"})}),
// },
// },
// description: "Internal Server Error",
// },
},
}), }),
async (c) => { async (c) => {
// make sure we have a vaid user being accessed thats really logged in // make sure we have a vaid user being accessed thats really logged in
apiHit(c, {endpoint: "api/auth/register"}); apiHit(c, { endpoint: "api/auth/register" });
try { try {
return c.json({success: true, message: "Ocme Info", data: await getInfo()}, 200); return c.json(
{ success: true, message: "Ocme Info", data: await getInfo() },
200
);
} catch (error) { } catch (error) {
return c.json({success: false, message: "There was an error getting ocmeInfo data", data: error}, 400); return c.json(
{
success: false,
message: "There was an error getting ocmeInfo data",
data: error,
},
400
);
} }
} }
); );

View File

@@ -1,11 +1,11 @@
import {createRoute, OpenAPIHono, z} from "@hono/zod-openapi"; import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import {apiHit} from "../../../globalUtils/apiHits.js"; import { apiHit } from "../../../globalUtils/apiHits.js";
import {getShipmentPallets} from "../controller/getShipmentPallets.js"; import { getShipmentPallets } from "../controller/getShipmentPallets.js";
const app = new OpenAPIHono(); const app = new OpenAPIHono();
const ShipmentID = z.object({ const ShipmentID = z.object({
shipmentID: z.string().optional().openapi({example: "14558"}), shipmentID: z.string().optional().openapi({ example: "14558" }),
}); });
app.openapi( app.openapi(
@@ -13,11 +13,11 @@ app.openapi(
tags: ["ocme"], tags: ["ocme"],
summary: "Post New running number to be picked up.", summary: "Post New running number to be picked up.",
method: "post", method: "post",
path: "/getshipmentpallets", path: "/GetShipmentPallets",
request: { request: {
body: { body: {
content: { content: {
"application/json": {schema: ShipmentID}, "application/json": { schema: ShipmentID },
}, },
}, },
}, },
@@ -26,8 +26,8 @@ app.openapi(
content: { content: {
"application/json": { "application/json": {
schema: z.object({ schema: z.object({
success: z.boolean().openapi({example: true}), success: z.boolean().openapi({ example: true }),
message: z.string().openapi({example: "Starter"}), message: z.string().openapi({ example: "Starter" }),
// data: z // data: z
// .array(z.object({sscc: z.string().optional()})) // .array(z.object({sscc: z.string().optional()}))
// .optional() // .optional()
@@ -41,9 +41,12 @@ app.openapi(
content: { content: {
"application/json": { "application/json": {
schema: z.object({ schema: z.object({
success: z.boolean().openapi({example: false}), success: z.boolean().openapi({ example: false }),
message: z.string().optional().openapi({example: "Internal Server error"}), message: z
data: z.array(z.object({})).optional().openapi({example: []}), .string()
.optional()
.openapi({ example: "Internal Server error" }),
data: z.array(z.object({})).optional().openapi({ example: [] }),
}), }),
}, },
}, },
@@ -71,11 +74,17 @@ app.openapi(
// make sure we have a vaid user being accessed thats really logged in // make sure we have a vaid user being accessed thats really logged in
try { try {
const data = await c.req.json(); const data = await c.req.json();
apiHit(c, {endpoint: "api/ocme/getshipmentpallets", lastBody: data}); apiHit(c, { endpoint: "api/ocme/getshipmentpallets", lastBody: data });
console.log;
if (!data.shipmentID) { if (!data.shipmentID) {
return c.json( return c.json(
{success: false, message: "You are missing the shipment id please try again.", data: []}, {
success: false,
message: "You are missing the shipment id please try again.",
data: [],
},
400 400
); );
} }
@@ -83,11 +92,22 @@ app.openapi(
const shiptmentData = await getShipmentPallets(data.shipmentID); const shiptmentData = await getShipmentPallets(data.shipmentID);
return c.json( return c.json(
{success: shiptmentData.success, message: shiptmentData.message, data: shiptmentData.data ?? []}, {
success: shiptmentData.success,
message: shiptmentData.message,
data: shiptmentData.data ?? [],
},
200 200
); );
} catch (error) { } catch (error) {
return c.json({success: false, message: "There was an error getting the shipment data.", data: error}, 400); return c.json(
{
success: false,
message: "There was an error getting the shipment data.",
data: error,
},
400
);
} }
} }
); );

View File

@@ -1,16 +1,19 @@
import {createRoute, OpenAPIHono, z} from "@hono/zod-openapi"; import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import {postLabelData} from "../controller/postRunningNr.js"; import { postLabelData } from "../controller/postRunningNr.js";
import {apiHit} from "../../../globalUtils/apiHits.js"; import { apiHit } from "../../../globalUtils/apiHits.js";
import {pickedup} from "../controller/pickedup.js"; import { pickedup } from "../controller/pickedup.js";
const app = new OpenAPIHono(); const app = new OpenAPIHono();
const PostRunningNr = z.object({ const PostRunningNr = z.object({
sscc: z.string().optional().openapi({example: "00090103830005710997"}), sscc: z.string().optional().openapi({ example: "00090103830005710997" }),
runningNr: z.string().optional().openapi({example: "localhost"}), runningNr: z.string().optional().openapi({ example: "localhost" }),
areaFrom: z.string().optional().openapi({example: "The server we are going to connect to"}), areaFrom: z
completed: z.boolean().optional().openapi({example: true}), .string()
all: z.boolean().optional().openapi({example: false}), .optional()
.openapi({ example: "The server we are going to connect to" }),
completed: z.boolean().optional().openapi({ example: true }),
all: z.boolean().optional().openapi({ example: false }),
}); });
app.openapi( app.openapi(
@@ -20,11 +23,11 @@ app.openapi(
method: "patch", method: "patch",
description: description:
"removes the pallet(s) from showing as needed to be picked up, we clear everything related to the pallet number to reduce the risk of a mix, passing `all` will just clear everything that is pending.", "removes the pallet(s) from showing as needed to be picked up, we clear everything related to the pallet number to reduce the risk of a mix, passing `all` will just clear everything that is pending.",
path: "/pickedup", path: "/pickedUp",
request: { request: {
body: { body: {
content: { content: {
"application/json": {schema: PostRunningNr}, "application/json": { schema: PostRunningNr },
}, },
}, },
}, },
@@ -33,8 +36,8 @@ app.openapi(
content: { content: {
"application/json": { "application/json": {
schema: z.object({ schema: z.object({
success: z.boolean().openapi({example: true}), success: z.boolean().openapi({ example: true }),
message: z.string().openapi({example: "Starter"}), message: z.string().openapi({ example: "Starter" }),
// data: z // data: z
// .array(z.object({sscc: z.string().optional()})) // .array(z.object({sscc: z.string().optional()}))
// .optional() // .optional()
@@ -48,9 +51,12 @@ app.openapi(
content: { content: {
"application/json": { "application/json": {
schema: z.object({ schema: z.object({
success: z.boolean().openapi({example: false}), success: z.boolean().openapi({ example: false }),
message: z.string().optional().openapi({example: "Internal Server error"}), message: z
data: z.array(z.object({})).optional().openapi({example: []}), .string()
.optional()
.openapi({ example: "Internal Server error" }),
data: z.array(z.object({})).optional().openapi({ example: [] }),
}), }),
}, },
}, },
@@ -67,7 +73,12 @@ app.openapi(
500: { 500: {
content: { content: {
"application/json": { "application/json": {
schema: z.object({message: z.string().optional().openapi({example: "Internal Server error"})}), schema: z.object({
message: z
.string()
.optional()
.openapi({ example: "Internal Server error" }),
}),
}, },
}, },
description: "Internal Server Error", description: "Internal Server Error",
@@ -78,11 +89,25 @@ app.openapi(
// make sure we have a vaid user being accessed thats really logged in // make sure we have a vaid user being accessed thats really logged in
try { try {
const data = await c.req.json(); const data = await c.req.json();
apiHit(c, {endpoint: "api/ocme/pickedup", lastBody: data}); apiHit(c, { endpoint: "api/ocme/pickedup", lastBody: data });
const postPallet = await pickedup(data); const postPallet = await pickedup(data);
return c.json({success: postPallet.success, message: postPallet.message, data: postPallet.data}, 200); return c.json(
{
success: postPallet.success,
message: postPallet.message,
data: postPallet.data,
},
200
);
} catch (error) { } catch (error) {
return c.json({success: false, message: "There was an error getting ocmeInfo data", data: error}, 400); return c.json(
{
success: false,
message: "There was an error getting ocmeInfo data",
data: error,
},
400
);
} }
} }
); );

View File

@@ -1,15 +1,18 @@
import {createRoute, OpenAPIHono, z} from "@hono/zod-openapi"; import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import {getInfo} from "../controller/getInfo.js"; import { getInfo } from "../controller/getInfo.js";
import {postLabelData} from "../controller/postRunningNr.js"; import { postLabelData } from "../controller/postRunningNr.js";
import {apiHit} from "../../../globalUtils/apiHits.js"; import { apiHit } from "../../../globalUtils/apiHits.js";
const app = new OpenAPIHono(); const app = new OpenAPIHono();
const PostRunningNr = z.object({ const PostRunningNr = z.object({
sscc: z.string().optional().openapi({example: "00090103830005710997"}), sscc: z.string().optional().openapi({ example: "00090103830005710997" }),
runningNr: z.string().optional().openapi({example: "localhost"}), runningNr: z.string().optional().openapi({ example: "localhost" }),
areaFrom: z.string().optional().openapi({example: "The server we are going to connect to"}), areaFrom: z
completed: z.boolean().optional().openapi({example: true}), .string()
.optional()
.openapi({ example: "The server we are going to connect to" }),
completed: z.boolean().optional().openapi({ example: true }),
}); });
app.openapi( app.openapi(
@@ -17,11 +20,11 @@ app.openapi(
tags: ["ocme"], tags: ["ocme"],
summary: "Post New running number to be picked up.", summary: "Post New running number to be picked up.",
method: "post", method: "post",
path: "/postrunningnumber", path: "/postRunningNumber",
request: { request: {
body: { body: {
content: { content: {
"application/json": {schema: PostRunningNr}, "application/json": { schema: PostRunningNr },
}, },
}, },
}, },
@@ -30,8 +33,8 @@ app.openapi(
content: { content: {
"application/json": { "application/json": {
schema: z.object({ schema: z.object({
success: z.boolean().openapi({example: true}), success: z.boolean().openapi({ example: true }),
message: z.string().openapi({example: "Starter"}), message: z.string().openapi({ example: "Starter" }),
// data: z // data: z
// .array(z.object({sscc: z.string().optional()})) // .array(z.object({sscc: z.string().optional()}))
// .optional() // .optional()
@@ -45,9 +48,12 @@ app.openapi(
content: { content: {
"application/json": { "application/json": {
schema: z.object({ schema: z.object({
success: z.boolean().openapi({example: false}), success: z.boolean().openapi({ example: false }),
message: z.string().optional().openapi({example: "Internal Server error"}), message: z
data: z.array(z.object({})).optional().openapi({example: []}), .string()
.optional()
.openapi({ example: "Internal Server error" }),
data: z.array(z.object({})).optional().openapi({ example: [] }),
}), }),
}, },
}, },
@@ -75,11 +81,25 @@ app.openapi(
// make sure we have a vaid user being accessed thats really logged in // make sure we have a vaid user being accessed thats really logged in
try { try {
const data = await c.req.json(); const data = await c.req.json();
apiHit(c, {endpoint: "api/ocme/postRunningNumber", lastBody: data}); apiHit(c, { endpoint: "api/ocme/postRunningNumber", lastBody: data });
const postPallet = await postLabelData(data); const postPallet = await postLabelData(data);
return c.json({success: postPallet.success, message: postPallet.message, data: postPallet.data ?? []}, 200); return c.json(
{
success: postPallet.success,
message: postPallet.message,
data: postPallet.data ?? [],
},
200
);
} catch (error) { } catch (error) {
return c.json({success: false, message: "There was an error getting ocmeInfo data", data: error}, 400); return c.json(
{
success: false,
message: "There was an error getting ocmeInfo data",
data: error,
},
400
);
} }
} }
); );

View File

@@ -1,15 +1,18 @@
import {createRoute, OpenAPIHono, z} from "@hono/zod-openapi"; import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import {getInfo} from "../controller/getInfo.js"; import { getInfo } from "../controller/getInfo.js";
import {postLabelData} from "../controller/postRunningNr.js"; import { postLabelData } from "../controller/postRunningNr.js";
import {apiHit} from "../../../globalUtils/apiHits.js"; import { apiHit } from "../../../globalUtils/apiHits.js";
const app = new OpenAPIHono(); const app = new OpenAPIHono();
const PostRunningNr = z.object({ const PostRunningNr = z.object({
sscc: z.string().optional().openapi({example: "00090103830005710997"}), sscc: z.string().optional().openapi({ example: "00090103830005710997" }),
runningNr: z.string().optional().openapi({example: "localhost"}), runningNr: z.string().optional().openapi({ example: "localhost" }),
areaFrom: z.string().optional().openapi({example: "The server we are going to connect to"}), areaFrom: z
completed: z.boolean().optional().openapi({example: true}), .string()
.optional()
.openapi({ example: "The server we are going to connect to" }),
completed: z.boolean().optional().openapi({ example: true }),
}); });
app.openapi( app.openapi(
@@ -17,11 +20,11 @@ app.openapi(
tags: ["ocme"], tags: ["ocme"],
summary: "Post New running number to be picked up.", summary: "Post New running number to be picked up.",
method: "post", method: "post",
path: "/postsscc", path: "/postSSCC",
request: { request: {
body: { body: {
content: { content: {
"application/json": {schema: PostRunningNr}, "application/json": { schema: PostRunningNr },
}, },
}, },
}, },
@@ -30,8 +33,8 @@ app.openapi(
content: { content: {
"application/json": { "application/json": {
schema: z.object({ schema: z.object({
success: z.boolean().openapi({example: true}), success: z.boolean().openapi({ example: true }),
message: z.string().openapi({example: "Starter"}), message: z.string().openapi({ example: "Starter" }),
// data: z // data: z
// .array(z.object({sscc: z.string().optional()})) // .array(z.object({sscc: z.string().optional()}))
// .optional() // .optional()
@@ -45,9 +48,12 @@ app.openapi(
content: { content: {
"application/json": { "application/json": {
schema: z.object({ schema: z.object({
success: z.boolean().openapi({example: false}), success: z.boolean().openapi({ example: false }),
message: z.string().optional().openapi({example: "Internal Server error"}), message: z
data: z.array(z.object({})).optional().openapi({example: []}), .string()
.optional()
.openapi({ example: "Internal Server error" }),
data: z.array(z.object({})).optional().openapi({ example: [] }),
}), }),
}, },
}, },
@@ -75,11 +81,25 @@ app.openapi(
// make sure we have a vaid user being accessed thats really logged in // make sure we have a vaid user being accessed thats really logged in
try { try {
const data = await c.req.json(); const data = await c.req.json();
apiHit(c, {endpoint: "api/ocme/postRunningNumber", lastBody: data}); apiHit(c, { endpoint: "api/ocme/postRunningNumber", lastBody: data });
const postPallet = await postLabelData(data); const postPallet = await postLabelData(data);
return c.json({success: postPallet.success, message: postPallet.message, data: postPallet.data ?? []}, 200); return c.json(
{
success: postPallet.success,
message: postPallet.message,
data: postPallet.data ?? [],
},
200
);
} catch (error) { } catch (error) {
return c.json({success: false, message: "There was an error getting ocmeInfo data", data: error}, 400); return c.json(
{
success: false,
message: "There was an error getting ocmeInfo data",
data: error,
},
400
);
} }
} }
); );

View File

@@ -0,0 +1,25 @@
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { getInfo } from "../controller/getInfo.js";
import { apiHit } from "../../../globalUtils/apiHits.js";
import { responses } from "../../../globalUtils/routeDefs/responses.js";
import { triggerScanner } from "../controller/triggerCamera.js";
const app = new OpenAPIHono({ strict: false });
app.openapi(
createRoute({
tags: ["ocme"],
summary: "Triggers the camera at the end of the dyco.",
method: "get",
path: "/manualCameraTrigger",
responses: responses(),
}),
async (c) => {
// make sure we have a vaid user being accessed thats really logged in
apiHit(c, { endpoint: "api/auth/register" });
const manualTrigger = await triggerScanner();
console.log(manualTrigger);
return c.json({ success: true, message: "Manual triggered" });
}
);
export default app;

View File

@@ -3,9 +3,9 @@
* Phase 2 we will just reprint the tag that was generated at the line * Phase 2 we will just reprint the tag that was generated at the line
*/ */
import {createLog} from "../../../logger/logger.js"; import { createLog } from "../../../logger/logger.js";
import type {TagData} from "../tagData.js"; import type { TagData } from "../tagData.js";
import {tagStuff} from "../tags/crudTag.js"; import { tagStuff } from "../tags/crudTag.js";
export const wrapperStuff = async (tagData: TagData[]) => { export const wrapperStuff = async (tagData: TagData[]) => {
if (tagData.length != 1) { if (tagData.length != 1) {
@@ -18,18 +18,28 @@ export const wrapperStuff = async (tagData: TagData[]) => {
tagStuff(tagData); tagStuff(tagData);
} else { } else {
const tagdata = await tagStuff(tagData); const tagdata = await tagStuff(tagData);
if (!tagData) {
createLog("error", "rfid", "rfid", `No tagData was grabbed.`);
}
/** /**
* we want to make sure this pallet came from a line as its last spot if not we need to have a manual check. * we want to make sure this pallet came from a line as its last spot if not we need to have a manual check.
*/ */
const station3 = tagdata.some((n: any) => n.lastareaIn.includes("line3")); if (
!Array.isArray(tagdata) &&
tagdata?.some((n: any) => n.lastareaIn.includes("line3"))
) {
createLog("error", "rfid", "rfid", `Data passed over is not an array.`);
return;
}
const station3 = tagdata; //?.some((n: any) => n.lastareaIn.includes("line3"));
if (!station3) { if (!station3) {
createLog( createLog(
"error", "error",
"rfid", "rfid",
"rfid", "rfid",
`${tagdata.tag}, Did not come from a line please check the pallet and manually print the label.` `${tagdata[0].tag}, Did not come from a line please check the pallet and manually print the label.`
); );
// when we manually run again we want to make sure we read from the 3rd antenna this way we do not get the wrong info. // when we manually run again we want to make sure we read from the 3rd antenna this way we do not get the wrong info.
@@ -38,9 +48,19 @@ export const wrapperStuff = async (tagData: TagData[]) => {
// check if a running number exists // check if a running number exists
if (station3.runningNumber) { if (station3.runningNumber) {
createLog("info", "rfid", "rfid", `Reprint label ${station3.runningNumber}`); createLog(
"info",
"rfid",
"rfid",
`Reprint label ${station3.runningNumber}`
);
} else { } else {
createLog("info", "rfid", "rfid", `A new labels will be created and linked to this ${tagdata.tag} tag`); createLog(
"info",
"rfid",
"rfid",
`A new labels will be created and linked to this ${tagdata.tag} tag`
);
} }
} }
}; };

View File

@@ -1,23 +1,28 @@
import net from "net"; import net from "net";
import {OpenAPIHono} from "@hono/zod-openapi"; import { OpenAPIHono } from "@hono/zod-openapi";
import {createLog} from "../logger/logger.js"; import { createLog } from "../logger/logger.js";
import startTCP from "./route/startServer.js"; import startTCP from "./route/startServer.js";
import stopTCP from "./route/stopServer.js"; import stopTCP from "./route/stopServer.js";
import restartTCP from "./route/restartServer.js"; import restartTCP from "./route/restartServer.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 {eq} from "drizzle-orm"; import { eq } from "drizzle-orm";
import { postLabelData } from "../ocme/controller/postRunningNr.js";
let tcpServer: net.Server; let tcpServer: net.Server;
let tcpSockets: Set<net.Socket> = new Set(); let tcpSockets: Set<net.Socket> = new Set();
let isServerRunning = false; let isServerRunning = false;
const tcpPort = await db.select().from(settings).where(eq(settings.name, "tcpPort")); const tcpPort = await db
.select()
.from(settings)
.where(eq(settings.name, "tcpPort"));
const app = new OpenAPIHono(); const app = new OpenAPIHono();
export const startTCPServer = () => { export const startTCPServer = () => {
if (isServerRunning) return {success: false, message: "Server is already running"}; if (isServerRunning)
return { success: false, message: "Server is already running" };
tcpServer = net.createServer((socket) => { tcpServer = net.createServer((socket) => {
console.log("Client connected"); console.log("Client connected");
@@ -25,7 +30,19 @@ export const startTCPServer = () => {
tcpSockets.add(socket); tcpSockets.add(socket);
socket.on("data", (data: Buffer) => { socket.on("data", (data: Buffer) => {
console.log("Received:", data.toString()); console.log("Received:", data.toString());
socket.write("Message received"); const parseData = data.toString("utf-8").trimEnd().split(" ");
// hb from the scanners
if (parseData[0] === "HB") {
return;
}
// alert from the printers
if (parseData[0] === "ALERT:" || parseData[0] === "ALERT") {
return;
}
// from the wrapper send the data
postLabelData(parseData);
}); });
socket.on("end", () => { socket.on("end", () => {
@@ -40,16 +57,22 @@ export const startTCPServer = () => {
}); });
tcpServer.listen(tcpPort[0]?.value ?? 2222, () => { tcpServer.listen(tcpPort[0]?.value ?? 2222, () => {
createLog("info", "lst", "tcp", `TCP Server listening on port ${tcpPort[0]?.value ?? 2222}`); createLog(
"info",
"lst",
"tcp",
`TCP Server listening on port ${tcpPort[0]?.value ?? 2222}`
);
}); });
isServerRunning = true; isServerRunning = true;
return {success: true, message: "TCP Server started"}; return { success: true, message: "TCP Server started" };
}; };
// Function to stop the TCP server // Function to stop the TCP server
export const stopTCPServer = () => { export const stopTCPServer = () => {
if (!isServerRunning) return {success: false, message: "Server is not running"}; if (!isServerRunning)
return { success: false, message: "Server is not running" };
for (const socket of tcpSockets) { for (const socket of tcpSockets) {
socket.destroy(); socket.destroy();
} }
@@ -58,7 +81,7 @@ export const stopTCPServer = () => {
console.log("TCP Server stopped"); console.log("TCP Server stopped");
}); });
isServerRunning = false; isServerRunning = false;
return {success: true, message: "TCP Server stopped"}; return { success: true, message: "TCP Server stopped" };
}; };
app.route("/tcpserver/start", startTCP); app.route("/tcpserver/start", startTCP);