2026-10-04 19:04:14 +00:00
|
|
|
import type { Application, RequestHandler, Response } from "express";
|
|
|
|
|
import { Router } from "express";
|
|
|
|
|
import { z } from "zod/v4";
|
|
|
|
|
|
|
|
|
|
import { AssetParamsSchema, InventoryParamsSchema } from "../../../common/inventory";
|
|
|
|
|
import { SaveWorkstationRequestSchema } from "../../../common/workstations";
|
|
|
|
|
import type { WorkstationUseCases } from "../../application/workstation.use-cases";
|
|
|
|
|
import { buildWorkstationResponse } from "../../application/workstation-response.builder";
|
|
|
|
|
|
|
|
|
|
function fail(response: Response, code: string) {
|
|
|
|
|
response
|
|
|
|
|
.status(code === "INVALID_REQUEST" ? 400 : code.endsWith("NOT_FOUND") ? 404 : 409)
|
|
|
|
|
.json({ code, requestId: response.getHeader("x-request-id") });
|
|
|
|
|
}
|
2026-10-10 10:01:58 +00:00
|
|
|
|
2026-10-04 19:04:14 +00:00
|
|
|
export function registerWorkstationRoutes(
|
|
|
|
|
app: Application,
|
|
|
|
|
useCases: WorkstationUseCases,
|
|
|
|
|
authenticate: RequestHandler
|
|
|
|
|
) {
|
|
|
|
|
const router = Router();
|
2026-10-10 10:01:58 +00:00
|
|
|
|
2026-10-04 19:04:14 +00:00
|
|
|
for (const path of ["/:companyId/workstations", "/:companyId/workstations/:id/update"]) {
|
|
|
|
|
router.post(path, (request, response, next) => {
|
|
|
|
|
const params = (
|
|
|
|
|
path.endsWith("update") ? AssetParamsSchema : InventoryParamsSchema
|
|
|
|
|
).safeParse(request.params);
|
|
|
|
|
const body = SaveWorkstationRequestSchema.safeParse(request.body);
|
|
|
|
|
const actor = z
|
|
|
|
|
.object({ userId: z.uuid() })
|
|
|
|
|
.safeParse("session" in request ? request.session : undefined);
|
2026-10-10 10:01:58 +00:00
|
|
|
|
2026-10-04 19:04:14 +00:00
|
|
|
if (
|
|
|
|
|
!(
|
|
|
|
|
params.success &&
|
|
|
|
|
body.success &&
|
|
|
|
|
actor.success &&
|
|
|
|
|
z.strictObject({}).safeParse(request.query).success
|
|
|
|
|
)
|
|
|
|
|
) {
|
|
|
|
|
fail(response, "INVALID_REQUEST");
|
2026-10-10 10:01:58 +00:00
|
|
|
|
2026-10-04 19:04:14 +00:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
const id =
|
|
|
|
|
"id" in params.data && typeof params.data.id === "string" ? params.data.id : undefined;
|
2026-10-10 10:01:58 +00:00
|
|
|
|
2026-10-04 19:04:14 +00:00
|
|
|
useCases
|
|
|
|
|
.save(params.data.companyId, id, body.data.values, actor.data.userId)
|
|
|
|
|
.then((result) => {
|
|
|
|
|
if (!result.isSuccess) {
|
|
|
|
|
fail(response, result.error.code);
|
2026-10-10 10:01:58 +00:00
|
|
|
|
2026-10-04 19:04:14 +00:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
response.status(id ? 200 : 201).json({
|
|
|
|
|
workstation: buildWorkstationResponse(result.data.workstation, result.data.actorNames),
|
|
|
|
|
});
|
|
|
|
|
})
|
|
|
|
|
.catch(next);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
app.use("/api/assets", authenticate, router);
|
|
|
|
|
}
|