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.

feat: company switching

Brad Barbin2e84c1fe834c
diff --git a/apps/carbon/app/components/Layout/Topbar/Breadcrumbs.tsx b/apps/carbon/app/components/Layout/Topbar/Breadcrumbs.tsx
index 4bf5bdf2e2..10867c6f53 100644
--- a/apps/carbon/app/components/Layout/Topbar/Breadcrumbs.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/Breadcrumbs.tsx
@@ -23,7 +23,7 @@ import {
useWindowSize,
} from "@carbon/react";
import { ValidatedForm } from "@carbon/remix-validated-form";
-import { Link, useMatches } from "@remix-run/react";
+import { Form, Link, useMatches } from "@remix-run/react";
import { BsFillHexagonFill } from "react-icons/bs";
import { LuChevronsUpDown } from "react-icons/lu";
import { MdAdd } from "react-icons/md";
@@ -126,22 +126,30 @@ function CompanyBreadcrumb() {
<DropdownMenuSeparator />
<DropdownMenuGroup>
{routeData?.companies.map((c) => (
- <DropdownMenuItem
+ <Form
key={c.companyId}
- className="flex items-center justify-between"
+ method="post"
+ action={path.to.companySwitch(c.companyId!)}
>
- <HStack>
- <Avatar
- size="xs"
- name={c.name ?? undefined}
- src={c.logo ?? undefined}
- />
- <span>{c.name}</span>
- </HStack>
- <Badge variant="secondary" className="ml-2">
- {c.employeeType}
- </Badge>
- </DropdownMenuItem>
+ <DropdownMenuItem
+ className="flex items-center justify-between w-full"
+ asChild
+ >
+ <button type="submit">
+ <HStack>
+ <Avatar
+ size="xs"
+ name={c.name ?? undefined}
+ src={c.logo ?? undefined}
+ />
+ <span>{c.name}</span>
+ </HStack>
+ <Badge variant="secondary" className="ml-2">
+ {c.employeeType}
+ </Badge>
+ </button>
+ </DropdownMenuItem>
+ </Form>
))}
</DropdownMenuGroup>
diff --git a/apps/carbon/app/config/env.ts b/apps/carbon/app/config/env.ts
index 0ef2c548fd..31aa3f45d0 100644
--- a/apps/carbon/app/config/env.ts
+++ b/apps/carbon/app/config/env.ts
@@ -55,7 +55,6 @@ function getEnv(
export const SUPABASE_SERVICE_ROLE = getEnv("SUPABASE_SERVICE_ROLE");
export const SESSION_SECRET = getEnv("SESSION_SECRET");
export const SESSION_KEY = "auth";
-export const SESSION_COMPANY_KEY = "company";
export const SESSION_ERROR_KEY = "error";
export const SESSION_MAX_AGE = 60 * 60 * 24 * 7; // 7 days;
export const REFRESH_ACCESS_TOKEN_THRESHOLD = 60 * 10; // 10 minutes left before token expires
diff --git a/apps/carbon/app/modules/purchasing/purchasing.service.ts b/apps/carbon/app/modules/purchasing/purchasing.service.ts
index 04487b2205..dd5f562ca8 100644
--- a/apps/carbon/app/modules/purchasing/purchasing.service.ts
+++ b/apps/carbon/app/modules/purchasing/purchasing.service.ts
@@ -777,7 +777,7 @@ export async function upsertPurchaseOrder(
const [supplierPayment, supplierShipping, purchaser] = await Promise.all([
getSupplierPayment(client, purchaseOrder.supplierId),
getSupplierShipping(client, purchaseOrder.supplierId),
- getEmployeeJob(client, purchaseOrder.createdBy),
+ getEmployeeJob(client, purchaseOrder.createdBy, purchaseOrder.companyId),
]);
if (supplierPayment.error) return supplierPayment;
diff --git a/apps/carbon/app/modules/users/users.server.ts b/apps/carbon/app/modules/users/users.server.ts
index 3eaf3c609d..412139c7cd 100644
--- a/apps/carbon/app/modules/users/users.server.ts
+++ b/apps/carbon/app/modules/users/users.server.ts
@@ -985,7 +985,8 @@ export async function updatePermissions(
const permissionsUpdate = await getSupabaseServiceRole()
.from("user")
- .update({ permissions: updatedPermissions });
+ .update({ permissions: updatedPermissions })
+ .eq("id", id);
if (permissionsUpdate.error)
return error(permissionsUpdate.error, "Failed to update claims");
diff --git a/apps/carbon/app/routes/_public+/callback.tsx b/apps/carbon/app/routes/_public+/callback.tsx
index 332a8c7e0c..9dbc561161 100644
--- a/apps/carbon/app/routes/_public+/callback.tsx
+++ b/apps/carbon/app/routes/_public+/callback.tsx
@@ -5,8 +5,11 @@ import { useActionData, useFetcher } from "@remix-run/react";
import { useEffect } from "react";
import { supabaseClient } from "~/lib/supabase/client";
import { getUserByEmail } from "~/modules/users/users.server";
-import { refreshAccessToken } from "~/services/auth/auth.server";
import { callbackValidator } from "~/services/auth/auth.models";
+import {
+ refreshAccessToken,
+ requirePermissions,
+} from "~/services/auth/auth.server";
import {
commitAuthSession,
destroyAuthSession,
@@ -28,6 +31,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
export async function action({ request }: ActionFunctionArgs): FormActionData {
assertIsPost(request);
+ const { companyId } = await requirePermissions(request, {});
const validation = await validator(callbackValidator).validate(
await request.formData()
@@ -40,7 +44,7 @@ export async function action({ request }: ActionFunctionArgs): FormActionData {
}
const { refreshToken } = validation.data;
- const authSession = await refreshAccessToken(refreshToken);
+ const authSession = await refreshAccessToken(refreshToken, companyId);
if (!authSession) {
return redirect(
path.to.root,
diff --git a/apps/carbon/app/routes/x+/settings+/company.new.tsx b/apps/carbon/app/routes/x+/settings+/company.new.tsx
index b27c59c169..4876ddefd0 100644
--- a/apps/carbon/app/routes/x+/settings+/company.new.tsx
+++ b/apps/carbon/app/routes/x+/settings+/company.new.tsx
@@ -16,7 +16,7 @@ import {
getPermissionCacheKey,
} from "~/modules/users/users.server";
import { requirePermissions } from "~/services/auth/auth.server";
-import { commitAuthSession } from "~/services/session.server";
+import { updateCompanySession } from "~/services/session.server";
import { assertIsPost } from "~/utils/http";
import { path } from "~/utils/path";
@@ -96,9 +96,7 @@ export async function action({ request }: ActionFunctionArgs) {
throw redirect(path.to.authenticatedRoot, {
headers: {
- "Set-Cookie": await commitAuthSession(request, {
- company: companyId,
- }),
+ "Set-Cookie": await updateCompanySession(request, companyId),
},
});
}
diff --git a/apps/carbon/app/routes/x+/settings+/company.switch.$companyId.tsx b/apps/carbon/app/routes/x+/settings+/company.switch.$companyId.tsx
new file mode 100644
index 0000000000..e7f21b830f
--- /dev/null
+++ b/apps/carbon/app/routes/x+/settings+/company.switch.$companyId.tsx
@@ -0,0 +1,32 @@
+import { redirect, type ActionFunctionArgs } from "@remix-run/node";
+import { getCompanies } from "~/modules/settings";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash, updateCompanySession } from "~/services/session.server";
+import { path, requestReferrer } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client, userId } = await requirePermissions(request, {});
+ const companies = await getCompanies(client, userId);
+
+ if (companies.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.authenticatedRoot,
+ await flash(request, error(companies.error, "Failed to get companies"))
+ );
+ }
+
+ const companyId = Number(params.companyId);
+ if (!companies.data?.find((company) => company.id === companyId)) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.authenticatedRoot,
+ await flash(request, error(null, "Company not found"))
+ );
+ }
+
+ throw redirect(path.to.authenticatedRoot, {
+ headers: {
+ "Set-Cookie": await updateCompanySession(request, companyId),
+ },
+ });
+}
diff --git a/apps/carbon/app/services/auth/auth.server.ts b/apps/carbon/app/services/auth/auth.server.ts
index 4d3ad3d8f9..b08bb3c3f4 100644
--- a/apps/carbon/app/services/auth/auth.server.ts
+++ b/apps/carbon/app/services/auth/auth.server.ts
@@ -191,7 +191,7 @@ export async function signInWithEmail(email: string, password: string) {
export async function refreshAccessToken(
refreshToken?: string,
- companyId?: number | null
+ companyId?: number
): Promise<AuthSession | null> {
if (!refreshToken) return null;
@@ -203,13 +203,7 @@ export async function refreshAccessToken(
if (!data.session || error) return null;
- let company = companyId;
- if (!companyId) {
- const companies = await getCompaniesForUser(client, data.user?.id!);
- company = companies?.[0] ?? -1;
- }
-
- return makeAuthSession(data.session, company!);
+ return makeAuthSession(data.session, companyId!);
}
export async function verifyAuthSession(authSession: AuthSession) {
diff --git a/apps/carbon/app/services/session.server.ts b/apps/carbon/app/services/session.server.ts
index 32b3bf6ec6..71210feee1 100644
--- a/apps/carbon/app/services/session.server.ts
+++ b/apps/carbon/app/services/session.server.ts
@@ -5,7 +5,6 @@ import { getCurrentPath, isGet, makeRedirectToFromHere } from "~/utils/http";
import {
NODE_ENV,
REFRESH_ACCESS_TOKEN_THRESHOLD,
- SESSION_COMPANY_KEY,
SESSION_KEY,
SESSION_MAX_AGE,
SESSION_SECRET,
@@ -46,10 +45,8 @@ export async function commitAuthSession(
request: Request,
{
authSession,
- company,
}: {
authSession?: AuthSession | null;
- company?: number;
} = {}
) {
const session = await getSession(request);
@@ -60,10 +57,6 @@ export async function commitAuthSession(
session.set(SESSION_KEY, authSession);
}
- if (company !== undefined) {
- session.set(SESSION_COMPANY_KEY, company);
- }
-
return sessionStorage.commitSession(session, { maxAge: SESSION_MAX_AGE });
}
@@ -89,13 +82,6 @@ export async function flash(request: Request, result: Result) {
};
}
-export async function getCompanySession(
- request: Request
-): Promise<number | null> {
- const session = await getSession(request);
- return session.get(SESSION_COMPANY_KEY);
-}
-
export async function getAuthSession(
request: Request
): Promise<AuthSession | null> {
@@ -154,11 +140,10 @@ export async function refreshAuthSession(
request: Request
): Promise<AuthSession> {
const authSession = await getAuthSession(request);
- const companyId = await getCompanySession(request);
const refreshedAuthSession = await refreshAccessToken(
authSession?.refreshToken,
- companyId
+ authSession?.companyId
);
if (!refreshedAuthSession) {
@@ -191,3 +176,22 @@ export async function refreshAuthSession(
// we can't redirect because we are in an action, so, deal with it and don't forget to handle session commit 👮‍♀️
return refreshedAuthSession;
}
+
+export async function updateCompanySession(
+ request: Request,
+ companyId: number
+) {
+ const session = await getSession(request);
+ const authSession = await getAuthSession(request);
+
+ // allow user session to be null.
+ // useful you want to clear session and display a message explaining why
+ if (authSession !== undefined) {
+ session.set(SESSION_KEY, {
+ ...authSession,
+ companyId,
+ });
+ }
+
+ return sessionStorage.commitSession(session, { maxAge: SESSION_MAX_AGE });
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 4b516e9439..aff8c9757f 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -100,6 +100,8 @@ export const path = {
generatePath(`${x}/accounting/charts/${id}`),
chartOfAccounts: `${x}/accounting/charts`,
company: `${x}/settings/company`,
+ companySwitch: (companyId: number) =>
+ generatePath(`${x}/settings/company/switch/${companyId}`),
contractor: (id: string) =>
generatePath(`${x}/resources/contractors/${id}`),
contractors: `${x}/resources/contractors`,
diff --git a/packages/database/supabase/migrations/20230123004206_claims.sql b/packages/database/supabase/migrations/20230123004206_claims.sql
index bd652eb73d..d53600f5f5 100644
--- a/packages/database/supabase/migrations/20230123004206_claims.sql
+++ b/packages/database/supabase/migrations/20230123004206_claims.sql
@@ -145,7 +145,7 @@ CREATE OR REPLACE FUNCTION get_company_id_from_foreign_key(foreign_key TEXT, tbl
DECLARE
company_id integer;
BEGIN
- EXECUTE 'SELECT "companyId" FROM ' || tbl || ' WHERE id = $1' INTO company_id USING foreign_key;
+ EXECUTE 'SELECT "companyId" FROM "' || tbl || '" WHERE id = $1' INTO company_id USING foreign_key;
RETURN company_id;
END;
$$;