feat(forklifts): added backend forklift stuff and frontend companies

This commit is contained in:
2025-11-02 16:16:35 -06:00
parent a6cc17ccb1
commit 50cde2d8d2
52 changed files with 20619 additions and 32 deletions

View File

@@ -0,0 +1,105 @@
import axios from "axios";
import { type DrizzleError, sql } from "drizzle-orm";
import type { Request, Response } from "express";
import { Router } from "express";
import https from "https";
import { db } from "../../../../pkg/db/db.js";
import {
forkliftCompanies,
insertForkliftCompanySchema,
} from "../../../../pkg/db/schema/forkliftLeaseCompanys.js";
import { createLogger } from "../../../../pkg/logger/logger.js";
import { tryCatch } from "../../../../pkg/utils/tryCatch.js";
const router = Router();
router.post("/", async (req: Request, res: Response) => {
// when a new server is posted from localhost or 127.0.0.1 we also want to post it to the test server so we can see it from there
//res.status(200).json({ message: "Server added", ip: req.hostname });
const log = createLogger({ module: "forklift", subModule: "add company" });
const parsed = insertForkliftCompanySchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ errors: parsed.error.flatten() });
}
const { data, error } = await tryCatch(
db
.insert(forkliftCompanies)
.values({
...parsed.data,
add_user: req.user?.username,
add_date: sql`NOW()`,
upd_user: req.user?.username,
upd_date: sql`NOW()`,
})
//.onConflictDoNothing()
.returning({
name: forkliftCompanies.name,
}),
);
if (error) {
const err: DrizzleError = error;
return res.status(400).json({
message: `Error adding the server`,
error: err.cause,
});
}
if (req.hostname === "localhost" && process.env.MAIN_SERVER) {
log.info({}, "Running in dev server about to add in a new server");
const axiosInstance = axios.create({
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
baseURL: process.env.MAIN_SERVER, // e.g. "https://example.com"
withCredentials: true,
});
const loginRes = (await axiosInstance.post(
`${process.env.MAIN_SERVER}/lst/api/auth/sign-in/username`,
{
username: process.env.MAIN_SERVER_USERNAME,
password: process.env.MAIN_SERVER_PASSWORD,
},
{
headers: { "Content-Type": "application/json" },
},
)) as any;
const setCookie = loginRes.headers["set-cookie"][0];
if (!setCookie) {
throw new Error("Did not receive a Set-Cookie header from login");
}
const { data, error } = await tryCatch(
axios.post(
`${process.env.MAIN_SERVER}/lst/api/forklifts/companies`,
parsed.data,
{
headers: {
"Content-Type": "application/json",
Cookie: setCookie.split(";")[0],
},
withCredentials: true,
},
),
);
if (error) {
log.error(
{ stack: error },
"There was an error adding the company to Main Server",
);
}
log.info(
{ stack: data?.data },
"A new Company was just added to the server.",
);
}
return res
.status(201)
.json({ message: `Server ${data[0]?.name} added`, data: data });
});
export default router;

View File

@@ -0,0 +1,22 @@
import { Router } from "express";
import { requireAuth } from "../../../../pkg/middleware/authMiddleware.js";
import { restrictToHosts } from "../../../../pkg/middleware/restrictToHosts.js";
import addCompany from "./addCompany.js";
import getCompanies from "./getCompanies.js";
import updateCompany from "./updateServer.js";
const router = Router();
router.use(
"/",
requireAuth("forklifts", ["systemAdmin", "admin"]),
getCompanies,
);
router.use("/", requireAuth("forklifts", ["systemAdmin", "admin"]), addCompany);
router.use(
"/",
requireAuth("forklifts", ["systemAdmin", "admin"]),
updateCompany,
);
export default router;

View File

@@ -0,0 +1,35 @@
import { and, asc, eq } from "drizzle-orm";
import type { Request, Response } from "express";
import { Router } from "express";
import { db } from "../../../../pkg/db/db.js";
import { forkliftCompanies } from "../../../../pkg/db/schema/forkliftLeaseCompanys.js";
import { tryCatch } from "../../../../pkg/utils/tryCatch.js";
const router = Router();
router.get("/", async (req: Request, res: Response) => {
const name = req.query.name;
const conditions = [];
if (name !== undefined) {
conditions.push(eq(forkliftCompanies.name, `${name}`));
}
//conditions.push(eq(forkliftCompanies.active, true));
const { data, error } = await tryCatch(
db
.select()
.from(forkliftCompanies)
.where(and(...conditions))
.orderBy(asc(forkliftCompanies.name)),
);
if (error) {
return res.status(400).json({ error: error });
}
res.status(200).json({ message: "Current Active Companies", data: data });
});
export default router;

View File

@@ -0,0 +1,103 @@
import axios from "axios";
import { eq, sql } from "drizzle-orm";
import type { Request, Response } from "express";
import { Router } from "express";
import https from "https";
import { db } from "../../../../pkg/db/db.js";
import { forkliftCompanies } from "../../../../pkg/db/schema/forkliftLeaseCompanys.js";
import { serverData } from "../../../../pkg/db/schema/servers.js";
import { createLogger } from "../../../../pkg/logger/logger.js";
import { tryCatch } from "../../../../pkg/utils/tryCatch.js";
const router = Router();
router.patch("/:id", async (req: Request, res: Response) => {
const log = createLogger({
module: "forklifts",
subModule: "update company",
});
// when a server is updated and is posted from localhost or 127.0.0.1 we also want to post it to the test server so we can see it from there, we want to insert with update on conflict.
const id = req.params.id;
const updates: Record<string, any> = {};
console.log(req.body);
if (req.body?.name !== undefined) {
updates.name = req.body.name;
}
if (req.body?.active !== undefined) {
updates.active = req.body.active;
}
updates.upd_user = req.user!.username || "lst_user";
updates.upd_date = sql`NOW()`;
try {
if (Object.keys(updates).length > 0) {
await db
.update(forkliftCompanies)
.set(updates)
.where(eq(forkliftCompanies.id, id));
}
if (req.hostname === "localhost" && process.env.MAIN_SERVER) {
log.info({}, "Running in dev server about to add in a new server");
const axiosInstance = axios.create({
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
baseURL: process.env.MAIN_SERVER,
withCredentials: true,
});
const loginRes = (await axiosInstance.post(
`${process.env.MAIN_SERVER}/lst/api/auth/sign-in/username`,
{
username: process.env.MAIN_SERVER_USERNAME,
password: process.env.MAIN_SERVER_PASSWORD,
},
{
headers: { "Content-Type": "application/json" },
},
)) as any;
const setCookie = loginRes?.headers["set-cookie"][0];
//console.log(setCookie.split(";")[0].replace("__Secure-", ""));
if (!setCookie) {
throw new Error("Did not receive a Set-Cookie header from login");
}
const { data, error } = await tryCatch(
axios.patch(
`${process.env.MAIN_SERVER}/lst/api/forklifts/companies/${id}`,
updates,
{
headers: {
"Content-Type": "application/json",
Cookie: setCookie.split(";")[0],
},
withCredentials: true,
},
),
);
if (error) {
//console.log(error);
log.error(
{ stack: error },
"There was an error updating the company to Main Server",
);
}
log.info(
{ stack: data?.data },
"A new company was just updated to the server.",
);
}
res.status(200).json({ message: `${id} was just updated` });
} catch (error) {
//console.log(error);
res.status(200).json({ message: "Error Server updated", error });
}
});
export default router;

View File

@@ -0,0 +1,9 @@
import type { Express, Request, Response } from "express";
import { requireAuth } from "../../../pkg/middleware/authMiddleware.js";
import companies from "./companies/companiesRoutes.js";
export const setupForkliftRoutes = (app: Express, basePath: string) => {
app.use(
basePath + "/api/forklifts/companies", // will pass bc system admin but this is just telling us we need this
companies,
);
};

View File

@@ -1,23 +1,25 @@
import type { Express, Request, Response } from "express";
import { setupAuthRoutes } from "../auth/routes/routes.js";
import { setupAdminRoutes } from "../admin/routes.js";
import { setupSystemRoutes } from "../system/routes.js";
import { setupAuthRoutes } from "../auth/routes/routes.js";
import { setupForkliftRoutes } from "../forklifts/routes/routes.js";
import { setupLogisticsRoutes } from "../logistics/routes.js";
import { setupSystemRoutes } from "../system/routes.js";
export const setupRoutes = (app: Express, basePath: string) => {
// all routes
setupAuthRoutes(app, basePath);
setupAdminRoutes(app, basePath);
setupSystemRoutes(app, basePath);
setupLogisticsRoutes(app, basePath);
// all routes
setupAuthRoutes(app, basePath);
setupAdminRoutes(app, basePath);
setupSystemRoutes(app, basePath);
setupLogisticsRoutes(app, basePath);
setupForkliftRoutes(app, basePath);
// always try to go to the app weather we are in dev or in production.
app.get(basePath + "/", (req: Request, res: Response) => {
res.redirect(basePath + "/app");
});
// always try to go to the app weather we are in dev or in production.
app.get(basePath + "/", (req: Request, res: Response) => {
res.redirect(basePath + "/app");
});
// Fallback 404 handler
app.use((req: Request, res: Response) => {
res.status(404).json({ error: "Not Found" });
});
// Fallback 404 handler
app.use((req: Request, res: Response) => {
res.status(404).json({ error: "Not Found" });
});
};