Compare commits

..

4 Commits

14 changed files with 959 additions and 781 deletions

View File

@@ -2,10 +2,23 @@ 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 {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../ui/table";
import { Skeleton } from "../ui/skeleton"; import { Skeleton } from "../ui/skeleton";
//import CycleCountLog from "./CycleCountLog"; //import CycleCountLog from "./CycleCountLog";
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "../ui/select"; import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "../ui/select";
import { Controller, useForm } from "react-hook-form"; import { Controller, useForm } from "react-hook-form";
import axios from "axios"; import axios from "axios";
import { useState } from "react"; import { useState } from "react";
@@ -28,9 +41,10 @@ export default function OcmeCycleCount() {
setCounting(true); setCounting(true);
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}` },
}); });
console.log(data);
toast.success(res.data.message); toast.success(res.data.message);
setData(res.data.data); setData(res.data.data);
setCounting(false); setCounting(false);
@@ -41,11 +55,14 @@ export default function OcmeCycleCount() {
reset(); reset();
} }
}; };
return ( return (
<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">
@@ -86,7 +103,11 @@ export default function OcmeCycleCount() {
</div> </div>
</div> </div>
<Button className="m-2" type="submit" disabled={counting}> <Button className="m-2" type="submit" disabled={counting}>
{counting ? <span>Counting...</span> : <span>CycleCount</span>} {counting ? (
<span>Counting...</span>
) : (
<span>CycleCount</span>
)}
</Button> </Button>
</div> </div>
</form> </form>
@@ -105,7 +126,7 @@ export default function OcmeCycleCount() {
<TableHead>Result</TableHead> <TableHead>Result</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
{data.length === 0 ? ( {data?.length === 0 ? (
<TableBody> <TableBody>
{Array(10) {Array(10)
.fill(0) .fill(0)
@@ -140,7 +161,7 @@ export default function OcmeCycleCount() {
</TableBody> </TableBody>
) : ( ) : (
<> <>
{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`;
@@ -165,9 +186,15 @@ export default function OcmeCycleCount() {
<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 className={`font-medium ${classname}`}>
<TableCell className={`font-medium ${classname}`}>{i.stock}</TableCell> {i.ocme}
<TableCell className={`font-medium ${classname}`}>{i.info}</TableCell> </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": 54,
"oldBuild": "backend-0.1.3.zip" "oldBuild": "backend-0.1.3.zip"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -53,17 +53,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

@@ -10,7 +10,10 @@ type UpdateServerResponse = {
message: string; 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 app = await getAppInfo(devApp);
const serverInfo = await db const serverInfo = await db
.select() .select()
@@ -26,7 +29,8 @@ 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.",
}; };
} }
@@ -73,6 +77,8 @@ export const updateServer = async (devApp: string, server: string | null): Promi
, ,
]; ];
console.log(args);
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
@@ -156,7 +162,12 @@ export const updateServer = async (devApp: string, server: string | null): Promi
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);
createLog("info", "lst", "serverUpdater", `Running the update on all servers`); 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 +177,12 @@ 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: 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

@@ -6,38 +6,62 @@ import {query} from "../../sqlServer/prodSqlServer.js";
import { labelData } from "../../sqlServer/querys/materialHelpers/labelInfo.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,
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 });
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: newPost,
};
} }
}; };

View File

@@ -18,7 +18,7 @@ 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: {
@@ -48,10 +48,21 @@ app.openapi(
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

@@ -7,7 +7,9 @@ const app = new OpenAPIHono({strict: false});
const AddSetting = z.object({ const AddSetting = z.object({
name: z.string().openapi({ example: "server" }), name: z.string().openapi({ example: "server" }),
value: z.string().openapi({ example: "localhost" }), value: z.string().openapi({ example: "localhost" }),
description: z.string().openapi({example: "The server we are going to connect to"}), description: z
.string()
.openapi({ example: "The server we are going to connect to" }),
roles: z.string().openapi({ example: "admin" }), roles: z.string().openapi({ example: "admin" }),
module: z.string().openapi({ example: "production" }), module: z.string().openapi({ example: "production" }),
}); });
@@ -17,7 +19,7 @@ app.openapi(
tags: ["ocme"], tags: ["ocme"],
summary: "Get all current info", summary: "Get all current info",
method: "get", method: "get",
path: "/getinfo", path: "/getInfo",
request: { request: {
body: { body: {
content: { content: {
@@ -43,7 +45,10 @@ app.openapi(
"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
.string()
.optional()
.openapi({ example: "Internal Server error" }),
data: z.array(z.object({})).optional().openapi({ example: [] }), data: z.array(z.object({})).optional().openapi({ example: [] }),
}), }),
}, },
@@ -72,9 +77,19 @@ 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
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

@@ -13,7 +13,7 @@ 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: {
@@ -42,7 +42,10 @@ app.openapi(
"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
.string()
.optional()
.openapi({ example: "Internal Server error" }),
data: z.array(z.object({})).optional().openapi({ example: [] }), data: z.array(z.object({})).optional().openapi({ example: [] }),
}), }),
}, },
@@ -73,9 +76,15 @@ app.openapi(
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

@@ -8,7 +8,10 @@ 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
.string()
.optional()
.openapi({ example: "The server we are going to connect to" }),
completed: z.boolean().optional().openapi({ example: true }), completed: z.boolean().optional().openapi({ example: true }),
all: z.boolean().optional().openapi({ example: false }), all: z.boolean().optional().openapi({ example: false }),
}); });
@@ -20,7 +23,7 @@ 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: {
@@ -49,7 +52,10 @@ app.openapi(
"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
.string()
.optional()
.openapi({ example: "Internal Server error" }),
data: z.array(z.object({})).optional().openapi({ example: [] }), 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",
@@ -80,9 +91,23 @@ app.openapi(
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

@@ -8,7 +8,10 @@ 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
.string()
.optional()
.openapi({ example: "The server we are going to connect to" }),
completed: z.boolean().optional().openapi({ example: true }), completed: z.boolean().optional().openapi({ example: true }),
}); });
@@ -17,7 +20,7 @@ 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: {
@@ -46,7 +49,10 @@ app.openapi(
"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
.string()
.optional()
.openapi({ example: "Internal Server error" }),
data: z.array(z.object({})).optional().openapi({ example: [] }), data: z.array(z.object({})).optional().openapi({ example: [] }),
}), }),
}, },
@@ -77,9 +83,23 @@ app.openapi(
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

@@ -8,16 +8,21 @@ 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,11 @@ 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(" ");
if (parseData[0] === "HB") {
return;
}
postLabelData(parseData);
}); });
socket.on("end", () => { socket.on("end", () => {
@@ -40,7 +49,12 @@ 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;
@@ -49,7 +63,8 @@ export const startTCPServer = () => {
// 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();
} }