Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

refactor: use a different cookie per company in MES

Brad Barbin75b44a52bcde
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index 034f32b03c..0065062acf 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -30,7 +30,6 @@ import {
import {
getLocationAndWorkCenter,
setLocationAndWorkCenter,
- updateLocationAndWorkCenter,
} from "~/services/location.server";
import { defaultLayout } from "~/utils/layout";
import { path } from "~/utils/path";
@@ -82,33 +81,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
throw new Error(`No locations found for ${company.name}`);
}
- if (!locations.data.some((l) => l.id === storedLocations.location)) {
- const { locationId, workCenterId } = await updateLocationAndWorkCenter(
- request,
- client,
- {
- companyId: companyId!,
- }
- );
-
- storedLocations.location = locationId;
- storedLocations.workCenter = workCenterId;
- storedLocations.updated = true;
-
- // TODO: replace this garbage once middleware is available.
- // for now the race condition makes it so that each route has to be self-healing
- let freshData = await Promise.all([
- getLocationsByCompany(client, companyId),
- getActiveJobCount(client, {
- employeeId: userId,
- companyId,
- }),
- ]);
-
- locations = freshData[0];
- activeEvents = freshData[1];
- }
-
return json(
{
session: {
@@ -127,6 +99,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
? {
headers: {
"Set-Cookie": setLocationAndWorkCenter(
+ companyId,
storedLocations.location,
storedLocations.workCenter
),
diff --git a/apps/mes/app/routes/x+/company.switch.$companyId.tsx b/apps/mes/app/routes/x+/company.switch.$companyId.tsx
index e41ed5fd1f..ad26bd83d8 100644
--- a/apps/mes/app/routes/x+/company.switch.$companyId.tsx
+++ b/apps/mes/app/routes/x+/company.switch.$companyId.tsx
@@ -7,8 +7,8 @@ import {
} from "@carbon/auth/session.server";
import { redirect, type ActionFunctionArgs } from "@vercel/remix";
import {
+ getLocationAndWorkCenter,
setLocationAndWorkCenter,
- updateLocationAndWorkCenter,
} from "~/services/location.server";
import { path, requestReferrer } from "~/utils/path";
@@ -35,23 +35,29 @@ export async function action({ request, params }: ActionFunctionArgs) {
await destroyAuthSession(request);
}
- const { locationId, workCenterId } = await updateLocationAndWorkCenter(
- request,
- client,
- {
- companyId: companyId!,
- }
- );
-
const sessionCookie = await updateCompanySession(request, companyId!);
- const workCenterLocationCookie = await setLocationAndWorkCenter(
- locationId,
- workCenterId
- );
+ const storedLocations = await getLocationAndWorkCenter(request, client, {
+ userId,
+ companyId: companyId!,
+ });
+
+ if (storedLocations.updated) {
+ const workCenterLocationCookie = await setLocationAndWorkCenter(
+ companyId!,
+ storedLocations.location,
+ storedLocations.workCenter
+ );
+
+ throw redirect(path.to.authenticatedRoot, {
+ headers: {
+ "Set-Cookie": `${sessionCookie} ${workCenterLocationCookie}`,
+ },
+ });
+ }
throw redirect(path.to.authenticatedRoot, {
headers: {
- "Set-Cookie": `${sessionCookie} ${workCenterLocationCookie}`,
+ "Set-Cookie": sessionCookie,
},
});
}
diff --git a/apps/mes/app/routes/x+/jobs.$workCenterId.tsx b/apps/mes/app/routes/x+/jobs.$workCenterId.tsx
index fd3cc0dd02..41bb193ca8 100644
--- a/apps/mes/app/routes/x+/jobs.$workCenterId.tsx
+++ b/apps/mes/app/routes/x+/jobs.$workCenterId.tsx
@@ -37,7 +37,6 @@ import {
import {
getLocationAndWorkCenter,
setLocationAndWorkCenter,
- updateLocationAndWorkCenter,
} from "~/services/location.server";
import { makeDurations } from "~/utils/durations";
import { path } from "~/utils/path";
@@ -60,21 +59,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (workCenter.error) {
throw new Error("Work center not found");
}
- if (workCenter.data?.companyId !== companyId) {
- // TODO: replace this garbage once middleware is available.
- // for now the race condition makes it so that each route has to be self-healing
- const { locationId, workCenterId } = await updateLocationAndWorkCenter(
- request,
- client,
- {
- companyId: companyId!,
- }
- );
-
- storedLocations.location = locationId;
- storedLocations.workCenter = workCenterId;
- storedLocations.updated = true;
- }
const [operations, workCenters] = await Promise.all([
getJobOperationsByWorkCenter(client, {
@@ -93,6 +77,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return json(payload, {
headers: {
"Set-Cookie": setLocationAndWorkCenter(
+ companyId,
storedLocations.location,
workCenterId
),
diff --git a/apps/mes/app/routes/x+/location.tsx b/apps/mes/app/routes/x+/location.tsx
index f7403a0bc6..8ae3dad37f 100644
--- a/apps/mes/app/routes/x+/location.tsx
+++ b/apps/mes/app/routes/x+/location.tsx
@@ -8,7 +8,7 @@ import { path } from "~/utils/path";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {});
+ const { client, companyId } = await requirePermissions(request, {});
const formData = await request.formData();
const currentLocation = formData.get("location");
@@ -21,7 +21,11 @@ export async function action({ request }: ActionFunctionArgs) {
throw redirect(path.to.authenticatedRoot, {
headers: {
- "Set-Cookie": setLocationAndWorkCenter(currentLocation, workCenter),
+ "Set-Cookie": setLocationAndWorkCenter(
+ companyId,
+ currentLocation,
+ workCenter
+ ),
},
});
}
diff --git a/apps/mes/app/services/location.server.ts b/apps/mes/app/services/location.server.ts
index b33a26cf08..e7d7291661 100644
--- a/apps/mes/app/services/location.server.ts
+++ b/apps/mes/app/services/location.server.ts
@@ -1,91 +1,34 @@
-import { error } from "@carbon/auth";
-import { flash } from "@carbon/auth/session.server";
import type { Database } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
-import { redirect } from "@vercel/remix";
import * as cookie from "cookie";
-import { path, requestReferrer } from "~/utils/path";
-import {
- getLocationsByCompany,
- getWorkCentersByLocation,
-} from "./jobs.service";
-const locationCookieName = "location";
-const workCenterCookieName = "workCenter";
-
-export function getLocation(request: Request): string | null {
- const cookieHeader = request.headers.get("cookie");
- const parsed = cookieHeader
- ? cookie.parse(cookieHeader)[locationCookieName]
- : null;
- return parsed || null;
-}
-
-export function setLocation(location: string) {
- return cookie.serialize(locationCookieName, location, {
- path: "/",
- maxAge: 31536000,
- });
-}
-
-export function getWorkCenter(request: Request): string | null {
- const cookieHeader = request.headers.get("cookie");
- const parsed = cookieHeader
- ? cookie.parse(cookieHeader)[workCenterCookieName]
- : null;
- return parsed || null;
-}
-
-export function setWorkCenter(workCenter: string) {
- return cookie.serialize(workCenterCookieName, workCenter, {
- path: "/",
- maxAge: 31536000,
- });
-}
-
-export async function updateLocationAndWorkCenter(
+export function getCompanySettings(
request: Request,
- client: SupabaseClient<Database>,
- args: { companyId: string }
-) {
- const location = await getLocationsByCompany(client, args.companyId!);
- if (!location.data || location.data.length === 0) {
- throw redirect(
- requestReferrer(request) ?? path.to.authenticatedRoot,
- await flash(request, error(null, "Location not found"))
- );
- }
- const workCenters = await getWorkCentersByLocation(
- client,
- location.data[0].id
- );
- if (!workCenters.data || workCenters.data.length === 0) {
- throw redirect(
- requestReferrer(request) ?? path.to.authenticatedRoot,
- await flash(request, error(null, "Location not found"))
- );
+ companyId: string
+):
+ | { location: string; workCenter: string }
+ | { location: undefined; workCenter: undefined } {
+ const cookieHeader = request.headers.get("cookie");
+ const parsed = cookieHeader ? cookie.parse(cookieHeader)[companyId] : null;
+ if (parsed) {
+ const [location, workCenter] = parsed.split(":");
+ return { location, workCenter };
}
-
return {
- locationId: location.data[0].id,
- workCenterId: workCenters.data[0].id,
+ location: undefined,
+ workCenter: undefined,
};
}
export function setLocationAndWorkCenter(
+ companyId: string,
currentLocation: string,
workCenter: string
) {
- return [
- cookie.serialize(locationCookieName, currentLocation, {
- path: "/",
- maxAge: 31536000,
- }),
- cookie.serialize(workCenterCookieName, workCenter, {
- path: "/",
- maxAge: 31536000,
- }),
- ].join(",");
+ return cookie.serialize(companyId, `${currentLocation}:${workCenter}`, {
+ path: "/",
+ maxAge: 31536000,
+ });
}
export async function getLocationAndWorkCenter(
@@ -97,8 +40,7 @@ export async function getLocationAndWorkCenter(
}
) {
const { userId, companyId } = args;
- let location = getLocation(request);
- let workCenter = getWorkCenter(request);
+ let { location, workCenter } = getCompanySettings(request, companyId);
let updated = false;
@@ -113,7 +55,6 @@ export async function getLocationAndWorkCenter(
if (employeeJob.data && employeeJob.data.locationId) {
location = employeeJob.data.locationId;
updated = true;
- setLocation(location);
} else {
const locations = await client
.from("location")
@@ -141,6 +82,9 @@ export async function getLocationAndWorkCenter(
}
if (!workCenter) throw new Error("Failed to get a valid work center");
+ if (updated) {
+ setLocationAndWorkCenter(companyId, location, workCenter);
+ }
return { location, workCenter, updated };
}