refactor(old app): login migration to new app

This commit is contained in:
2025-10-21 20:22:21 -05:00
parent a2a8e0ef9f
commit eb3fa4dd52
28 changed files with 2273 additions and 2140 deletions

View File

@@ -1,154 +1,152 @@
import { eq } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { settings } from "../../../../../database/schema/settings.js";
import { siloAdjustments } from "../../../../../database/schema/siloAdjustments.js";
import { greetingStuff } from "../../../../globalUtils/greetingEmail.js";
import { generateOneTimeKey } from "../../../../globalUtils/singleUseKey.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { sendEmail } from "../../../notifications/controller/sendMail.js";
import {
getSettings,
serverSettings,
} from "../../../server/controller/settings/getSettings.js";
import { query } from "../../../sqlServer/prodSqlServer.js";
import { siloQuery } from "../../../sqlServer/querys/silo/siloQuery.js";
import { postAdjustment } from "./postAdjustment.js";
import { siloAdjustments } from "../../../../../database/schema/siloAdjustments.js";
import { greetingStuff } from "../../../../globalUtils/greetingEmail.js";
import { sendEmail } from "../../../notifications/controller/sendMail.js";
import { settings } from "../../../../../database/schema/settings.js";
import { generateOneTimeKey } from "../../../../globalUtils/singleUseKey.js";
import { eq } from "drizzle-orm";
import {
getSettings,
serverSettings,
} from "../../../server/controller/settings/getSettings.js";
export const createSiloAdjustment = async (
data: any | null,
user: any | null
data: any | null,
user: any | null,
) => {
/**
* Creates a silo adjustment based off warehouse, location, and qty.
* qty will come from the hmi, prolink, or silo patrol
*/
// const { data: set, error: setError } = await tryCatch(
// db.select().from(settings)
// );
/**
* Creates a silo adjustment based off warehouse, location, and qty.
* qty will come from the hmi, prolink, or silo patrol
*/
// const { data: set, error: setError } = await tryCatch(
// db.select().from(settings)
// );
// const { data: set, error: setError } = await tryCatch(getSettings());
// const { data: set, error: setError } = await tryCatch(getSettings());
// if (setError) {
// return {
// success: false,
// message: `There was an error getting setting data to post to the server.`,
// data: setError,
// };
// }
// if (setError) {
// return {
// success: false,
// message: `There was an error getting setting data to post to the server.`,
// data: setError,
// };
// }
const set = serverSettings.length === 0 ? [] : serverSettings;
// getting stock data first so we have it prior to the adjustment
const { data: s, error: stockError } = await tryCatch(
query(siloQuery, "Silo data Query")
);
const set = serverSettings.length === 0 ? [] : serverSettings;
// getting stock data first so we have it prior to the adjustment
const { data: s, error: stockError } = await tryCatch(
query(siloQuery, "Silo data Query"),
);
if (stockError) {
return {
success: false,
message: `There was an error getting stock data to post to the server.`,
data: stockError,
};
}
const stock: any = s?.data as any;
const { data: a, error: errorAdj } = await tryCatch(
postAdjustment(data, user.prod)
);
if (stockError) {
return {
success: false,
message: `There was an error getting stock data to post to the server.`,
data: stockError,
};
}
const stock: any = s?.data as any;
const { data: a, error: errorAdj } = await tryCatch(postAdjustment(data));
if (errorAdj) {
return {
success: false,
message: `There was an error doing the silo adjustment.`,
data: errorAdj,
};
}
/**
* Checking to see the difference, and send email if +/- 5% will change later if needed
*/
if (errorAdj) {
return {
success: false,
message: `There was an error doing the silo adjustment.`,
data: errorAdj,
};
}
/**
* Checking to see the difference, and send email if +/- 5% will change later if needed
*/
const sa: any = a;
const sa: any = a;
if (!sa.success) {
console.log(`insde error`);
return {
success: sa.success,
message: sa.message,
data: sa.data,
};
}
if (!sa.success) {
console.log(`inside error`);
return {
success: sa.success,
message: sa.message,
data: sa.data,
};
}
const stockNummy = stock.filter((s: any) => s.LocationID === data.laneId);
const theDiff =
((data.quantity - stockNummy[0].Stock_Total) /
((data.quantity + stockNummy[0].Stock_Total) / 2)) *
100;
const stockNummy = stock.filter((s: any) => s.LocationID === data.laneId);
const theDiff =
((data.quantity - stockNummy[0].Stock_Total) /
((data.quantity + stockNummy[0].Stock_Total) / 2)) *
100;
/**
* Post the data to our db.
*/
/**
* Post the data to our db.
*/
//console.log(stockNummy);
const { data: postAdj, error: postAdjError } = await tryCatch(
db
.insert(siloAdjustments)
.values({
warehouseID: data.warehouseId,
locationID: data.laneId,
currentStockLevel: stockNummy[0].Stock_Total,
newLevel: data.quantity,
lastDateAdjusted: new Date(stockNummy[0].LastAdjustment),
add_user: user.username,
})
.returning({ id: siloAdjustments.siloAdjust_id })
);
//console.log(stockNummy);
const { data: postAdj, error: postAdjError } = await tryCatch(
db
.insert(siloAdjustments)
.values({
warehouseID: data.warehouseId,
locationID: data.laneId,
currentStockLevel: stockNummy[0].Stock_Total,
newLevel: data.quantity,
lastDateAdjusted: new Date(stockNummy[0].LastAdjustment),
add_user: user.username,
})
.returning({ id: siloAdjustments.siloAdjust_id }),
);
if (postAdjError) {
//console.log(postAdjError);
return {
success: false,
message: `There was an error posting the new adjustment.`,
data: postAdjError,
};
}
let adj: any = a;
if (Math.abs(theDiff) > 5) {
// console.log(`Send for comment due to being: ${theDiff.toFixed(2)}%`);
const server = set.filter((n: any) => n.name === "server");
if (postAdjError) {
//console.log(postAdjError);
return {
success: false,
message: `There was an error posting the new adjustment.`,
data: postAdjError,
};
}
let adj: any = a;
if (Math.abs(theDiff) > 5) {
// console.log(`Send for comment due to being: ${theDiff.toFixed(2)}%`);
const server = set.filter((n: any) => n.name === "server");
const port = set.filter((n: any) => n.name === "serverPort");
const key = await generateOneTimeKey();
const updateKey = await db
.update(siloAdjustments)
.set({ commentKey: key })
.where(eq(siloAdjustments.siloAdjust_id, postAdj[0].id));
const port = set.filter((n: any) => n.name === "serverPort");
const key = await generateOneTimeKey();
const updateKey = await db
.update(siloAdjustments)
.set({ commentKey: key })
.where(eq(siloAdjustments.siloAdjust_id, postAdj[0].id));
const emailSetup = {
email: user.email,
subject: `Alert - Siloadjustment was done with a descrepancy of 5% or greater`,
template: "siloAdjustmentComment",
context: {
greeting: await greetingStuff(),
siloName: stockNummy[0].Description,
variance: `${theDiff.toFixed(2)}%`,
currentLevel: stockNummy[0].Stock_Total,
newLevel: data.quantity,
variancePer: 5,
adjustID: `${postAdj[0].id}&${key}`,
server: server[0].value,
port: port[0].value,
},
};
const emailSetup = {
email: user.email,
subject: `Alert - Siloadjustment was done with a descrepancy of 5% or greater`,
template: "siloAdjustmentComment",
context: {
greeting: await greetingStuff(),
siloName: stockNummy[0].Description,
variance: `${theDiff.toFixed(2)}%`,
currentLevel: stockNummy[0].Stock_Total,
newLevel: data.quantity,
variancePer: 5,
adjustID: `${postAdj[0].id}&${key}`,
server: server[0].value,
port: port[0].value,
},
};
//console.log(emailSetup);
//console.log(emailSetup);
await sendEmail(emailSetup);
return {
success: adj.success,
message: `Silo adjustmnet was completed you will also receive and email due to the adjustment having a variation of ${Math.abs(
theDiff
).toFixed(2)}%`,
data: adj.data,
};
} else {
return { success: adj.success, message: adj.message, data: adj.data };
}
await sendEmail(emailSetup);
return {
success: adj.success,
message: `Silo adjustmnet was completed you will also receive and email due to the adjustment having a variation of ${Math.abs(
theDiff,
).toFixed(2)}%`,
data: adj.data,
};
} else {
return { success: adj.success, message: adj.message, data: adj.data };
}
};

View File

@@ -2,99 +2,99 @@ import axios from "axios";
import { prodEndpointCreation } from "../../../../globalUtils/createUrl.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
export const postAdjustment = async (data: any, prod: any) => {
if (data.warehouseId === undefined) {
return {
sucess: false,
message: `Missing mandatory field: warehouseID`,
data: { error: `Missing mandatory field: warehouseID` },
};
}
export const postAdjustment = async (data: any) => {
if (data.warehouseId === undefined) {
return {
sucess: false,
message: `Missing mandatory field: warehouseID`,
data: { error: `Missing mandatory field: warehouseID` },
};
}
if (data.laneId === undefined) {
return {
sucess: false,
message: `Missing mandatory field: locationID`,
data: { error: `Missing mandatory field: locationID` },
};
}
if (data.laneId === undefined) {
return {
sucess: false,
message: `Missing mandatory field: locationID`,
data: { error: `Missing mandatory field: locationID` },
};
}
if (data.quantity == "0") {
return {
sucess: false,
message: `You entered 0 for the quantity to post, quantity needs to be at leave 1`,
data: {
error: `You entered 0 for the quantity to post, quantity needs to be at leave 1`,
},
};
}
if (data.quantity == "0") {
return {
sucess: false,
message: `You entered 0 for the quantity to post, quantity needs to be at leave 1`,
data: {
error: `You entered 0 for the quantity to post, quantity needs to be at leave 1`,
},
};
}
const siloAdjustment = {
warehouseId: data.warehouseId,
laneId: data.laneId,
quantity: data.quantity,
};
const siloAdjustment = {
warehouseId: data.warehouseId,
laneId: data.laneId,
quantity: data.quantity,
};
let url = await prodEndpointCreation(
"/public/v1.0/Warehousing/AdjustSiloStockLevel"
);
let url = await prodEndpointCreation(
"/public/v1.0/Warehousing/AdjustSiloStockLevel",
);
const { data: silo, error } = await tryCatch(
axios.post(url, siloAdjustment, {
headers: {
"X-API-Key": process.env.TEC_API_KEY || "",
"Content-Type": "application/json",
},
})
);
let e = error as any;
if (e) {
console.log(e.response);
if (e.status === 401) {
const data = {
success: false,
message: `There was error posting the data: ${JSON.stringify(
e.response?.data
)}`,
data: {
status: e.response?.status,
statusText: e.response?.statusText,
data: e.response?.data,
},
};
return data;
} else {
return {
success: false,
message: "Error in posting the silo adjustment.",
data: {
status: e.response?.status,
statusText: e.response?.statusText,
data: e.response?.data,
},
};
}
}
const { data: silo, error } = await tryCatch(
axios.post(url, siloAdjustment, {
headers: {
"X-API-Key": process.env.TEC_API_KEY || "",
"Content-Type": "application/json",
},
}),
);
let e = error as any;
if (e) {
console.log(e.response);
if (e.status === 401) {
const data = {
success: false,
message: `There was error posting the data: ${JSON.stringify(
e.response?.data,
)}`,
data: {
status: e.response?.status,
statusText: e.response?.statusText,
data: e.response?.data,
},
};
return data;
} else {
return {
success: false,
message: "Error in posting the silo adjustment.",
data: {
status: e.response?.status,
statusText: e.response?.statusText,
data: e.response?.data,
},
};
}
}
if (silo?.status !== 200) {
return {
success: false,
message: "Error in posting the silo adjustment",
data: {
status: silo?.status,
statusText: silo?.statusText,
data: silo?.data,
},
};
} else {
return {
success: true,
message: "Adjustment was completed",
data: {
status: silo.status,
statusText: silo.statusText,
data: silo.data,
},
};
}
if (silo?.status !== 200) {
return {
success: false,
message: "Error in posting the silo adjustment",
data: {
status: silo?.status,
statusText: silo?.statusText,
data: silo?.data,
},
};
} else {
return {
success: true,
message: "Adjustment was completed",
data: {
status: silo.status,
statusText: silo.statusText,
data: silo.data,
},
};
}
};

View File

@@ -1,9 +1,10 @@
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { ordersIn } from "../../controller/dm/ordersIn/ordersIn.js";
import { verify } from "hono/jwt";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { apiHit } from "../../../../globalUtils/apiHits.js";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { authMiddleware } from "../../../auth/middleware/authMiddleware.js";
import { ordersIn } from "../../controller/dm/ordersIn/ordersIn.js";
const app = new OpenAPIHono();
@@ -15,61 +16,53 @@ const app = new OpenAPIHono();
// })
// .openapi("User");
app.openapi(
createRoute({
tags: ["logistics"],
summary: "Post orders to DM",
method: "post",
path: "/postbulkorders",
// request: {
// body: {
// content: {
// "application/json": { schema: Body },
// },
// },
// },
// description:
// "Provided a running number and lot number you can consume material.",
responses: responses(),
}),
async (c) => {
apiHit(c, { endpoint: "/postbulkorders" });
const body = await c.req.parseBody();
const authHeader = c.req.header("Authorization");
const token = authHeader?.split("Bearer ")[1] || "";
//console.log(body); // File | string
createRoute({
tags: ["logistics"],
summary: "Post orders to DM",
method: "post",
path: "/postbulkorders",
middleware: authMiddleware,
// request: {
// body: {
// content: {
// "application/json": { schema: Body },
// },
// },
// },
// description:
// "Provided a running number and lot number you can consume material.",
responses: responses(),
}),
async (c) => {
apiHit(c, { endpoint: "/postbulkorders" });
const body = await c.req.parseBody();
//console.log(body); // File | string
// if (body["fileType"] === "standard") {
// console.log(`doing standard orders in.`);
// }
const { data: payload, error: pe } = await tryCatch(
verify(token, process.env.JWT_SECRET!)
);
// if (body["fileType"] === "standard") {
// console.log(`doing standard orders in.`);
// }
if (pe) {
return c.json({ success: false, message: "Unauthorized" }, 401);
}
const { data: orders, error } = await tryCatch(
ordersIn(body, c.get("user")),
);
const { data: orders, error } = await tryCatch(
ordersIn(body, payload.user)
);
if (error) {
console.log(error);
return c.json(
{
success: false,
message: "Error posting Orders",
data: error,
},
400,
);
}
if (error) {
console.log(error);
return c.json(
{
success: false,
message: "Error posting Orders",
data: error,
},
400
);
}
return c.json({
success: orders?.success ?? false,
message: orders?.message ?? "Error posting forecast",
data: orders?.data ?? [],
});
}
return c.json({
success: orders?.success ?? false,
message: orders?.message ?? "Error posting forecast",
data: orders?.data ?? [],
});
},
);
export default app;

View File

@@ -1,10 +1,11 @@
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { ordersIn } from "../../controller/dm/ordersIn/ordersIn.js";
import { verify } from "hono/jwt";
import { forecastIn } from "../../controller/dm/forecast/forecastIn.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { apiHit } from "../../../../globalUtils/apiHits.js";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { authMiddleware } from "../../../auth/middleware/authMiddleware.js";
import { forecastIn } from "../../controller/dm/forecast/forecastIn.js";
import { ordersIn } from "../../controller/dm/ordersIn/ordersIn.js";
const app = new OpenAPIHono();
@@ -16,61 +17,54 @@ const app = new OpenAPIHono();
// })
// .openapi("User");
app.openapi(
createRoute({
tags: ["logistics"],
summary: "Post forecast to DM",
method: "post",
path: "/postforecastin",
// request: {
// body: {
// content: {
// "application/json": { schema: Body },
// },
// },
// },
// description:
// "Provided a running number and lot number you can consume material.",
responses: responses(),
}),
async (c) => {
apiHit(c, { endpoint: "/postforecastin" });
const body = await c.req.parseBody();
const authHeader = c.req.header("Authorization");
const token = authHeader?.split("Bearer ")[1] || "";
//console.log(body); // File | string
createRoute({
tags: ["logistics"],
summary: "Post forecast to DM",
method: "post",
path: "/postforecastin",
middleware: authMiddleware,
// request: {
// body: {
// content: {
// "application/json": { schema: Body },
// },
// },
// },
// description:
// "Provided a running number and lot number you can consume material.",
responses: responses(),
}),
async (c) => {
apiHit(c, { endpoint: "/postforecastin" });
const body = await c.req.parseBody();
// if (body["fileType"] === "standard") {
// console.log(`doing standard orders in.`);
// }
const { data: payload, error: pe } = await tryCatch(
verify(token, process.env.JWT_SECRET!)
);
//console.log(body); // File | string
if (pe) {
return c.json({ success: false, message: "Unauthorized" }, 401);
}
// if (body["fileType"] === "standard") {
// console.log(`doing standard orders in.`);
// }
const { data: orders, error } = await tryCatch(
forecastIn(body, payload.user)
);
const { data: orders, error } = await tryCatch(
forecastIn(body, c.get("user")),
);
if (error) {
console.log(error);
return c.json(
{
success: false,
message: "Error posting forecast",
data: error,
},
400
);
}
if (error) {
console.log(error);
return c.json(
{
success: false,
message: "Error posting forecast",
data: error,
},
400,
);
}
return c.json({
success: orders?.success ?? false,
message: orders?.message ?? "Error posting forecast",
data: orders?.data ?? [],
});
}
return c.json({
success: orders?.success ?? false,
message: orders?.message ?? "Error posting forecast",
data: orders?.data ?? [],
});
},
);
export default app;

View File

@@ -1,10 +1,10 @@
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { format } from "date-fns";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { standardTemplate } from "../../controller/dm/ordersIn/createTemplate.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { standardForCastTemplate } from "../../controller/dm/forecast/createTemplate.js";
import { apiHit } from "../../../../globalUtils/apiHits.js";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { standardForCastTemplate } from "../../controller/dm/forecast/createTemplate.js";
const app = new OpenAPIHono();
@@ -16,52 +16,52 @@ const app = new OpenAPIHono();
// })
// .openapi("User");
app.openapi(
createRoute({
tags: ["logistics"],
summary: "Gets the standard Forecast Template",
method: "get",
path: "/bulkforcasttemplate",
// request: {
// body: {
// content: {
// "application/json": { schema: Body },
// },
// },
// },
// description:
// "Provided a running number and lot number you can consume material.",
responses: responses(),
}),
async (c: any) => {
apiHit(c, { endpoint: "/bulkforcasttemplate" });
const defaultFilename = `bulkForcastTemplate-${format(
new Date(Date.now()),
"M-d-yyyy"
)}.xlsx`;
const filename = c.req.query("filename") || defaultFilename;
const { data, error } = await tryCatch(standardForCastTemplate());
createRoute({
tags: ["logistics"],
summary: "Gets the standard Forecast Template",
method: "get",
path: "/bulkforcasttemplate",
// request: {
// body: {
// content: {
// "application/json": { schema: Body },
// },
// },
// },
// description:
// "Provided a running number and lot number you can consume material.",
responses: responses(),
}),
async (c: any) => {
apiHit(c, { endpoint: "/bulkforcasttemplate" });
const defaultFilename = `bulkForcastTemplate-${format(
new Date(Date.now()),
"M-d-yyyy",
)}.xlsx`;
const filename = c.req.query("filename") || defaultFilename;
const { data, error } = await tryCatch(standardForCastTemplate());
if (error) {
return c.json({
success: false,
message: "Error creating template",
data: error,
});
}
if (error) {
return c.json({
success: false,
message: "Error creating template",
data: error,
});
}
return new Response(data, {
headers: {
"Content-Type":
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Content-Disposition": `attachment; filename="${filename}"`,
},
});
return new Response(data, {
headers: {
"Content-Type":
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Content-Disposition": `attachment; filename="${filename}"`,
},
});
// return c.json({
// success: data.success,
// message: data.message,
// data: data.data,
// });
}
// return c.json({
// success: data.success,
// message: data.message,
// data: data.data,
// });
},
);
export default app;

View File

@@ -1,78 +1,74 @@
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { verify } from "hono/jwt";
import { authMiddleware } from "../../../auth/middleware/authMiddleware.js";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { createSiloAdjustment } from "../../controller/siloAdjustments/createSiloAdjustment.js";
import { apiHit } from "../../../../globalUtils/apiHits.js";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { authMiddleware } from "../../../auth/middleware/authMiddleware.js";
import { createSiloAdjustment } from "../../controller/siloAdjustments/createSiloAdjustment.js";
const app = new OpenAPIHono();
const responseSchema = z.object({
success: z.boolean().optional().openapi({ example: true }),
message: z.string().optional().openapi({ example: "user access" }),
success: z.boolean().optional().openapi({ example: true }),
message: z.string().optional().openapi({ example: "user access" }),
});
app.openapi(
createRoute({
tags: ["logistics"],
summary: "Creates silo adjustmennt",
method: "post",
path: "/createsiloadjustment",
middleware: authMiddleware,
description:
"Creates a silo adjustment for the silo if and stores the stock numbers.",
responses: responses(),
}),
async (c) => {
const { data, error } = await tryCatch(c.req.json());
createRoute({
tags: ["logistics"],
summary: "Creates silo adjustmennt",
method: "post",
path: "/createsiloadjustment",
middleware: authMiddleware,
description:
"Creates a silo adjustment for the silo if and stores the stock numbers.",
responses: responses(),
}),
async (c) => {
const { data, error } = await tryCatch(c.req.json());
if (error) {
return c.json(
{
success: false,
message: "Missing data please try again",
error,
},
400
);
}
apiHit(c, { endpoint: "/createsiloadjustment", lastBody: data });
const authHeader = c.req.header("Authorization");
const token = authHeader?.split("Bearer ")[1] || "";
if (error) {
return c.json(
{
success: false,
message: "Missing data please try again",
error,
},
400,
);
}
apiHit(c, { endpoint: "/createsiloadjustment", lastBody: data });
try {
const payload = await verify(token, process.env.JWT_SECRET!);
try {
//return apiReturn(c, true, access?.message, access?.data, 200);
const createSiloAdj = await createSiloAdjustment(
data,
payload.user
);
const user = c.get("user");
return c.json(
{
success: createSiloAdj.success,
message: createSiloAdj.message,
data: createSiloAdj.data,
},
200
);
} catch (error) {
//console.log(error);
//return apiReturn(c, false, "Error in setting the user access", error, 400);
return c.json(
{
success: false,
message: "Missing data please try again",
error,
},
400
);
}
} catch (error) {
return c.json({ success: false, message: "Unauthorized" }, 401);
}
}
try {
try {
//return apiReturn(c, true, access?.message, access?.data, 200);
const createSiloAdj = await createSiloAdjustment(data, c.get("user"));
return c.json(
{
success: createSiloAdj.success,
message: createSiloAdj.message,
data: createSiloAdj.data,
},
200,
);
} catch (error) {
//console.log(error);
//return apiReturn(c, false, "Error in setting the user access", error, 400);
return c.json(
{
success: false,
message: "Missing data please try again",
error,
},
400,
);
}
} catch (error) {
return c.json({ success: false, message: "Unauthorized" }, 401);
}
},
);
export default app;

View File

@@ -1,88 +1,85 @@
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { verify } from "hono/jwt";
import { authMiddleware } from "../../../auth/middleware/authMiddleware.js";
import { apiHit } from "../../../../globalUtils/apiHits.js";
import { responses } from "../../../../globalUtils/routeDefs/responses.js";
import { authMiddleware } from "../../../auth/middleware/authMiddleware.js";
import { createSiloAdjustment } from "../../controller/siloAdjustments/createSiloAdjustment.js";
import { postSiloComment } from "../../controller/siloAdjustments/postComment.js";
import { apiHit } from "../../../../globalUtils/apiHits.js";
const app = new OpenAPIHono();
const ParamsSchema = z.object({
adjId: z
.string()
.min(3)
.openapi({
param: {
name: "adjId",
in: "path",
},
example: "3b555052-a960-4301-8d38-a6f1acb98dbe",
}),
adjId: z
.string()
.min(3)
.openapi({
param: {
name: "adjId",
in: "path",
},
example: "3b555052-a960-4301-8d38-a6f1acb98dbe",
}),
});
const Body = z.object({
comment: z
.string()
.openapi({ example: "Reason to why i had a badd adjustment." }),
comment: z
.string()
.openapi({ example: "Reason to why i had a badd adjustment." }),
});
app.openapi(
createRoute({
tags: ["logistics"],
summary: "Post a comment to why you had a discrepancy",
method: "post",
path: "/postcomment/:adjId",
middleware: authMiddleware,
request: {
params: ParamsSchema,
body: { content: { "application/json": { schema: Body } } },
},
// description:
// "Creates a silo adjustment for the silo if and stores the stock numbers.",
responses: responses(),
}),
async (c: any) => {
apiHit(c, { endpoint: "/postcomment" });
const authHeader = c.req.header("Authorization");
const token = authHeader?.split("Bearer ")[1] || "";
const { adjId } = c.req.valid("param");
createRoute({
tags: ["logistics"],
summary: "Post a comment to why you had a discrepancy",
method: "post",
path: "/postcomment/:adjId",
middleware: authMiddleware,
request: {
params: ParamsSchema,
body: { content: { "application/json": { schema: Body } } },
},
// description:
// "Creates a silo adjustment for the silo if and stores the stock numbers.",
responses: responses(),
}),
async (c: any) => {
apiHit(c, { endpoint: "/postcomment" });
const { adjId } = c.req.valid("param");
try {
const payload = await verify(token, process.env.JWT_SECRET!);
try {
//return apiReturn(c, true, access?.message, access?.data, 200);
const data = await c.req.json();
try {
try {
//return apiReturn(c, true, access?.message, access?.data, 200);
const data = await c.req.json();
const addComment = await postSiloComment(
adjId,
data.comment,
data.key,
payload.user
);
const addComment = await postSiloComment(
adjId,
data.comment,
data.key,
c.get("user"),
);
console.log(addComment);
return c.json(
{
success: addComment.success,
message: addComment.message,
data: addComment.data,
},
200
);
} catch (error) {
return c.json(
{
success: false,
message: "Missing data please try again",
error,
},
400
);
}
} catch (error) {
return c.json({ success: false, message: "Unauthorized" }, 401);
}
}
console.log(addComment);
return c.json(
{
success: addComment.success,
message: addComment.message,
data: addComment.data,
},
200,
);
} catch (error) {
return c.json(
{
success: false,
message: "Missing data please try again",
error,
},
400,
);
}
} catch (error) {
return c.json({ success: false, message: "Unauthorized" }, 401);
}
},
);
export default app;