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 @carbon/auth for supabase in carbon app

Brad Barbin323c238814dd
diff --git a/apps/carbon/app/components/CadModel.tsx b/apps/carbon/app/components/CadModel.tsx
index b3ac74a50c..ca150e88d4 100644
--- a/apps/carbon/app/components/CadModel.tsx
+++ b/apps/carbon/app/components/CadModel.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import {
AutodeskViewer,
CardHeader,
@@ -15,7 +16,7 @@ import { useDropzone } from "react-dropzone";
import { LuUploadCloud } from "react-icons/lu";
import { useUser } from "~/hooks";
import { useAutodeskToken } from "~/lib/autodesk";
-import { useSupabase } from "~/lib/supabase";
+
import { path } from "~/utils/path";
const fileSizeLimitMb = 50;
@@ -49,7 +50,7 @@ const CadModel = ({
company: { id: companyId },
} = useUser();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const { autodeskToken } = useAutodeskToken();
const fetcher = useFetcher<{}>();
@@ -63,12 +64,12 @@ const CadModel = ({
const onFileChange = async (file: File | null) => {
setFile(file);
if (file) {
- if (!supabase) throw new Error("Failed to initialize supabase client");
+ if (!carbon) throw new Error("Failed to initialize carbon client");
const fileId = nanoid();
const fileExtension = file.name.split(".").pop();
const fileName = `${companyId}/models/${fileId}.${fileExtension}`;
- const modelUpload = await supabase.storage
+ const modelUpload = await carbon.storage
.from("private")
.upload(fileName, file, {
upsert: true,
diff --git a/apps/carbon/app/components/Documents.tsx b/apps/carbon/app/components/Documents.tsx
index 38e220eb77..5fd646646b 100644
--- a/apps/carbon/app/components/Documents.tsx
+++ b/apps/carbon/app/components/Documents.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import {
Card,
CardAction,
@@ -27,7 +28,6 @@ import { LuAxis3D, LuUpload } from "react-icons/lu";
import { MdMoreVert } from "react-icons/md";
import { DocumentPreview, FileDropzone, Hyperlink } from "~/components";
import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
import type { ModelUpload, StorageItem } from "~/types";
import { path } from "~/utils/path";
@@ -54,7 +54,7 @@ const Documents = ({
}: DocumentsProps) => {
const permissions = usePermissions();
const revalidator = useRevalidator();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const { company } = useUser();
const submit = useSubmit();
const navigate = useNavigate();
@@ -80,7 +80,7 @@ const Documents = ({
const deleteFile = useCallback(
async (file: StorageItem) => {
- const fileDelete = await supabase?.storage
+ const fileDelete = await carbon?.storage
.from("private")
.remove([getReadPath(file)]);
@@ -92,14 +92,14 @@ const Documents = ({
toast.success(`${file.name} deleted successfully`);
revalidator.revalidate();
},
- [getReadPath, supabase?.storage, revalidator]
+ [getReadPath, carbon?.storage, revalidator]
);
const deleteModel = useCallback(async () => {
- if (!supabase) return;
+ if (!carbon) return;
if (sourceDocument === "Job") {
- const result = await supabase
+ const result = await carbon
.from("job")
.update({ modelUploadId: null })
.eq("id", sourceDocumentId);
@@ -117,11 +117,11 @@ const Documents = ({
toast.success(`Model removed from ${sourceDocument}`);
revalidator.revalidate();
- }, [supabase, sourceDocument, sourceDocumentId, revalidator]);
+ }, [carbon, sourceDocument, sourceDocumentId, revalidator]);
const download = useCallback(
async (file: StorageItem) => {
- const result = await supabase?.storage
+ const result = await carbon?.storage
.from("private")
.download(getReadPath(file));
@@ -142,7 +142,7 @@ const Documents = ({
document.body.removeChild(a);
}, 0);
},
- [supabase?.storage, getReadPath]
+ [carbon?.storage, getReadPath]
);
const viewModel = useCallback(
@@ -158,15 +158,15 @@ const Documents = ({
const upload = useCallback(
async (files: File[]) => {
- if (!supabase) {
- toast.error("Supabase client not available");
+ if (!carbon) {
+ toast.error("Carbon client not available");
return;
}
for (const file of files) {
const fileName = getWritePath({ name: file.name });
- const fileUpload = await supabase.storage
+ const fileUpload = await carbon.storage
.from("private")
.upload(fileName, file, {
cacheControl: `${12 * 60 * 60}`,
@@ -194,7 +194,7 @@ const Documents = ({
},
[
getWritePath,
- supabase,
+ carbon,
revalidator,
submit,
sourceDocument,
@@ -220,7 +220,7 @@ const Documents = ({
isDisabled={!canUpdate}
leftIcon={<LuUpload />}
onChange={async (e: ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && supabase && company) {
+ if (e.target.files && carbon && company) {
upload(Array.from(e.target.files));
}
}}
diff --git a/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsx b/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsx
index e5686f7bd5..b9123d578d 100644
--- a/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsx
+++ b/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsx
@@ -44,7 +44,7 @@ const EditablePurchaseInvoiceLineNumber =
}));
const onAccountChange = async (accountNumber: string) => {
- if (!client) throw new Error("Supabase client not found");
+ if (!client) throw new Error("Carbon client not found");
const account = await client
.from("account")
@@ -80,7 +80,7 @@ const EditablePurchaseInvoiceLineNumber =
};
const onItemChange = async (itemId: string) => {
- if (!client) throw new Error("Supabase client not found");
+ if (!client) throw new Error("Carbon client not found");
switch (row.invoiceLineType) {
case "Material":
case "Part":
diff --git a/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx b/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
index c3d841015f..d01debd501 100644
--- a/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
+++ b/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
@@ -44,7 +44,7 @@ const EditablePurchaseOrderLineNumber =
}));
const onAccountChange = async (accountNumber: string) => {
- if (!client) throw new Error("Supabase client not found");
+ if (!client) throw new Error("Carbon client not found");
if (!row.companyId) throw new Error("Company ID not found");
if (!row.id) throw new Error("Purchase order line ID not found");
@@ -82,7 +82,7 @@ const EditablePurchaseOrderLineNumber =
};
const onItemChange = async (itemId: string) => {
- if (!client) throw new Error("Supabase client not found");
+ if (!client) throw new Error("Carbon client not found");
if (!row.companyId) throw new Error("Company ID not found");
if (!row.id) throw new Error("Purchase order line ID not found");
diff --git a/apps/carbon/app/components/Layout/Topbar/Search.tsx b/apps/carbon/app/components/Layout/Topbar/Search.tsx
index dcf60784c0..22ab456cc7 100644
--- a/apps/carbon/app/components/Layout/Topbar/Search.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/Search.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import type { Database } from "@carbon/database";
import type { ShortcutDefinition } from "@carbon/react";
import {
@@ -37,7 +38,6 @@ import {
import { RxMagnifyingGlass } from "react-icons/rx";
import { useModules } from "~/components/Layout/Navigation/useModules";
import { useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import { useAccountSubmodules } from "~/modules/account";
import { useAccountingSubmodules } from "~/modules/accounting";
import { useDocumentsSubmodules } from "~/modules/documents";
@@ -75,7 +75,7 @@ const SearchModal = ({
onClose: () => void;
}) => {
const { company } = useUser();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
@@ -110,7 +110,7 @@ const SearchModal = ({
const getSearchResults = useCallback(
async (q: string) => {
- if (!supabase || !company.id) return;
+ if (!carbon || !company.id) return;
setLoading(true);
const tokens = q.split(" ");
@@ -119,7 +119,7 @@ const SearchModal = ({
? tokens.map((token) => `"${token}"`).join(" <-> ")
: q;
- const result = await supabase
+ const result = await carbon
?.from("search")
.select()
.textSearch("fts", `*${search}:*`)
@@ -133,7 +133,7 @@ const SearchModal = ({
}
setLoading(false);
},
- [company.id, supabase]
+ [company.id, carbon]
);
const onInputChange = (value: string) => {
diff --git a/apps/carbon/app/components/RealtimeDataProvider.tsx b/apps/carbon/app/components/RealtimeDataProvider.tsx
index e30d49078f..99ba566483 100644
--- a/apps/carbon/app/components/RealtimeDataProvider.tsx
+++ b/apps/carbon/app/components/RealtimeDataProvider.tsx
@@ -1,9 +1,9 @@
"use client";
+import { useCarbon } from "@carbon/auth";
import idb from "localforage";
import { useEffect } from "react";
import { useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import { useCustomers, useItems, usePeople, useSuppliers } from "~/stores";
import type { Item } from "~/stores/items";
import type { ListItem } from "~/types";
@@ -12,7 +12,7 @@ let hydratedFromIdb = false;
let hydratedFromServer = false;
const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
- const { supabase, accessToken } = useSupabase();
+ const { carbon, accessToken } = useCarbon();
const {
company: { id: companyId },
} = useUser();
@@ -41,25 +41,25 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
});
}
- if (!supabase || !accessToken) return;
+ if (!carbon || !accessToken) return;
const [items, suppliers, customers, people] = await Promise.all([
- supabase
+ carbon
.from("item")
.select("id, readableId, name, type, replenishmentSystem, active")
.eq("companyId", companyId)
.order("readableId"),
- supabase
+ carbon
.from("supplier")
.select("id, name")
.eq("companyId", companyId)
.order("name"),
- supabase
+ carbon
.from("customer")
.select("id, name")
.eq("companyId", companyId)
.order("name"),
- supabase
+ carbon
.from("employees")
.select("id, name, avatarUrl")
.eq("companyId", companyId)
@@ -93,9 +93,9 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
if (!companyId) return;
hydrate();
- if (!supabase || !accessToken) return;
- supabase.realtime.setAuth(accessToken);
- const channel = supabase
+ if (!carbon || !accessToken) return;
+ carbon.realtime.setAuth(accessToken);
+ const channel = carbon
.channel("realtime:core")
.on(
"postgres_changes",
@@ -271,7 +271,7 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
// TODO: there's a cleaner way of doing this, but since customers and suppliers
// are also in the users table, we can't automatically add/update/delete them
// from our list of employees. So for now we just refetch.
- const { data } = await supabase
+ const { data } = await carbon
.from("employees")
.select("id, name, avatarUrl")
.eq("companyId", companyId)
@@ -285,10 +285,10 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
.subscribe();
return () => {
- if (channel) supabase?.removeChannel(channel);
+ if (channel) carbon?.removeChannel(channel);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [supabase, accessToken, companyId]);
+ }, [carbon, accessToken, companyId]);
return <>{children}</>;
};
diff --git a/apps/carbon/app/config/env.ts b/apps/carbon/app/config/env.ts
deleted file mode 100644
index 5497626477..0000000000
--- a/apps/carbon/app/config/env.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { isBrowser } from "@carbon/utils";
-
-declare global {
- interface Window {
- env: {
- SUPABASE_URL: string;
- SUPABASE_ANON_PUBLIC: string;
- POSTHOG_API_HOST: string;
- POSTHOG_PROJECT_PUBLIC_KEY: string;
- };
- }
-}
-
-declare global {
- namespace NodeJS {
- interface ProcessEnv {
- AUTODESK_BUCKET_NAME?: string;
- AUTODESK_CLIENT_ID?: string;
- AUTODESK_CLIENT_SECRET?: string;
- DOMAIN: string;
- POSTHOG_API_HOST: string;
- POSTHOG_PROJECT_PUBLIC_KEY: string;
- SESSION_SECRET: string;
- SESSION_KEY: string;
- SESSION_ERROR_KEY: string;
- SUPABASE_ANON_PUBLIC: string;
- SUPABASE_URL: string;
- SUPABASE_SERVICE_ROLE: string;
- VERCEL_URL: string;
- }
- }
-}
-
-type EnvOptions = {
- isSecret?: boolean;
- isRequired?: boolean;
-};
-
-export function getEnv(
- name: string,
- { isRequired, isSecret }: EnvOptions = { isSecret: true, isRequired: true }
-) {
- if (isBrowser && isSecret) return "";
-
- const source = (isBrowser ? window.env : process.env) ?? {};
-
- const value = source[name as keyof typeof source];
-
- if (!value && isRequired) {
- throw new Error(`${name} is not set`);
- }
-
- return value;
-}
-
-/**
- * Server env
- */
-export const AUTODESK_BUCKET_NAME = getEnv("AUTODESK_BUCKET_NAME", {
- isRequired: false,
-});
-export const AUTODESK_CLIENT_ID = getEnv("AUTODESK_CLIENT_ID", {
- isRequired: false,
-});
-export const AUTODESK_CLIENT_SECRET = getEnv("AUTODESK_CLIENT_SECRET", {
- isRequired: false,
-});
-export const DOMAIN = getEnv("DOMAIN", { isRequired: false }); // preview environments need no domain
-export const SUPABASE_SERVICE_ROLE = getEnv("SUPABASE_SERVICE_ROLE");
-export const SESSION_SECRET = getEnv("SESSION_SECRET");
-export const SESSION_KEY = "auth";
-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
-export const VERCEL_URL = getEnv("VERCEL_URL");
-
-/**
- * Shared envs
- */
-export const VERCEL_ENV = getEnv("VERCEL_ENV", {
- isSecret: false,
- isRequired: false,
-});
-export const POSTHOG_API_HOST = getEnv("POSTHOG_API_HOST", {
- isSecret: false,
-});
-export const POSTHOG_PROJECT_PUBLIC_KEY = getEnv("POSTHOG_PROJECT_PUBLIC_KEY", {
- isSecret: false,
-});
-export const SUPABASE_API_URL = getEnv("SUPABASE_API_URL", { isSecret: false });
-export const SUPABASE_ANON_PUBLIC = getEnv("SUPABASE_ANON_PUBLIC", {
- isSecret: false,
-});
-
-export function getBrowserEnv() {
- return {
- SUPABASE_API_URL,
- SUPABASE_ANON_PUBLIC,
- POSTHOG_API_HOST,
- POSTHOG_PROJECT_PUBLIC_KEY,
- };
-}
-
-export function isVercel() {
- return VERCEL_URL.includes("vercel.app");
-}
diff --git a/apps/carbon/app/entry.client.tsx b/apps/carbon/app/entry.client.tsx
index 279edd0c0a..6ebc2c895e 100644
--- a/apps/carbon/app/entry.client.tsx
+++ b/apps/carbon/app/entry.client.tsx
@@ -1,10 +1,10 @@
+import { POSTHOG_API_HOST, POSTHOG_PROJECT_PUBLIC_KEY } from "@carbon/auth";
import { OperatingSystemContextProvider } from "@carbon/react";
import { I18nProvider } from "@react-aria/i18n";
import { RemixBrowser } from "@remix-run/react";
import posthog from "posthog-js";
import { startTransition, useEffect } from "react";
import { hydrateRoot } from "react-dom/client";
-import { POSTHOG_API_HOST, POSTHOG_PROJECT_PUBLIC_KEY } from "~/config/env";
function PosthogInit() {
useEffect(() => {
diff --git a/apps/carbon/app/hooks/useNextItemId.tsx b/apps/carbon/app/hooks/useNextItemId.tsx
index a3a70bfe5b..755d3ea04e 100644
--- a/apps/carbon/app/hooks/useNextItemId.tsx
+++ b/apps/carbon/app/hooks/useNextItemId.tsx
@@ -1,22 +1,22 @@
+import { useCarbon } from "@carbon/auth";
import { useState } from "react";
-import { useSupabase } from "~/lib/supabase";
import { useUser } from "./useUser";
export function useNextItemId(
table: "Part" | "Service" | "Tool" | "Material" | "Consumable" | "Fixture"
) {
const { company } = useUser();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const [loading, setLoading] = useState<boolean>(false);
const [id, setId] = useState<string>("");
const onIdChange = async (newItemId: string) => {
- if (newItemId.endsWith("...") && supabase) {
+ if (newItemId.endsWith("...") && carbon) {
setLoading(true);
const prefix = newItemId.slice(0, -3);
try {
- const { data } = await supabase
+ const { data } = await carbon
?.from("item")
.select("readableId")
.eq("companyId", company.id)
diff --git a/apps/carbon/app/hooks/useRealtime.tsx b/apps/carbon/app/hooks/useRealtime.tsx
index e65a19967b..67be77b82f 100644
--- a/apps/carbon/app/hooks/useRealtime.tsx
+++ b/apps/carbon/app/hooks/useRealtime.tsx
@@ -1,18 +1,18 @@
+import { useCarbon } from "@carbon/auth";
import { useRevalidator } from "@remix-run/react";
import { useEffect } from "react";
-import { useSupabase } from "~/lib/supabase";
import { useUser } from "./useUser";
export function useRealtime(table: string, filter?: string) {
const { company } = useUser();
- const { accessToken, supabase } = useSupabase();
+ const { accessToken, carbon } = useCarbon();
const revalidator = useRevalidator();
useEffect(() => {
- if (!supabase || !accessToken || !table) return;
- supabase.realtime.setAuth(accessToken);
+ if (!carbon || !accessToken || !table) return;
+ carbon.realtime.setAuth(accessToken);
- const channel = supabase
+ const channel = carbon
.channel(`postgres_changes:${table}}`)
.on(
"postgres_changes",
@@ -35,9 +35,9 @@ export function useRealtime(table: string, filter?: string) {
.subscribe();
return () => {
- if (channel) supabase?.removeChannel(channel);
+ if (channel) carbon?.removeChannel(channel);
};
// Don't put the revalidator in the deps array
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [supabase, table, filter, accessToken, company.id]);
+ }, [carbon, table, filter, accessToken, company.id]);
}
diff --git a/apps/carbon/app/lib/autodesk/autodesk.server.ts b/apps/carbon/app/lib/autodesk/autodesk.server.ts
index d128d5d21d..b23077842a 100644
--- a/apps/carbon/app/lib/autodesk/autodesk.server.ts
+++ b/apps/carbon/app/lib/autodesk/autodesk.server.ts
@@ -1,11 +1,11 @@
-import { redis } from "@carbon/kv";
-import { z } from "zod";
import {
AUTODESK_BUCKET_NAME,
AUTODESK_CLIENT_ID,
AUTODESK_CLIENT_SECRET,
-} from "~/config/env";
-import { getSupabaseServiceRole } from "../supabase";
+ getCarbonServiceRole,
+} from "@carbon/auth";
+import { redis } from "@carbon/kv";
+import { z } from "zod";
import type { AutodeskTokenResponse } from "./types";
const SIGNED_URL_EXPIRATION = 15;
@@ -317,7 +317,7 @@ export async function getThumbnail(
token: string,
companyId: string
) {
- const supabase = getSupabaseServiceRole();
+ const carbon = getCarbonServiceRole();
const url = autodeskAPI.getThumbnail.url(urn);
let response;
@@ -334,11 +334,11 @@ export async function getThumbnail(
// the response is a binary stream of the thumbnail
// of type image/png
// we convert it to an ArrayBuffer and then upload it
- // to supabase storage
+ // to carbon storage
const data = await response.arrayBuffer();
const fileName = `${companyId}/models/${urn}.png`;
- const fileUpload = await supabase.storage
+ const fileUpload = await carbon.storage
.from("private")
.upload(fileName, data, {
cacheControl: `${365 * 24 * 60 * 60}`,
diff --git a/apps/carbon/app/lib/supabase/client.ts b/apps/carbon/app/lib/supabase/client.ts
deleted file mode 100644
index 3133e2354d..0000000000
--- a/apps/carbon/app/lib/supabase/client.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import type { Database } from "@carbon/database";
-import { isBrowser } from "@carbon/utils";
-import { createClient } from "@supabase/supabase-js";
-
-import {
- SUPABASE_ANON_PUBLIC,
- SUPABASE_API_URL,
- SUPABASE_SERVICE_ROLE,
-} from "~/config/env";
-
-const getSupabaseClient = (supabaseKey: string, accessToken?: string) => {
- const global = accessToken
- ? {
- global: {
- headers: {
- Authorization: `Bearer ${accessToken}`,
- },
- },
- }
- : {};
-
- const client = createClient<Database>(SUPABASE_API_URL, supabaseKey, {
- auth: {
- autoRefreshToken: false,
- persistSession: false,
- },
- ...global,
- });
-
- return client;
-};
-
-/**
- * Provides a Supabase Client for the logged in user or get back a public and safe client without admin privileges
- *
- * It's a per request scoped client to prevent access token leaking over multiple concurrent requests and from different users.
- *
- */
-export const getSupabase = (accessToken?: string) => {
- return getSupabaseClient(SUPABASE_ANON_PUBLIC, accessToken);
-};
-
-/**
- * Provides a Supabase Admin Client with full admin privileges
- *
- * It's a per request scoped client, to prevent access token leaking`.
- *
- */
-export const getSupabaseServiceRole = () => {
- if (isBrowser)
- throw new Error(
- "getSupabaseServiceRole is not available in browser and should NOT be used in insecure environments"
- );
-
- return getSupabaseClient(SUPABASE_SERVICE_ROLE);
-};
-
-export const supabaseClient = getSupabase();
diff --git a/apps/carbon/app/lib/supabase/index.ts b/apps/carbon/app/lib/supabase/index.ts
deleted file mode 100644
index 26a0fa6c27..0000000000
--- a/apps/carbon/app/lib/supabase/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import { getSupabase, getSupabaseServiceRole } from "./client";
-import { SupabaseProvider, useSupabase } from "./provider";
-
-export { SupabaseProvider, getSupabase, getSupabaseServiceRole, useSupabase };
diff --git a/apps/carbon/app/lib/supabase/provider.tsx b/apps/carbon/app/lib/supabase/provider.tsx
deleted file mode 100644
index 52e0af1944..0000000000
--- a/apps/carbon/app/lib/supabase/provider.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-import type { Database } from "@carbon/database";
-import { useInterval } from "@carbon/react";
-import { isBrowser } from "@carbon/utils";
-import { useFetcher } from "@remix-run/react";
-import type { SupabaseClient } from "@supabase/supabase-js";
-import type { PropsWithChildren } from "react";
-import {
- createContext,
- useContext,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from "react";
-
-import type { AuthSession } from "~/services/auth";
-import { path } from "~/utils/path";
-import { getSupabase } from "./client";
-
-const SupabaseContext = createContext<{
- supabase: SupabaseClient<Database> | undefined;
- accessToken: string | undefined;
-}>({ supabase: undefined, accessToken: undefined });
-
-export const SupabaseProvider = ({
- children,
- session,
-}: PropsWithChildren<{
- session: Partial<AuthSession>;
-}>) => {
- const { accessToken, refreshToken, expiresIn, expiresAt } = session;
- const [browserSessionExpiresAt, setBrowserSessionExpiresAt] = useState<
- number | undefined
- >();
- const initialLoad = useRef(true);
- const [supabase, setSupabaseClient] = useState<SupabaseClient | undefined>(
- () => {
- // prevents server side initial state
- // init a default anonymous client in browser until we have an auth token
- if (isBrowser) return getSupabase();
- }
- );
- const refresh = useFetcher<{}>();
-
- useInterval(() => {
- if (!initialLoad.current && expiresIn) {
- refresh.submit(null, {
- method: "post",
- action: path.to.refreshSession,
- });
- }
-
- initialLoad.current = false;
- }, expiresIn);
-
- if (isBrowser && expiresAt !== browserSessionExpiresAt && accessToken) {
- // recreate a supabase client to force provider's consumer to rerender
- setSupabaseClient(getSupabase(accessToken));
- setBrowserSessionExpiresAt(expiresAt);
- }
-
- useEffect(() => {
- if (!supabase || !accessToken || !refreshToken) return;
-
- supabase.auth.setSession({
- access_token: accessToken,
- refresh_token: refreshToken,
- });
- }, [accessToken, refreshToken, supabase]);
-
- const value = useMemo(
- () => ({ supabase, accessToken }),
- [supabase, accessToken]
- );
-
- return (
- <SupabaseContext.Provider value={value}>
- {children}
- </SupabaseContext.Provider>
- );
-};
-
-export const useSupabase = () => {
- const context = useContext(SupabaseContext);
-
- if (isBrowser && context === undefined) {
- throw new Error(`useSupabase must be used within a SupabaseProvider.`);
- }
-
- return context;
-};
diff --git a/apps/carbon/app/modules/account/ui/Profile/ProfilePhotoForm.tsx b/apps/carbon/app/modules/account/ui/Profile/ProfilePhotoForm.tsx
index 89799de9bc..cd56f033f6 100644
--- a/apps/carbon/app/modules/account/ui/Profile/ProfilePhotoForm.tsx
+++ b/apps/carbon/app/modules/account/ui/Profile/ProfilePhotoForm.tsx
@@ -1,8 +1,8 @@
+import { useCarbon } from "@carbon/auth";
import { Button, File, VStack, toast } from "@carbon/react";
import { useSubmit } from "@remix-run/react";
import type { ChangeEvent } from "react";
import { Avatar } from "~/components";
-import { useSupabase } from "~/lib/supabase";
import type { Account } from "~/modules/account";
import { path } from "~/utils/path";
@@ -11,17 +11,17 @@ type ProfilePhotoFormProps = {
};
const ProfilePhotoForm = ({ user }: ProfilePhotoFormProps) => {
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const submit = useSubmit();
const uploadImage = async (e: ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && supabase) {
+ if (e.target.files && carbon) {
const avatarFile = e.target.files[0];
const fileExtension = avatarFile.name.substring(
avatarFile.name.lastIndexOf(".") + 1
);
- const imageUpload = await supabase.storage
+ const imageUpload = await carbon.storage
.from("avatars")
.upload(`${user.id}.${fileExtension}`, avatarFile, {
cacheControl: "0",
@@ -40,8 +40,8 @@ const ProfilePhotoForm = ({ user }: ProfilePhotoFormProps) => {
};
const deleteImage = async () => {
- if (supabase && user?.avatarUrl) {
- const imageDelete = await supabase.storage
+ if (carbon && user?.avatarUrl) {
+ const imageDelete = await carbon.storage
.from("avatars")
.remove([user.avatarUrl]);
diff --git a/apps/carbon/app/modules/accounting/ui/PostingGroups/usePostingGroups.tsx b/apps/carbon/app/modules/accounting/ui/PostingGroups/usePostingGroups.tsx
index c00d98661d..260415d238 100644
--- a/apps/carbon/app/modules/accounting/ui/PostingGroups/usePostingGroups.tsx
+++ b/apps/carbon/app/modules/accounting/ui/PostingGroups/usePostingGroups.tsx
@@ -1,6 +1,6 @@
+import { useCarbon } from "@carbon/auth";
import { useCallback } from "react";
import { usePermissions } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type {
InventoryPostingGroup,
PurchasingPostingGroup,
@@ -8,7 +8,7 @@ import type {
} from "~/modules/accounting";
export default function usePostingGroups(table: string) {
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const permissions = usePermissions();
const canEdit = permissions.can("update", "accounting");
@@ -20,8 +20,8 @@ export default function usePostingGroups(table: string) {
value: unknown,
row: PurchasingPostingGroup | SalesPostingGroup | InventoryPostingGroup
) => {
- if (!supabase) throw new Error("Supabase client not found");
- return await supabase
+ if (!carbon) throw new Error("Carbon client not found");
+ return await carbon
// @ts-ignore
.from(table)
.update({
@@ -29,13 +29,13 @@ export default function usePostingGroups(table: string) {
})
.eq("id", row.id);
},
- [supabase, table]
+ [carbon, table]
);
return {
canDelete,
canEdit,
- supabase,
+ carbon,
onCellEdit,
};
}
diff --git a/apps/carbon/app/modules/api/ui/TableDocs.tsx b/apps/carbon/app/modules/api/ui/TableDocs.tsx
index 58c3883179..3646933b1d 100644
--- a/apps/carbon/app/modules/api/ui/TableDocs.tsx
+++ b/apps/carbon/app/modules/api/ui/TableDocs.tsx
@@ -1,7 +1,7 @@
+import { getBrowserEnv } from "@carbon/auth";
import { swaggerDocsSchema } from "@carbon/database";
import { cn } from "@carbon/react";
import { LuTable2 } from "react-icons/lu";
-import { getBrowserEnv } from "~/config/env";
import type { ValidLang } from "~/modules/api";
import { CodeSnippet, Snippets } from "~/modules/api";
diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentCreateForm.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentCreateForm.tsx
index 017c308d85..c770aee651 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentCreateForm.tsx
+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentCreateForm.tsx
@@ -1,24 +1,24 @@
+import { useCarbon } from "@carbon/auth";
import { File, toast } from "@carbon/react";
import { useSubmit } from "@remix-run/react";
import { nanoid } from "nanoid";
import type { ChangeEvent } from "react";
import { LuUpload } from "react-icons/lu";
import { useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import { path } from "~/utils/path";
const DocumentCreateForm = () => {
const submit = useSubmit();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const user = useUser();
const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && supabase) {
+ if (e.target.files && carbon) {
const file = e.target.files[0];
const fileExtension = file.name.substring(file.name.lastIndexOf(".") + 1);
const fileName = `${user.id}/${nanoid()}.${fileExtension}`;
- const fileUpload = await supabase.storage
+ const fileUpload = await carbon.storage
.from("private")
.upload(fileName, file, {
cacheControl: `${12 * 60 * 60}`,
diff --git a/apps/carbon/app/modules/documents/ui/Documents/useDocument.ts b/apps/carbon/app/modules/documents/ui/Documents/useDocument.ts
index 91a664ee6b..3b9837a5b1 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/useDocument.ts
+++ b/apps/carbon/app/modules/documents/ui/Documents/useDocument.ts
@@ -1,8 +1,8 @@
+import { useCarbon } from "@carbon/auth";
import { toast } from "@carbon/react";
import { useNavigate } from "@remix-run/react";
import { useCallback } from "react";
import { usePermissions, useUrlParams, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type {
DocumentTransactionType,
Document as DocumentType,
@@ -12,7 +12,7 @@ import { path } from "~/utils/path";
export const useDocument = () => {
const navigate = useNavigate();
const permissions = usePermissions();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const [params, setParams] = useUrlParams();
const user = useUser();
@@ -43,13 +43,13 @@ export const useDocument = () => {
if (user?.id === undefined) throw new Error("User is undefined");
if (!document.id) throw new Error("Document id is undefined");
- return supabase?.from("documentTransaction").insert({
+ return carbon?.from("documentTransaction").insert({
documentId: document.id,
type,
userId: user.id,
});
},
- [supabase, user?.id]
+ [carbon, user?.id]
);
const deleteLabel = useCallback(
@@ -57,21 +57,21 @@ export const useDocument = () => {
if (!document.id) throw new Error("Document id is undefined");
if (user?.id === undefined) throw new Error("User is undefined");
- return supabase
+ return carbon
?.from("documentLabel")
.delete()
.eq("documentId", document.id)
.eq("userId", user.id)
.eq("label", label);
},
- [supabase, user?.id]
+ [carbon, user?.id]
);
const download = useCallback(
async (doc: DocumentType) => {
if (!doc.path) throw new Error("Document path is undefined");
- const result = await supabase?.storage.from("private").download(doc.path);
+ const result = await carbon?.storage.from("private").download(doc.path);
if (!result || result.error) {
toast.error(result?.error?.message || "Error downloading file");
@@ -92,7 +92,7 @@ export const useDocument = () => {
await insertTransaction(doc, "Download");
},
- [supabase, insertTransaction]
+ [carbon, insertTransaction]
);
const view = useCallback(
@@ -111,20 +111,20 @@ export const useDocument = () => {
const favorite = useCallback(
async (document: DocumentType) => {
if (document.favorite) {
- await supabase
+ await carbon
?.from("documentFavorite")
.delete()
.eq("documentId", document.id!)
.eq("userId", user?.id);
return insertTransaction(document, "Unfavorite");
} else {
- await supabase
+ await carbon
?.from("documentFavorite")
.insert({ documentId: document.id!, userId: user?.id });
return insertTransaction(document, "Favorite");
}
},
- [insertTransaction, supabase, user?.id]
+ [insertTransaction, carbon, user?.id]
);
const isImage = useCallback((fileType: string) => {
@@ -140,13 +140,13 @@ export const useDocument = () => {
const label = useCallback(
async (document: DocumentType, labels: string[]) => {
if (user?.id === undefined) throw new Error("User is undefined");
- await supabase
+ await carbon
?.from("documentLabel")
.delete()
.eq("documentId", document.id!)
.eq("userId", user.id)
.then(() => {
- return supabase?.from("documentLabel").insert(
+ return carbon?.from("documentLabel").insert(
labels.map((label) => ({
documentId: document.id!,
label,
@@ -157,13 +157,13 @@ export const useDocument = () => {
return insertTransaction(document, "Label");
},
- [insertTransaction, supabase, user.id]
+ [insertTransaction, carbon, user.id]
);
const makePreview = useCallback(
async (doc: DocumentType) => {
if (!doc.path) throw new Error("Document path is undefined");
- const result = await supabase?.storage.from("private").download(doc.path);
+ const result = await carbon?.storage.from("private").download(doc.path);
if (!result || result.error) {
toast.error(result?.error?.message || "Error previewing file");
@@ -172,19 +172,19 @@ export const useDocument = () => {
return window.URL.createObjectURL(result.data);
},
- [supabase]
+ [carbon]
);
const removeLabel = useCallback(
(document: DocumentType, label: string) => {
- return supabase
+ return carbon
?.from("documentLabel")
.delete()
.eq("documentId", document.id!)
.eq("userId", user?.id)
.eq("label", label);
},
- [supabase, user?.id]
+ [carbon, user?.id]
);
const setLabel = useCallback(
diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
index 9eabcee7c1..649bdba8ac 100644
--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
@@ -1,7 +1,7 @@
+import { useCarbon } from "@carbon/auth";
import { useParams } from "@remix-run/react";
import { useCallback, useEffect, useState } from "react";
import { useRouteData, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { Receipt, ReceiptSourceDocument } from "~/modules/inventory/types";
import type { ListItem } from "~/types";
import { path } from "~/utils/path";
@@ -18,7 +18,7 @@ export default function useReceiptForm() {
const user = useUser();
const [error, setError] = useState<string | null>(null);
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const routeData = useRouteData<{
locations: ListItem[];
@@ -37,11 +37,11 @@ export default function useReceiptForm() {
);
const fetchSourceDocuments = useCallback(() => {
- if (!supabase || !user.company.id) return;
+ if (!carbon || !user.company.id) return;
switch (sourceDocument) {
case "Purchase Order":
- supabase
+ carbon
?.from("purchaseOrder")
.select("id, purchaseOrderId")
.eq("companyId", user.company.id)
@@ -62,7 +62,7 @@ export default function useReceiptForm() {
default:
setSourceDocuments([]);
}
- }, [sourceDocument, supabase, user.company.id]);
+ }, [sourceDocument, carbon, user.company.id]);
useEffect(() => {
fetchSourceDocuments();
diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
index fcdd7f9527..73f3ca0998 100644
--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import {
Card,
CardContent,
@@ -11,7 +12,6 @@ import { useCallback, useMemo } from "react";
import { EditableNumber } from "~/components/Editable";
import Grid from "~/components/Grid";
import { useRealtime, useRouteData } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { Receipt, ReceiptLine } from "~/modules/inventory";
import { useItems } from "~/stores";
import type { ListItem } from "~/types";
@@ -21,7 +21,7 @@ const ReceiptLines = () => {
const { receiptId } = useParams();
if (!receiptId) throw new Error("receiptId not found");
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
useRealtime("receiptLine", `receiptId=eq.${receiptId}`);
const sharedReceiptData = useRouteData<{
locations: ListItem[];
@@ -96,15 +96,15 @@ const ReceiptLines = () => {
const onCellEdit = useCallback(
async (id: string, value: unknown, row: ReceiptLine) => {
- if (!supabase) throw new Error("Supabase client not found");
- return await supabase
+ if (!carbon) throw new Error("Carbon client not found");
+ return await carbon
.from("receiptLine")
.update({
[id]: value,
})
.eq("id", row.id);
},
- [supabase]
+ [carbon]
);
const receiptLineEditableComponents = useMemo(
diff --git a/apps/carbon/app/modules/invoicing/invoicing.server.ts b/apps/carbon/app/modules/invoicing/invoicing.server.ts
index 7a941cd2d4..cc6d8084fc 100644
--- a/apps/carbon/app/modules/invoicing/invoicing.server.ts
+++ b/apps/carbon/app/modules/invoicing/invoicing.server.ts
@@ -1,11 +1,11 @@
-import { getSupabaseServiceRole } from "~/lib/supabase";
+import { getCarbonServiceRole } from "@carbon/auth";
export async function createPurchaseInvoiceFromPurchaseOrder(
purchaseOrderId: string,
companyId: string,
userId: string
) {
- const client = getSupabaseServiceRole();
+ const client = getCarbonServiceRole();
return client.functions.invoke<{ id: string }>(
"create-purchase-invoice-from-purchase-order",
{
diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx
index 7253063a44..084f099bda 100644
--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx
+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import {
Card,
CardAttribute,
@@ -18,7 +19,6 @@ import { useParams } from "@remix-run/react";
import { useState } from "react";
import { Assignee, useOptimisticAssignment } from "~/components";
import { useCurrencyFormatter, usePermissions, useRouteData } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { PurchaseInvoice } from "~/modules/invoicing";
import {
PurchaseInvoicingStatus,
@@ -33,7 +33,7 @@ const PurchaseInvoiceHeader = () => {
const { invoiceId } = useParams();
const postingModal = useDisclosure();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const [linesNotAssociatedWithPO, setLinesNotAssociatedWithPO] = useState<
{ itemId: string | null; itemReadableId: string | null; quantity: number }[]
>([]);
@@ -54,8 +54,8 @@ const PurchaseInvoiceHeader = () => {
const formatter = useCurrencyFormatter();
const showPostModal = async () => {
// check if there are any lines that are not associated with a PO
- if (!supabase) throw new Error("supabase not found");
- const { data, error } = await supabase
+ if (!carbon) throw new Error("carbon not found");
+ const { data, error } = await carbon
.from("purchaseInvoiceLine")
.select("itemId, itemReadableId, quantity, conversionFactor")
.eq("invoiceId", invoiceId)
diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
index cd83c2c700..9d53e359bc 100644
--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
@@ -13,6 +13,7 @@ import {
VStack,
} from "@carbon/react";
+import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import { useNavigate, useParams } from "@remix-run/react";
import { useState } from "react";
@@ -31,7 +32,6 @@ import {
UnitOfMeasure,
} from "~/components/Form";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type {
PurchaseInvoice,
PurchaseInvoiceLineType,
@@ -51,7 +51,7 @@ const PurchaseInvoiceLineForm = ({
initialValues,
}: PurchaseInvoiceLineFormProps) => {
const permissions = usePermissions();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const navigate = useNavigate();
const { company, defaults } = useUser();
const { invoiceId } = useParams();
@@ -134,7 +134,7 @@ const PurchaseInvoiceLineForm = ({
};
const onItemChange = async (itemId: string) => {
- if (!supabase) throw new Error("Supabase client not found");
+ if (!carbon) throw new Error("Carbon client not found");
switch (type) {
case "Consumable":
case "Material":
@@ -142,7 +142,7 @@ const PurchaseInvoiceLineForm = ({
case "Tool":
case "Fixture":
const [item, buyMethod, inventory] = await Promise.all([
- supabase
+ carbon
.from("item")
.select(
"name, readableId, unitOfMeasureCode, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"
@@ -150,14 +150,14 @@ const PurchaseInvoiceLineForm = ({
.eq("id", itemId)
.eq("companyId", company.id)
.single(),
- supabase
+ carbon
.from("buyMethod")
.select("*")
.eq("itemId", itemId)
.eq("companyId", company.id)
.eq("supplierId", routeData?.purchaseInvoice.supplierId!)
.maybeSingle(),
- supabase
+ carbon
.from("pickMethod")
.select("defaultShelfId")
.eq("itemId", itemId)
@@ -188,7 +188,7 @@ const PurchaseInvoiceLineForm = ({
break;
case "Service":
- const service = await supabase
+ const service = await carbon
.from("item")
.select("readableId, name")
.eq("id", itemId)
@@ -217,13 +217,13 @@ const PurchaseInvoiceLineForm = ({
};
const onLocationChange = async (newLocation: { value: string } | null) => {
- if (!supabase) throw new Error("supabase is not defined");
+ if (!carbon) throw new Error("carbon is not defined");
if (typeof newLocation?.value !== "string")
throw new Error("locationId is not a string");
setLocationId(newLocation.value);
if (!itemData.itemId) return;
- const shelf = await supabase
+ const shelf = await carbon
.from("pickMethod")
.select("defaultShelfId")
.eq("itemId", itemData.itemId)
@@ -358,7 +358,9 @@ const PurchaseInvoiceLineForm = ({
}
/>
- {["Part", "Material", "Consumable", "Tool"] && (
+ {["Part", "Material", "Consumable", "Tool"].includes(
+ type
+ ) && (
<>
<UnitOfMeasure
name="purchaseUnitOfMeasureCode"
diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx
index 2fc963e4a6..87d1c40710 100644
--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx
+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx
@@ -56,7 +56,7 @@ const PurchaseInvoiceLines = () => {
const { defaults, id: userId } = useUser();
const [items] = useItems();
const unitOfMeasureOptions = useUnitOfMeasure();
- const { canEdit, canDelete, supabase, accountOptions, onCellEdit } =
+ const { canEdit, canDelete, carbon, accountOptions, onCellEdit } =
usePurchaseInvoiceLines();
const [, setPurchaseInvoiceTotals] = usePurchaseInvoiceTotals();
@@ -262,7 +262,7 @@ const PurchaseInvoiceLines = () => {
quantity: EditableNumber(onCellEdit),
unitPrice: EditableNumber(onCellEdit),
itemId: EditablePurchaseInvoiceLineNumber(onCellEdit, {
- client: supabase,
+ client: carbon,
items: items,
accounts: accountOptions,
defaultLocationId: defaults.locationId,
@@ -274,7 +274,7 @@ const PurchaseInvoiceLines = () => {
}),
[
onCellEdit,
- supabase,
+ carbon,
items,
accountOptions,
defaults.locationId,
diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/usePurchaseInvoiceLines.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/usePurchaseInvoiceLines.tsx
index edfd8d72d2..f4fcd28073 100644
--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/usePurchaseInvoiceLines.tsx
+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/usePurchaseInvoiceLines.tsx
@@ -1,15 +1,15 @@
+import { useCarbon } from "@carbon/auth";
import { useMount } from "@carbon/react";
import { useFetcher } from "@remix-run/react";
import { useCallback, useMemo } from "react";
import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { getAccountsList } from "~/modules/accounting";
import type { PurchaseInvoiceLine } from "~/modules/invoicing";
import { path } from "~/utils/path";
export default function usePurchaseInvoiceLines() {
const { id: userId } = useUser();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const permissions = usePermissions();
const canEdit = permissions.can("update", "invoicing");
@@ -35,8 +35,8 @@ export default function usePurchaseInvoiceLines() {
const onCellEdit = useCallback(
async (id: string, value: unknown, row: PurchaseInvoiceLine) => {
- if (!supabase) throw new Error("Supabase client not found");
- return await supabase
+ if (!carbon) throw new Error("Carbon client not found");
+ return await carbon
.from("purchaseInvoiceLine")
.update({
[id]: value,
@@ -44,14 +44,14 @@ export default function usePurchaseInvoiceLines() {
})
.eq("id", row.id);
},
- [supabase, userId]
+ [carbon, userId]
);
return {
accountOptions,
canDelete,
canEdit,
- supabase,
+ carbon,
onCellEdit,
};
}
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
index 1475ec8929..490a6cde99 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -1,4 +1,5 @@
"use client";
+import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import {
Badge,
@@ -38,7 +39,6 @@ import type {
} from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { MethodItemType, MethodType } from "~/modules/shared";
import { path } from "~/utils/path";
import type { methodOperationValidator } from "../../items.models";
@@ -393,7 +393,7 @@ function MaterialForm({
setSelectedItemId: Dispatch<SetStateAction<string | null>>;
methodOperations: Operation[];
}) {
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const methodMaterialFetcher = useFetcher<{ id: string }>();
const params = useParams();
const { company } = useUser();
@@ -453,13 +453,13 @@ function MaterialForm({
};
const onItemChange = async (itemId: string) => {
- if (!supabase) return;
+ if (!carbon) return;
if (itemId === params.itemId) {
toast.error("An item cannot be added to itself.");
return;
}
- const item = await supabase
+ const item = await carbon
.from("item")
.select("name, readableId, unitOfMeasureCode, defaultMethodType")
.eq("id", itemId)
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
index 984d2da2f5..ca242fbb3f 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -1,4 +1,5 @@
"use client";
+import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import type { JSONContent } from "@carbon/react";
import {
@@ -44,7 +45,6 @@ import {
import type { Item, SortableItemRenderProps } from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import { methodOperationOrders, operationTypes } from "~/modules/shared";
import { path } from "~/utils/path";
import { methodOperationValidator } from "../../items.models";
@@ -116,7 +116,7 @@ const initialOperation: Omit<Operation, "makeMethodId" | "order"> = {
const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
const permissions = usePermissions();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const sortOrderFetcher = useFetcher<{}>();
const {
id: userId,
@@ -171,7 +171,7 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
setItems((prevItems) => prevItems.filter((item) => item.id !== id));
- const response = await supabase
+ const response = await carbon
?.from("methodOperation")
.delete()
.eq("id", id);
@@ -244,7 +244,7 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
);
if (selectedItemId !== null && !isTemporaryId(selectedItemId))
- await supabase
+ await carbon
?.from("methodOperation")
.update({
workInstruction: content,
@@ -257,7 +257,7 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
const onUploadImage = async (file: File) => {
const fileType = file.name.split(".").pop();
const fileName = `${companyId}/parts/${selectedItemId}/${nanoid()}.${fileType}`;
- const result = await supabase?.storage
+ const result = await carbon?.storage
.from("private")
.upload(fileName, file, {
upsert: true,
@@ -510,7 +510,7 @@ function OperationForm({
}) {
const methodOperationFetcher = useFetcher<{ id: string }>();
const { id: userId } = useUser();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const permissions = usePermissions();
useEffect(() => {
@@ -533,8 +533,8 @@ function OperationForm({
);
});
// save the work instructions
- if (isTemporaryId(item.id) && supabase) {
- supabase
+ if (isTemporaryId(item.id) && carbon) {
+ carbon
.from("methodOperation")
.update({
workInstruction: item.data.workInstruction,
@@ -555,7 +555,7 @@ function OperationForm({
methodOperationFetcher.data,
setItems,
setSelectedItemId,
- supabase,
+ carbon,
userId,
]);
@@ -597,8 +597,8 @@ function OperationForm({
});
const onProcessChange = async (processId: string) => {
- if (!supabase || !processId) return;
- const { data, error } = await supabase
+ if (!carbon || !processId) return;
+ const { data, error } = await carbon
.from("process")
.select("*")
.eq("id", processId)
@@ -619,8 +619,8 @@ function OperationForm({
};
const onWorkCenterChange = async (workCenterId: string) => {
- if (!supabase || !workCenterId) return;
- const { data, error } = await supabase
+ if (!carbon || !workCenterId) return;
+ const { data, error } = await carbon
.from("workCenter")
.select("*")
.eq("id", workCenterId)
diff --git a/apps/carbon/app/modules/items/ui/Item/BuyMethods/useBuyMethods.tsx b/apps/carbon/app/modules/items/ui/Item/BuyMethods/useBuyMethods.tsx
index 7e4f529529..f50e5839f0 100644
--- a/apps/carbon/app/modules/items/ui/Item/BuyMethods/useBuyMethods.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BuyMethods/useBuyMethods.tsx
@@ -1,10 +1,10 @@
+import { useCarbon } from "@carbon/auth";
import { useCallback } from "react";
import { usePermissions } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { BuyMethod } from "~/modules/items";
export default function useBuyMethods() {
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const permissions = usePermissions();
const canEdit = permissions.can("update", "parts");
@@ -12,21 +12,21 @@ export default function useBuyMethods() {
const onCellEdit = useCallback(
async (id: string, value: unknown, row: BuyMethod) => {
- if (!supabase) throw new Error("Supabase client not found");
- return await supabase
+ if (!carbon) throw new Error("Carbon client not found");
+ return await carbon
.from("buyMethod")
.update({
[id]: value,
})
.eq("id", row.id);
},
- [supabase]
+ [carbon]
);
return {
canDelete,
canEdit,
- supabase,
+ carbon,
onCellEdit,
};
}
diff --git a/apps/carbon/app/modules/items/ui/Item/CustomerParts/useCustomerParts.tsx b/apps/carbon/app/modules/items/ui/Item/CustomerParts/useCustomerParts.tsx
index b3397ff97b..777fd2be98 100644
--- a/apps/carbon/app/modules/items/ui/Item/CustomerParts/useCustomerParts.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/CustomerParts/useCustomerParts.tsx
@@ -1,10 +1,10 @@
+import { useCarbon } from "@carbon/auth";
import { useCallback } from "react";
import { usePermissions } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { CustomerPart } from "~/modules/items";
export default function useCustomerParts() {
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const permissions = usePermissions();
const canEdit = permissions.can("update", "parts");
@@ -12,21 +12,21 @@ export default function useCustomerParts() {
const onCellEdit = useCallback(
async (id: string, value: unknown, row: CustomerPart) => {
- if (!supabase) throw new Error("Supabase client not found");
- return await supabase
+ if (!carbon) throw new Error("Carbon client not found");
+ return await carbon
.from("customerPartToItem")
.update({
[id]: value,
})
.eq("id", row.id);
},
- [supabase]
+ [carbon]
);
return {
canDelete,
canEdit,
- supabase,
+ carbon,
onCellEdit,
};
}
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx b/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
index f1a205d4c3..a750c9cef3 100644
--- a/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import {
Card,
CardAction,
@@ -32,7 +33,6 @@ import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { ModelUpload } from "~/types";
import { path } from "~/utils/path";
@@ -250,7 +250,7 @@ export const useItemDocuments = ({ itemId, type }: Props) => {
const navigate = useNavigate();
const permissions = usePermissions();
const revalidator = useRevalidator();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const { company } = useUser();
const submit = useSubmit();
@@ -264,7 +264,7 @@ export const useItemDocuments = ({ itemId, type }: Props) => {
const deleteFile = useCallback(
async (file: FileObject) => {
- const fileDelete = await supabase?.storage
+ const fileDelete = await carbon?.storage
.from("private")
.remove([getPath(file)]);
@@ -276,13 +276,13 @@ export const useItemDocuments = ({ itemId, type }: Props) => {
toast.success("File deleted successfully");
revalidator.revalidate();
},
- [getPath, supabase?.storage, revalidator]
+ [getPath, carbon?.storage, revalidator]
);
const deleteModel = useCallback(async () => {
- if (!supabase) return;
+ if (!carbon) return;
- const { error } = await supabase
+ const { error } = await carbon
.from("item")
.update({ modelUploadId: null })
.eq("id", itemId);
@@ -292,11 +292,11 @@ export const useItemDocuments = ({ itemId, type }: Props) => {
}
toast.success("Model removed from item");
revalidator.revalidate();
- }, [supabase, itemId, revalidator]);
+ }, [carbon, itemId, revalidator]);
const download = useCallback(
async (file: FileObject) => {
- const result = await supabase?.storage
+ const result = await carbon?.storage
.from("private")
.download(getPath(file));
@@ -317,7 +317,7 @@ export const useItemDocuments = ({ itemId, type }: Props) => {
document.body.removeChild(a);
}, 0);
},
- [supabase?.storage, getPath]
+ [carbon?.storage, getPath]
);
const viewModel = useCallback(
@@ -333,15 +333,15 @@ export const useItemDocuments = ({ itemId, type }: Props) => {
const upload = useCallback(
async (files: File[]) => {
- if (!supabase) {
- toast.error("Supabase client not available");
+ if (!carbon) {
+ toast.error("Carbon client not available");
return;
}
for (const file of files) {
const fileName = getPath(file);
- const fileUpload = await supabase.storage
+ const fileUpload = await carbon.storage
.from("private")
.upload(fileName, file, {
cacheControl: `${12 * 60 * 60}`,
@@ -367,7 +367,7 @@ export const useItemDocuments = ({ itemId, type }: Props) => {
}
revalidator.revalidate();
},
- [getPath, supabase, revalidator, submit, type, itemId]
+ [getPath, carbon, revalidator, submit, type, itemId]
);
return {
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
index adee5ae761..2a85efceea 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
@@ -1,4 +1,5 @@
"use client";
+import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import {
Badge,
@@ -39,7 +40,6 @@ import type {
} from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { MethodItemType, MethodType } from "~/modules/shared";
import { path } from "~/utils/path";
import type { jobOperationValidator } from "../../production.models";
@@ -408,7 +408,7 @@ function MaterialForm({
const { jobId } = useParams();
if (!jobId) throw new Error("jobId not found");
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const methodMaterialFetcher = useFetcher<{ id: string }>();
const params = useParams();
const { company } = useUser();
@@ -469,24 +469,20 @@ function MaterialForm({
};
const onItemChange = async (itemId: string) => {
- if (!supabase) return;
+ if (!carbon) return;
if (itemId === params.itemId) {
toast.error("An item cannot be added to itself.");
return;
}
const [item, itemCost] = await await Promise.all([
- supabase
+ carbon
.from("item")
.select("name, readableId, unitOfMeasureCode, defaultMethodType")
.eq("id", itemId)
.eq("companyId", company.id)
.single(),
- supabase
- .from("itemCost")
- .select("unitCost")
- .eq("itemId", itemId)
- .single(),
+ carbon.from("itemCost").select("unitCost").eq("itemId", itemId).single(),
]);
if (item.error) {
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index 1546d833a6..8864ef4486 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -1,4 +1,5 @@
"use client";
+import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import type { JSONContent } from "@carbon/react";
import {
@@ -44,7 +45,6 @@ import {
import type { Item, SortableItemRenderProps } from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import { methodOperationOrders, operationTypes } from "~/modules/shared";
import { path } from "~/utils/path";
import { jobOperationValidator } from "../../production.models";
@@ -124,7 +124,7 @@ const JobBillOfProcess = ({
jobMakeMethodId,
operations,
}: JobBillOfProcessProps) => {
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const sortOrderFetcher = useFetcher<{}>();
const permissions = usePermissions();
const {
@@ -187,7 +187,7 @@ const JobBillOfProcess = ({
setItems((prevItems) => prevItems.filter((item) => item.id !== id));
- const response = await supabase?.from("jobOperation").delete().eq("id", id);
+ const response = await carbon?.from("jobOperation").delete().eq("id", id);
if (response?.error) {
// add the item back to the list if there was an error
setItems((prevItems) => {
@@ -256,7 +256,7 @@ const JobBillOfProcess = ({
)
);
if (selectedItemId !== null && !isTemporaryId(selectedItemId))
- await supabase
+ await carbon
?.from("jobOperation")
.update({
workInstruction: content,
@@ -269,7 +269,7 @@ const JobBillOfProcess = ({
const onUploadImage = async (file: File) => {
const fileType = file.name.split(".").pop();
const fileName = `${companyId}/parts/${selectedItemId}/${nanoid()}.${fileType}`;
- const result = await supabase?.storage
+ const result = await carbon?.storage
.from("private")
.upload(fileName, file, { upsert: true });
@@ -526,7 +526,7 @@ function OperationForm({
if (!jobId) throw new Error("jobId not found");
const fetcher = useFetcher<{ id: string }>();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
useEffect(() => {
// replace the temporary id with the actual id
@@ -549,8 +549,8 @@ function OperationForm({
});
// save the work instructions
- if (isTemporaryId(item.id) && supabase) {
- supabase
+ if (isTemporaryId(item.id) && carbon) {
+ carbon
.from("jobOperation")
.update({
workInstruction: item.data.workInstruction,
@@ -571,7 +571,7 @@ function OperationForm({
setItems,
setSelectedItemId,
item.data.workInstruction,
- supabase,
+ carbon,
userId,
]);
@@ -627,15 +627,15 @@ function OperationForm({
});
const onProcessChange = async (processId: string) => {
- if (!supabase || !processId) return;
+ if (!carbon || !processId) return;
const [process, workCenters, supplierProcesses] = await Promise.all([
- supabase.from("process").select("*").eq("id", processId).single(),
- supabase
+ carbon.from("process").select("*").eq("id", processId).single(),
+ carbon
.from("workCenterProcess")
.select("workCenter(*)")
.eq("processId", processId)
.eq("workCenter.active", true),
- supabase.from("supplierProcess").select("*").eq("processId", processId),
+ carbon.from("supplierProcess").select("*").eq("processId", processId),
]);
const activeWorkCenters =
@@ -695,14 +695,14 @@ function OperationForm({
};
const onWorkCenterChange = async (workCenterId: string | null) => {
- if (!supabase) return;
+ if (!carbon) return;
if (!workCenterId) {
// get the average costs
await onProcessChange(processData.processId);
return;
}
- const { data, error } = await supabase
+ const { data, error } = await carbon
.from("workCenter")
.select("*")
.eq("id", workCenterId)
@@ -723,8 +723,8 @@ function OperationForm({
};
const onSupplierProcessChange = async (supplierProcessId: string) => {
- if (!supabase) return;
- const { data, error } = await supabase
+ if (!carbon) return;
+ const { data, error } = await carbon
.from("supplierProcess")
.select("*")
.eq("id", supplierProcessId)
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx
index 26667f38f3..67b0f0bff1 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import {
Card,
@@ -27,7 +28,6 @@ import {
UnitOfMeasure,
} from "~/components/Form";
import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { jobStatus } from "~/modules/production";
import { deadlineTypes, jobValidator } from "~/modules/production";
import { type MethodItemType } from "~/modules/shared";
@@ -45,7 +45,7 @@ type JobFormProps = {
const JobForm = ({ initialValues }: JobFormProps) => {
const permissions = usePermissions();
const { company } = useUser();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const [type, setType] = useState<MethodItemType>(
initialValues.itemType ?? "Part"
);
@@ -89,9 +89,9 @@ const JobForm = ({ initialValues }: JobFormProps) => {
const onItemChange = async (itemId: string) => {
if (!itemId) return;
- if (!supabase || !company.id) return;
+ if (!carbon || !company.id) return;
const [item, manufacturing] = await Promise.all([
- supabase
+ carbon
.from("item")
.select(
"name, readableId, defaultMethodType, unitOfMeasureCode, modelUploadId"
@@ -99,7 +99,7 @@ const JobForm = ({ initialValues }: JobFormProps) => {
.eq("id", itemId)
.eq("companyId", company.id)
.single(),
- supabase
+ carbon
.from("itemReplenishment")
.select("lotSize, scrapPercentage")
.eq("itemId", itemId)
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobMaterialForm.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobMaterialForm.tsx
index f13f59466d..c0c3c90789 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobMaterialForm.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobMaterialForm.tsx
@@ -14,6 +14,7 @@ import {
useParams,
} from "@remix-run/react";
+import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import { useEffect, useState } from "react";
import type { z } from "zod";
@@ -30,7 +31,6 @@ import {
UnitOfMeasure,
} from "~/components/Form";
import { usePermissions } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { jobOperationValidator } from "~/modules/production";
import { jobMaterialValidator } from "~/modules/production";
import type { MethodItemType, MethodType } from "~/modules/shared";
@@ -48,7 +48,7 @@ const JobMaterialForm = ({
operations,
}: JobMaterialFormProps) => {
const fetcher = useFetcher<{ id: string; methodType: MethodType }>();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const permissions = usePermissions();
const navigate = useNavigate();
const location = useLocation();
@@ -92,19 +92,15 @@ const JobMaterialForm = ({
};
const onItemChange = async (itemId: string) => {
- if (!supabase) return;
+ if (!carbon) return;
const [item, itemCost] = await await Promise.all([
- supabase
+ carbon
.from("item")
.select("name, readableId, unitOfMeasureCode, defaultMethodType")
.eq("id", itemId)
.single(),
- supabase
- .from("itemCost")
- .select("unitCost")
- .eq("itemId", itemId)
- .single(),
+ carbon.from("itemCost").select("unitCost").eq("itemId", itemId).single(),
]);
if (item.error) {
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx
index cf83494da1..a0602b456d 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx
@@ -1,9 +1,9 @@
+import { useCarbon } from "@carbon/auth";
import { File, toast } from "@carbon/react";
import { useSubmit } from "@remix-run/react";
import type { ChangeEvent } from "react";
import { LuUpload } from "react-icons/lu";
import { useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import { path } from "~/utils/path";
type PurchaseOrderDocumentFormProps = {
@@ -17,16 +17,16 @@ const PurchaseOrderDocumentForm = ({
}: PurchaseOrderDocumentFormProps) => {
const submit = useSubmit();
const { company } = useUser();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && supabase && company) {
+ if (e.target.files && carbon && company) {
const file = e.target.files[0];
const fileName = `${company.id}/purchasing/${
isExternal ? "external" : "internal"
}/${orderId}/${file.name}`;
- const fileUpload = await supabase.storage
+ const fileUpload = await carbon.storage
.from("private")
.upload(fileName, file, {
cacheControl: `${12 * 60 * 60}`,
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/usePurchaseOrderDocuments.ts b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/usePurchaseOrderDocuments.ts
index 79ab56ab7e..beb53dabe8 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/usePurchaseOrderDocuments.ts
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/usePurchaseOrderDocuments.ts
@@ -1,8 +1,8 @@
+import { useCarbon } from "@carbon/auth";
import { toast } from "@carbon/react";
import { useFetcher } from "@remix-run/react";
import { useCallback } from "react";
import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { PurchaseOrderAttachment } from "~/modules/purchasing/types";
type Props = {
@@ -13,7 +13,7 @@ type Props = {
export const usePurchaseOrderDocuments = ({ isExternal, orderId }: Props) => {
const fetcher = useFetcher<{}>();
const permissions = usePermissions();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const { company } = useUser();
const canDelete = permissions.can("delete", "purchasing"); // TODO: or is document owner
@@ -34,7 +34,7 @@ export const usePurchaseOrderDocuments = ({ isExternal, orderId }: Props) => {
const deleteAttachment = useCallback(
async (attachment: PurchaseOrderAttachment) => {
- const fileDelete = await supabase?.storage
+ const fileDelete = await carbon?.storage
.from("private")
.remove([getPath(attachment)]);
@@ -46,12 +46,12 @@ export const usePurchaseOrderDocuments = ({ isExternal, orderId }: Props) => {
toast.success("File deleted successfully");
refresh();
},
- [supabase, getPath, refresh]
+ [carbon, getPath, refresh]
);
const download = useCallback(
async (attachment: PurchaseOrderAttachment) => {
- const result = await supabase?.storage
+ const result = await carbon?.storage
.from("private")
.download(getPath(attachment));
@@ -72,7 +72,7 @@ export const usePurchaseOrderDocuments = ({ isExternal, orderId }: Props) => {
document.body.removeChild(a);
}, 0);
},
- [supabase?.storage, getPath]
+ [carbon?.storage, getPath]
);
return {
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
index 90280f9692..cb05260e27 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
@@ -13,6 +13,7 @@ import {
VStack,
} from "@carbon/react";
+import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import { useNavigate, useParams } from "@remix-run/react";
import { useState } from "react";
@@ -31,7 +32,6 @@ import {
UnitOfMeasure,
} from "~/components/Form";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type {
PurchaseOrder,
PurchaseOrderLineType,
@@ -52,7 +52,7 @@ const PurchaseOrderLineForm = ({
initialValues,
}: PurchaseOrderLineFormProps) => {
const permissions = usePermissions();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const navigate = useNavigate();
const { company, defaults } = useUser();
const { orderId } = useParams();
@@ -131,7 +131,7 @@ const PurchaseOrderLineForm = ({
};
const onItemChange = async (itemId: string) => {
- if (!supabase) throw new Error("Supabase client not found");
+ if (!carbon) throw new Error("Carbon client not found");
switch (type) {
case "Consumable":
case "Material":
@@ -139,7 +139,7 @@ const PurchaseOrderLineForm = ({
case "Tool":
case "Fixture":
const [item, buyMethod, inventory] = await Promise.all([
- supabase
+ carbon
.from("item")
.select(
"name, readableId, unitOfMeasureCode, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"
@@ -147,14 +147,14 @@ const PurchaseOrderLineForm = ({
.eq("id", itemId)
.eq("companyId", company.id)
.single(),
- supabase
+ carbon
.from("buyMethod")
.select("*")
.eq("itemId", itemId)
.eq("companyId", company.id)
.eq("supplierId", routeData?.purchaseOrder.supplierId!)
.maybeSingle(),
- supabase
+ carbon
.from("pickMethod")
.select("defaultShelfId")
.eq("itemId", itemId)
@@ -184,7 +184,7 @@ const PurchaseOrderLineForm = ({
break;
case "Service":
- const service = await supabase
+ const service = await carbon
.from("item")
.select("readableId, name")
.eq("id", itemId)
@@ -213,13 +213,13 @@ const PurchaseOrderLineForm = ({
};
const onLocationChange = async (newLocation: { value: string } | null) => {
- if (!supabase) throw new Error("supabase is not defined");
+ if (!carbon) throw new Error("carbon is not defined");
if (typeof newLocation?.value !== "string")
throw new Error("locationId is not a string");
setLocationId(newLocation.value);
if (!itemData.itemId) return;
- const shelf = await supabase
+ const shelf = await carbon
.from("pickMethod")
.select("defaultShelfId")
.eq("itemId", itemData.itemId)
@@ -348,7 +348,9 @@ const PurchaseOrderLineForm = ({
}
/>
- {["Part", "Material", "Consumable", "Tool"] && (
+ {["Part", "Material", "Consumable", "Tool"].includes(
+ type
+ ) && (
<>
<UnitOfMeasure
name="purchaseUnitOfMeasureCode"
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
index 11c205a74e..0ce2da9b0a 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
@@ -57,7 +57,7 @@ const PurchaseOrderLines = () => {
const { defaults, id: userId } = useUser();
const unitOfMeasureOptions = useUnitOfMeasure();
- const { canEdit, canDelete, supabase, accountOptions, onCellEdit } =
+ const { canEdit, canDelete, carbon, accountOptions, onCellEdit } =
usePurchaseOrderLines();
const [, setPurchaseOrderTotals] = usePurchaseOrderTotals();
@@ -327,7 +327,7 @@ const PurchaseOrderLines = () => {
purchaseQuantity: EditableNumber(onCellEdit),
unitPrice: EditableNumber(onCellEdit),
itemId: EditablePurchaseOrderLineNumber(onCellEdit, {
- client: supabase,
+ client: carbon,
items: items,
accounts: accountOptions,
defaultLocationId: defaults.locationId,
@@ -339,7 +339,7 @@ const PurchaseOrderLines = () => {
}),
[
onCellEdit,
- supabase,
+ carbon,
items,
accountOptions,
defaults.locationId,
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsx
index a909f06073..3ad451beb2 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsx
@@ -1,15 +1,15 @@
+import { useCarbon } from "@carbon/auth";
import { useMount } from "@carbon/react";
import { useFetcher } from "@remix-run/react";
import { useCallback, useMemo } from "react";
import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { getAccountsList } from "~/modules/accounting";
import type { PurchaseOrderLine } from "~/modules/purchasing";
import { path } from "~/utils/path";
export default function usePurchaseOrderLines() {
const { id: userId } = useUser();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const permissions = usePermissions();
const canEdit = permissions.can("update", "purchasing");
@@ -35,8 +35,8 @@ export default function usePurchaseOrderLines() {
const onCellEdit = useCallback(
async (id: string, value: unknown, row: PurchaseOrderLine) => {
- if (!supabase) throw new Error("Supabase client not found");
- return await supabase
+ if (!carbon) throw new Error("Carbon client not found");
+ return await carbon
.from("purchaseOrderLine")
.update({
[id]: value,
@@ -44,14 +44,14 @@ export default function usePurchaseOrderLines() {
})
.eq("id", row.id!);
},
- [supabase, userId]
+ [carbon, userId]
);
return {
accountOptions,
canDelete,
canEdit,
- supabase,
+ carbon,
onCellEdit,
};
}
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsx
index 5944bac7ea..6a7e73198c 100644
--- a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import {
Card,
CardAction,
@@ -22,7 +23,6 @@ import { EditableNumber } from "~/components/Editable";
import Grid from "~/components/Grid";
import { useCurrencyFormatter, usePermissions, useUser } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
-import { useSupabase } from "~/lib/supabase";
import type { SupplierProcess } from "~/modules/purchasing";
import { path } from "~/utils/path";
@@ -40,12 +40,12 @@ const SupplierProccesses = ({ processes }: SupplierProccessesProps) => {
const canEdit = permissions.can("update", "purchasing");
const canDelete = permissions.can("delete", "purchasing");
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const onCellEdit = useCallback(
async (id: string, value: unknown, row: SupplierProcess) => {
- if (!supabase) throw new Error("Supabase client not found");
- return await supabase
+ if (!carbon) throw new Error("Carbon client not found");
+ return await carbon
.from("supplierProcess")
.update({
[id]: value,
@@ -53,7 +53,7 @@ const SupplierProccesses = ({ processes }: SupplierProccessesProps) => {
})
.eq("id", row.id!);
},
- [supabase, userId]
+ [carbon, userId]
);
const customColumns = useCustomColumns<SupplierProcess>("supplierProcess");
diff --git a/apps/carbon/app/modules/resources/ui/Contractors/ContractorsTable.tsx b/apps/carbon/app/modules/resources/ui/Contractors/ContractorsTable.tsx
index 9cde4e7cc4..5559d84508 100644
--- a/apps/carbon/app/modules/resources/ui/Contractors/ContractorsTable.tsx
+++ b/apps/carbon/app/modules/resources/ui/Contractors/ContractorsTable.tsx
@@ -34,9 +34,7 @@ const ContractorsTable = memo(
<HStack>
<Avatar
size="sm"
- name={
- `${row.original.firstName} ${row.original.lastName}` ?? ""
- }
+ name={`${row.original.firstName} ${row.original.lastName}`}
/>
<Hyperlink
to={`${path.to.contractor(
diff --git a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
index a43686345e..535d1a851a 100644
--- a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import {
Badge,
Card,
@@ -35,7 +36,6 @@ import {
import { MdMoreVert } from "react-icons/md";
import { DocumentPreview, FileDropzone, Hyperlink } from "~/components";
import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
import { path } from "~/utils/path";
import type { Opportunity } from "../../types";
@@ -219,7 +219,7 @@ export const useOpportunityDocuments = ({
}: OpportunityDocumentFormProps) => {
const permissions = usePermissions();
const { company } = useUser();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const revalidator = useRevalidator();
const submit = useSubmit();
@@ -234,7 +234,7 @@ export const useOpportunityDocuments = ({
const deleteAttachment = useCallback(
async (attachment: FileObject) => {
- const result = await supabase?.storage
+ const result = await carbon?.storage
.from("private")
.remove([getPath(attachment)]);
@@ -246,12 +246,12 @@ export const useOpportunityDocuments = ({
toast.success(`${attachment.name} deleted successfully`);
revalidator.revalidate();
},
- [supabase?.storage, getPath, revalidator]
+ [carbon?.storage, getPath, revalidator]
);
const download = useCallback(
async (attachment: FileObject) => {
- const result = await supabase?.storage
+ const result = await carbon?.storage
.from("private")
.download(getPath(attachment));
@@ -272,7 +272,7 @@ export const useOpportunityDocuments = ({
document.body.removeChild(a);
}, 0);
},
- [supabase?.storage, getPath]
+ [carbon?.storage, getPath]
);
const createDocumentRecord = useCallback(
@@ -302,15 +302,15 @@ export const useOpportunityDocuments = ({
const upload = useCallback(
async (files: File[]) => {
- if (!supabase) {
- toast.error("Supabase client not available");
+ if (!carbon) {
+ toast.error("Carbon client not available");
return;
}
for (const file of files) {
const fileName = getPath(file);
- const fileUpload = await supabase.storage
+ const fileUpload = await carbon.storage
.from("private")
.upload(fileName, file, {
cacheControl: `${12 * 60 * 60}`,
@@ -330,7 +330,7 @@ export const useOpportunityDocuments = ({
}
revalidator.revalidate();
},
- [getPath, createDocumentRecord, supabase, revalidator]
+ [getPath, createDocumentRecord, carbon, revalidator]
);
return {
@@ -344,13 +344,13 @@ export const useOpportunityDocuments = ({
const OpportunityDocumentForm = (props: OpportunityDocumentFormProps) => {
const { company } = useUser();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const permissions = usePermissions();
const { upload } = useOpportunityDocuments(props);
const uploadFiles = async (e: ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && supabase && company) {
+ if (e.target.files && carbon && company) {
upload(Array.from(e.target.files));
}
};
diff --git a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
index 79a8738959..e4c27fe77b 100644
--- a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
@@ -30,9 +30,9 @@ import type { ItemFile } from "~/modules/items";
import { useNavigate, useRevalidator, useSubmit } from "@remix-run/react";
import type { ChangeEvent } from "react";
import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import { path } from "~/utils/path";
+import { useCarbon } from "@carbon/auth";
import { useCallback } from "react";
import type { ModelUpload } from "~/types";
@@ -48,7 +48,7 @@ const useOpportunityLineDocuments = ({
const navigate = useNavigate();
const permissions = usePermissions();
const revalidator = useRevalidator();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const { company } = useUser();
const submit = useSubmit();
@@ -64,7 +64,7 @@ const useOpportunityLineDocuments = ({
const deleteFile = useCallback(
async (file: ItemFile) => {
- const fileDelete = await supabase?.storage
+ const fileDelete = await carbon?.storage
.from("private")
.remove([getPath(file)]);
@@ -76,24 +76,24 @@ const useOpportunityLineDocuments = ({
toast.success(`${file.name} deleted successfully`);
revalidator.revalidate();
},
- [getPath, supabase?.storage, revalidator]
+ [getPath, carbon?.storage, revalidator]
);
const deleteModel = useCallback(
async (lineId: string) => {
- if (!lineId || !supabase) return;
+ if (!lineId || !carbon) return;
const [salesRfqLineResult, quoteLineResult, salesOrderLineResult] =
await Promise.all([
- supabase
+ carbon
.from("salesRfqLine")
.update({ modelUploadId: null })
.eq("id", lineId),
- supabase
+ carbon
.from("quoteLine")
.update({ modelUploadId: null })
.eq("id", lineId),
- supabase
+ carbon
.from("salesOrderLine")
.update({ modelUploadId: null })
.eq("id", lineId),
@@ -116,12 +116,12 @@ const useOpportunityLineDocuments = ({
toast.success("Model removed from line");
revalidator.revalidate();
},
- [supabase, revalidator]
+ [carbon, revalidator]
);
const download = useCallback(
async (file: ItemFile) => {
- const result = await supabase?.storage
+ const result = await carbon?.storage
.from("private")
.download(getPath(file));
@@ -142,7 +142,7 @@ const useOpportunityLineDocuments = ({
document.body.removeChild(a);
}, 0);
},
- [supabase?.storage, getPath]
+ [carbon?.storage, getPath]
);
const viewModel = useCallback(
@@ -183,15 +183,15 @@ const useOpportunityLineDocuments = ({
const upload = useCallback(
async (files: File[]) => {
- if (!supabase) {
- toast.error("Supabase client not available");
+ if (!carbon) {
+ toast.error("Carbon client not available");
return;
}
for (const file of files) {
const fileName = getPath(file);
- const fileUpload = await supabase.storage
+ const fileUpload = await carbon.storage
.from("private")
.upload(fileName, file, {
cacheControl: `${12 * 60 * 60}`,
@@ -210,7 +210,7 @@ const useOpportunityLineDocuments = ({
}
revalidator.revalidate();
},
- [getPath, createDocumentRecord, supabase, revalidator]
+ [getPath, createDocumentRecord, carbon, revalidator]
);
return {
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
index 7196512bb8..bd243aacad 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
@@ -1,4 +1,5 @@
"use client";
+import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import {
Badge,
@@ -39,7 +40,6 @@ import type {
} from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { MethodItemType, MethodType } from "~/modules/shared";
import { path } from "~/utils/path";
import type { quoteOperationValidator } from "../../sales.models";
@@ -410,7 +410,7 @@ function MaterialForm({
if (!quoteId) throw new Error("quoteId not found");
if (!lineId) throw new Error("lineId not found");
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const methodMaterialFetcher = useFetcher<{ id: string }>();
const params = useParams();
const { company } = useUser();
@@ -471,24 +471,20 @@ function MaterialForm({
};
const onItemChange = async (itemId: string) => {
- if (!supabase) return;
+ if (!carbon) return;
if (itemId === params.itemId) {
toast.error("An item cannot be added to itself.");
return;
}
const [item, itemCost] = await await Promise.all([
- supabase
+ carbon
.from("item")
.select("name, readableId, unitOfMeasureCode, defaultMethodType")
.eq("id", itemId)
.eq("companyId", company.id)
.single(),
- supabase
- .from("itemCost")
- .select("unitCost")
- .eq("itemId", itemId)
- .single(),
+ carbon.from("itemCost").select("unitCost").eq("itemId", itemId).single(),
]);
if (item.error) {
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
index b58edd3fe3..45d7e1711e 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
@@ -1,4 +1,5 @@
"use client";
+import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import type { JSONContent } from "@carbon/react";
import {
@@ -44,7 +45,6 @@ import {
import type { Item, SortableItemRenderProps } from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import { methodOperationOrders, operationTypes } from "~/modules/shared";
import { path } from "~/utils/path";
import { quoteOperationValidator } from "../../sales.models";
@@ -124,7 +124,7 @@ const QuoteBillOfProcess = ({
quoteMakeMethodId,
operations,
}: QuoteBillOfProcessProps) => {
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const sortOrderFetcher = useFetcher<{}>();
const permissions = usePermissions();
const {
@@ -187,10 +187,7 @@ const QuoteBillOfProcess = ({
setItems((prevItems) => prevItems.filter((item) => item.id !== id));
- const response = await supabase
- ?.from("quoteOperation")
- .delete()
- .eq("id", id);
+ const response = await carbon?.from("quoteOperation").delete().eq("id", id);
if (response?.error) {
// add the item back to the list if there was an error
setItems((prevItems) => {
@@ -259,7 +256,7 @@ const QuoteBillOfProcess = ({
)
);
if (selectedItemId !== null && !isTemporaryId(selectedItemId))
- await supabase
+ await carbon
?.from("quoteOperation")
.update({
workInstruction: content,
@@ -272,7 +269,7 @@ const QuoteBillOfProcess = ({
const onUploadImage = async (file: File) => {
const fileType = file.name.split(".").pop();
const fileName = `${companyId}/parts/${selectedItemId}/${nanoid()}.${fileType}`;
- const result = await supabase?.storage
+ const result = await carbon?.storage
.from("private")
.upload(fileName, file, { upsert: true });
@@ -530,7 +527,7 @@ function OperationForm({
if (!lineId) throw new Error("lineId not found");
const fetcher = useFetcher<{ id: string }>();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
useEffect(() => {
// replace the temporary id with the actual id
@@ -553,8 +550,8 @@ function OperationForm({
});
// save the work instructions
- if (isTemporaryId(item.id) && supabase) {
- supabase
+ if (isTemporaryId(item.id) && carbon) {
+ carbon
.from("quoteOperation")
.update({
workInstruction: item.data.workInstruction,
@@ -575,7 +572,7 @@ function OperationForm({
setItems,
setSelectedItemId,
item.data.workInstruction,
- supabase,
+ carbon,
userId,
]);
@@ -631,15 +628,15 @@ function OperationForm({
});
const onProcessChange = async (processId: string) => {
- if (!supabase || !processId) return;
+ if (!carbon || !processId) return;
const [process, workCenters, supplierProcesses] = await Promise.all([
- supabase.from("process").select("*").eq("id", processId).single(),
- supabase
+ carbon.from("process").select("*").eq("id", processId).single(),
+ carbon
.from("workCenterProcess")
.select("workCenter(*)")
.eq("processId", processId)
.eq("workCenter.active", true),
- supabase.from("supplierProcess").select("*").eq("processId", processId),
+ carbon.from("supplierProcess").select("*").eq("processId", processId),
]);
const activeWorkCenters =
@@ -699,14 +696,14 @@ function OperationForm({
};
const onWorkCenterChange = async (workCenterId: string | null) => {
- if (!supabase) return;
+ if (!carbon) return;
if (!workCenterId) {
// get the average costs
await onProcessChange(processData.processId);
return;
}
- const { data, error } = await supabase
+ const { data, error } = await carbon
.from("workCenter")
.select("*")
.eq("id", workCenterId)
@@ -727,8 +724,8 @@ function OperationForm({
};
const onSupplierProcessChange = async (supplierProcessId: string) => {
- if (!supabase) return;
- const { data, error } = await supabase
+ if (!carbon) return;
+ const { data, error } = await carbon
.from("supplierProcess")
.select("*")
.eq("id", supplierProcessId)
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
index 4ecc25f1e0..76aeac021b 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
@@ -20,6 +20,7 @@ import {
VStack,
} from "@carbon/react";
+import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import { useParams } from "@remix-run/react";
import { useState } from "react";
@@ -37,7 +38,6 @@ import {
Submit,
} from "~/components/Form";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { Quotation, QuotationLine } from "~/modules/sales";
import {
DeleteQuoteLine,
@@ -60,7 +60,7 @@ const QuoteLineForm = ({
}: QuoteLineFormProps) => {
const permissions = usePermissions();
const { company } = useUser();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const { quoteId } = useParams();
@@ -97,9 +97,9 @@ const QuoteLineForm = ({
});
const onCustomerPartChange = async (customerPartId: string) => {
- if (!supabase || !routeData?.quote?.customerId) return;
+ if (!carbon || !routeData?.quote?.customerId) return;
- const customerPart = await supabase
+ const customerPart = await carbon
.from("customerPartToItem")
.select("itemId")
.eq("customerPartId", customerPartId)
@@ -118,10 +118,10 @@ const QuoteLineForm = ({
};
const onCustomerPartRevisionChange = async (customerPartRevision: string) => {
- if (!supabase || !routeData?.quote?.customerId || !itemData.customerPartId)
+ if (!carbon || !routeData?.quote?.customerId || !itemData.customerPartId)
return;
- const customerPart = await supabase
+ const customerPart = await carbon
.from("customerPartToItem")
.select("itemId")
.eq("customerPartId", itemData.customerPartId)
@@ -140,10 +140,10 @@ const QuoteLineForm = ({
};
const onItemChange = async (itemId: string) => {
- if (!supabase) return;
+ if (!carbon) return;
const [item, customerPart] = await Promise.all([
- supabase
+ carbon
.from("item")
.select(
"name, readableId, defaultMethodType, unitOfMeasureCode, modelUploadId"
@@ -151,7 +151,7 @@ const QuoteLineForm = ({
.eq("id", itemId)
.eq("companyId", company.id)
.single(),
- supabase
+ carbon
.from("customerPartToItem")
.select("customerPartId, customerPartRevision")
.eq("itemId", itemId)
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineNotes.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineNotes.tsx
index c4dbae1fe3..0f1232ee87 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineNotes.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineNotes.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import type { JSONContent } from "@carbon/react";
import {
Card,
@@ -12,7 +13,6 @@ import {
import { getLocalTimeZone, today } from "@internationalized/date";
import { nanoid } from "nanoid";
import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { QuotationLine } from "~/modules/sales";
const QuoteLineNotes = ({ line }: { line: QuotationLine }) => {
@@ -21,16 +21,14 @@ const QuoteLineNotes = ({ line }: { line: QuotationLine }) => {
company: { id: companyId },
} = useUser();
const permissions = usePermissions();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const onUploadImage = async (file: File) => {
const fileType = file.name.split(".").pop();
const fileName = `${companyId}/opportunity/${
line.id
}/${nanoid()}.${fileType}`;
- const result = await supabase?.storage
- .from("private")
- .upload(fileName, file);
+ const result = await carbon?.storage.from("private").upload(fileName, file);
if (result?.error) {
toast.error("Failed to upload image");
@@ -45,7 +43,7 @@ const QuoteLineNotes = ({ line }: { line: QuotationLine }) => {
};
const onUpdateInternalNotes = useThrottle(async (content: JSONContent) => {
- await supabase
+ await carbon
?.from("quoteLine")
.update({
notes: content,
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
index 274229dc25..2f1994a85d 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import {
Button,
Card,
@@ -42,7 +43,6 @@ import {
useRouteData,
useUser,
} from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import { path } from "~/utils/path";
import { quoteLineAdditionalChargesValidator } from "../../sales.models";
import type {
@@ -82,7 +82,7 @@ const QuoteLinePricing = ({
permissions.can("update", "sales") &&
["Draft"].includes(routeData?.quote?.status ?? "");
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const fetcher = useFetcher<{ id?: string; error: string | null }>();
useEffect(() => {
if (fetcher.data?.error) {
@@ -220,7 +220,7 @@ const QuoteLinePricing = ({
quantity: number,
value: number
) => {
- if (!supabase) return;
+ if (!carbon) return;
const hasPrice = prices[quantity];
const oldPrices = { ...prices };
const newPrices = { ...oldPrices };
@@ -240,7 +240,7 @@ const QuoteLinePricing = ({
setPrices(newPrices);
if (hasPrice) {
- const { error } = await supabase
+ const { error } = await carbon
.from("quoteLinePrice")
.update({ [key]: value })
.eq("quoteLineId", lineId)
@@ -249,7 +249,7 @@ const QuoteLinePricing = ({
setPrices(oldPrices);
}
} else {
- const { error } = await supabase.from("quoteLinePrice").insert([
+ const { error } = await carbon.from("quoteLinePrice").insert([
{
...newPrices[quantity],
},
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
index 6097c5cc9f..e65dc07cb3 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
@@ -14,6 +14,7 @@ import {
useParams,
} from "@remix-run/react";
+import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import { useEffect, useState } from "react";
import type { z } from "zod";
@@ -30,7 +31,6 @@ import {
UnitOfMeasure,
} from "~/components/Form";
import { usePermissions } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { quoteOperationValidator } from "~/modules/sales";
import { quoteMaterialValidator } from "~/modules/sales";
import type { MethodItemType, MethodType } from "~/modules/shared";
@@ -48,7 +48,7 @@ const QuoteMaterialForm = ({
operations,
}: QuoteMaterialFormProps) => {
const fetcher = useFetcher<{ id: string; methodType: MethodType }>();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const permissions = usePermissions();
const navigate = useNavigate();
const location = useLocation();
@@ -93,19 +93,15 @@ const QuoteMaterialForm = ({
};
const onItemChange = async (itemId: string) => {
- if (!supabase) return;
+ if (!carbon) return;
const [item, itemCost] = await await Promise.all([
- supabase
+ carbon
.from("item")
.select("name, readableId, unitOfMeasureCode, defaultMethodType")
.eq("id", itemId)
.single(),
- supabase
- .from("itemCost")
- .select("unitCost")
- .eq("itemId", itemId)
- .single(),
+ carbon.from("itemCost").select("unitCost").eq("itemId", itemId).single(),
]);
if (item.error) {
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteToOrderModal.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteToOrderModal.tsx
index 86c717ec5e..07cba80ece 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteToOrderModal.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteToOrderModal.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import {
Button,
cn,
@@ -47,7 +48,6 @@ import { usePaymentTerm } from "~/components/Form/PaymentTerm";
import { useShippingMethod } from "~/components/Form/ShippingMethod";
import { useRouteData } from "~/hooks";
import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
-import { useSupabase } from "~/lib/supabase";
import { getDocumentType } from "~/modules/documents";
import { path } from "~/utils/path";
import type {
@@ -87,7 +87,7 @@ const QuoteToOrderDrawer = ({
>
>({});
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const { quoteId } = useParams();
if (!quoteId) throw new Error("Could not find quoteId");
@@ -103,8 +103,8 @@ const QuoteToOrderDrawer = ({
const [uploading, setUploading] = useState(false);
const onDrop = async (acceptedFiles: File[]) => {
- if (!supabase) {
- toast.error("Supabase client not available");
+ if (!carbon) {
+ toast.error("Carbon client not available");
return;
}
@@ -120,7 +120,7 @@ const QuoteToOrderDrawer = ({
if (file) upload([file]);
const purchaseOrderDocumentPath = getPath(file);
- const { error } = await supabase
+ const { error } = await carbon
.from("opportunity")
.update({
purchaseOrderDocumentPath,
@@ -140,15 +140,15 @@ const QuoteToOrderDrawer = ({
};
const removePurchaseOrder = async () => {
- if (!supabase) {
- toast.error("Failed to initialize Supabase client");
+ if (!carbon) {
+ toast.error("Failed to initialize Carbon client");
return;
}
setUploading(true);
const [opportunityDelete] = await Promise.all([
- supabase
+ carbon
.from("opportunity")
.update({
purchaseOrderDocumentPath: null,
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
index e2a40c06ec..73106cf845 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
@@ -41,8 +41,8 @@ import {
UnitOfMeasure,
} from "~/components/Form";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
+import { useCarbon } from "@carbon/auth";
import type {
SalesOrder,
SalesOrderLine,
@@ -65,7 +65,7 @@ const SalesOrderLineForm = ({
onClose,
}: SalesOrderLineFormProps) => {
const permissions = usePermissions();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const { company } = useUser();
const { orderId } = useParams();
@@ -120,9 +120,9 @@ const SalesOrderLineForm = ({
const onChange = async (itemId: string) => {
if (!itemId) return;
- if (!supabase || !company.id) return;
+ if (!carbon || !company.id) return;
const [item, shelf, price] = await Promise.all([
- supabase
+ carbon
.from("item")
.select(
"name, readableId, defaultMethodType, unitOfMeasureCode, modelUploadId"
@@ -130,14 +130,14 @@ const SalesOrderLineForm = ({
.eq("id", itemId)
.eq("companyId", company.id)
.single(),
- supabase
+ carbon
.from("pickMethod")
.select("defaultShelfId")
.eq("itemId", itemId)
.eq("companyId", company.id)
.eq("locationId", locationId)
.maybeSingle(),
- supabase
+ carbon
.from("itemUnitSalePrice")
.select("unitSalePrice")
.eq("itemId", itemId)
@@ -158,13 +158,13 @@ const SalesOrderLineForm = ({
};
const onLocationChange = async (newLocation: { value: string } | null) => {
- if (!supabase) throw new Error("supabase is not defined");
+ if (!carbon) throw new Error("carbon is not defined");
if (typeof newLocation?.value !== "string")
throw new Error("locationId is not a string");
setLocationId(newLocation.value);
if (!itemData.itemId) return;
- const shelf = await supabase
+ const shelf = await carbon
.from("pickMethod")
.select("defaultShelfId")
.eq("itemId", itemData.itemId)
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineForm.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineForm.tsx
index 01e2943a93..872b6c09ae 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineForm.tsx
@@ -20,6 +20,7 @@ import {
VStack,
} from "@carbon/react";
+import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import { useParams } from "@remix-run/react";
import { useState } from "react";
@@ -36,7 +37,6 @@ import {
UnitOfMeasure,
} from "~/components/Form";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { SalesRFQ, SalesRFQLine } from "~/modules/sales";
import { DeleteSalesRFQLine, salesRfqLineValidator } from "~/modules/sales";
import { path } from "~/utils/path";
@@ -54,7 +54,7 @@ const SalesRFQLineForm = ({
}: SalesRFQLineFormProps) => {
const permissions = usePermissions();
const { company } = useUser();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const { rfqId } = useParams();
@@ -87,9 +87,9 @@ const SalesRFQLineForm = ({
});
const onCustomerPartChange = async (customerPartId: string) => {
- if (!supabase || !routeData?.rfqSummary?.customerId) return;
+ if (!carbon || !routeData?.rfqSummary?.customerId) return;
- const customerPart = await supabase
+ const customerPart = await carbon
.from("customerPartToItem")
.select("itemId")
.eq("customerPartId", customerPartId)
@@ -109,13 +109,13 @@ const SalesRFQLineForm = ({
const onCustomerPartRevisionChange = async (customerPartRevision: string) => {
if (
- !supabase ||
+ !carbon ||
!routeData?.rfqSummary?.customerId ||
!itemData.customerPartId
)
return;
- const customerPart = await supabase
+ const customerPart = await carbon
.from("customerPartToItem")
.select("itemId")
.eq("customerPartId", itemData.customerPartId)
@@ -134,16 +134,16 @@ const SalesRFQLineForm = ({
};
const onItemChange = async (itemId: string) => {
- if (!supabase) return;
+ if (!carbon) return;
const [item, customerPart] = await Promise.all([
- supabase
+ carbon
.from("item")
.select("name, unitOfMeasureCode, modelUploadId")
.eq("id", itemId)
.eq("companyId", company.id)
.single(),
- supabase
+ carbon
.from("customerPartToItem")
.select("customerPartId, customerPartRevision")
.eq("itemId", itemId)
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineNotes.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineNotes.tsx
index 73eeb984b6..fe699d219f 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineNotes.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineNotes.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import type { JSONContent } from "@carbon/react";
import {
Card,
@@ -12,7 +13,6 @@ import {
import { getLocalTimeZone, today } from "@internationalized/date";
import { nanoid } from "nanoid";
import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type { SalesRFQLine } from "~/modules/sales";
const SalesRFQLineNotes = ({ line }: { line: SalesRFQLine }) => {
@@ -21,16 +21,14 @@ const SalesRFQLineNotes = ({ line }: { line: SalesRFQLine }) => {
company: { id: companyId },
} = useUser();
const permissions = usePermissions();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const onUploadImage = async (file: File) => {
const fileType = file.name.split(".").pop();
const fileName = `${companyId}/opportunity-line/${
line.id
}/${nanoid()}.${fileType}`;
- const result = await supabase?.storage
- .from("private")
- .upload(fileName, file);
+ const result = await carbon?.storage.from("private").upload(fileName, file);
if (result?.error) {
toast.error("Failed to upload image");
@@ -45,7 +43,7 @@ const SalesRFQLineNotes = ({ line }: { line: SalesRFQLine }) => {
};
const onUpdateInternalNotes = useThrottle(async (content: JSONContent) => {
- await supabase
+ await carbon
?.from("salesRfqLine")
.update({
internalNotes: content,
diff --git a/apps/carbon/app/modules/settings/settings.service.ts b/apps/carbon/app/modules/settings/settings.service.ts
index 341281d9b2..5730cbb490 100644
--- a/apps/carbon/app/modules/settings/settings.service.ts
+++ b/apps/carbon/app/modules/settings/settings.service.ts
@@ -1,8 +1,8 @@
+import { SUPABASE_API_URL } from "@carbon/auth";
import type { Database, Json } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import type { z } from "zod";
-import { SUPABASE_API_URL } from "~/config/env";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { interpolateSequenceDate } from "~/utils/string";
diff --git a/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx b/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx
index 499a467eaf..26f0ae6aab 100644
--- a/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx
+++ b/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx
@@ -1,7 +1,7 @@
+import { useCarbon } from "@carbon/auth";
import { Avatar, Button, File, VStack, toast } from "@carbon/react";
import { useSubmit } from "@remix-run/react";
import { type ChangeEvent } from "react";
-import { useSupabase } from "~/lib/supabase";
import type { Company } from "~/modules/settings";
import { path } from "~/utils/path";
@@ -10,7 +10,7 @@ type CompanyLogoFormProps = {
};
const CompanyLogoForm = ({ company }: CompanyLogoFormProps) => {
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const submit = useSubmit();
const logoPath = company?.logo
@@ -18,11 +18,11 @@ const CompanyLogoForm = ({ company }: CompanyLogoFormProps) => {
: null;
const uploadImage = async (e: ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && supabase) {
+ if (e.target.files && carbon) {
const logo = e.target.files[0];
const fileExtension = logo.name.substring(logo.name.lastIndexOf(".") + 1);
- const imageUpload = await supabase.storage
+ const imageUpload = await carbon.storage
.from("public")
.upload(`${company.id}/logo.${fileExtension}`, logo, {
cacheControl: "0",
@@ -40,8 +40,8 @@ const CompanyLogoForm = ({ company }: CompanyLogoFormProps) => {
};
const deleteImage = async () => {
- if (supabase && logoPath) {
- const imageDelete = await supabase.storage
+ if (carbon && logoPath) {
+ const imageDelete = await carbon.storage
.from("public")
.remove([logoPath]);
diff --git a/apps/carbon/app/modules/users/users.server.ts b/apps/carbon/app/modules/users/users.server.ts
index 1fc1817a86..323a75d919 100644
--- a/apps/carbon/app/modules/users/users.server.ts
+++ b/apps/carbon/app/modules/users/users.server.ts
@@ -1,9 +1,9 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import type { Database, Json } from "@carbon/database";
import { redis } from "@carbon/kv";
import type { SupabaseClient } from "@supabase/supabase-js";
import { redirect } from "@vercel/remix";
import crypto from "crypto";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import { getSupplierContact } from "~/modules/purchasing";
import { getCustomerContact } from "~/modules/sales";
import type {
@@ -94,7 +94,7 @@ export async function createCustomerAccount(
return error(insertUser, "No data returned from create user");
const permissions = makeCustomerPermissions(companyId);
- const supabaseAdmin = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const [
updateContact,
@@ -109,7 +109,7 @@ export async function createCustomerAccount(
companyId,
}),
addUserToCompany(client, { userId, companyId, role: "customer" }),
- setUserPermissions(supabaseAdmin, userId, permissions),
+ setUserPermissions(serviceRole, userId, permissions),
]);
if (updateContact.error) {
@@ -168,7 +168,7 @@ export async function createEmployeeAccount(
);
const permissions = makePermissionsFromEmployeeType(employeeTypePermissions);
- const supabaseAdmin = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const user = await getUserByEmail(email);
let userExists = false;
@@ -213,7 +213,7 @@ export async function createEmployeeAccount(
locationId,
}),
addUserToCompany(client, { userId, companyId, role: "employee" }),
- setUserPermissions(supabaseAdmin, userId, permissions),
+ setUserPermissions(serviceRole, userId, permissions),
]);
if (employeeInsert.error) {
@@ -295,7 +295,7 @@ export async function createSupplierAccount(
if (!insertUser.data)
return error(insertUser, "No data returned from create user");
- const supabaseAdmin = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const permissions = makeSupplierPermissions(companyId);
const [
@@ -311,7 +311,7 @@ export async function createSupplierAccount(
companyId,
}),
addUserToCompany(client, { userId, companyId, role: "supplier" }),
- setUserPermissions(supabaseAdmin, userId, permissions),
+ setUserPermissions(serviceRole, userId, permissions),
]);
if (updateContact.error) {
@@ -418,7 +418,7 @@ export async function getUser(client: SupabaseClient<Database>, id: string) {
}
export async function getUserByEmail(email: string) {
- return getSupabaseServiceRole()
+ return getCarbonServiceRole()
.from("user")
.select("*")
.eq("email", email)
@@ -440,7 +440,7 @@ export async function getUserClaims(userId: string, companyId: string) {
if (!claims) {
// TODO: remove service role from here, and move it up a level
const rawClaims = await getClaims(
- getSupabaseServiceRole(),
+ getCarbonServiceRole(),
userId,
companyId
);
@@ -782,7 +782,7 @@ export async function resendInvite(
}
export async function resetPassword(userId: string, password: string) {
- return getSupabaseServiceRole().auth.admin.updateUserById(userId, {
+ return getCarbonServiceRole().auth.admin.updateUserById(userId, {
password,
});
}
@@ -970,7 +970,7 @@ export async function updatePermissions(
});
}
- const permissionsUpdate = await getSupabaseServiceRole()
+ const permissionsUpdate = await getCarbonServiceRole()
.from("userPermission")
.update({ permissions: updatedPermissions })
.eq("id", id);
diff --git a/apps/carbon/app/root.tsx b/apps/carbon/app/root.tsx
index 308cce634d..75a4b37147 100644
--- a/apps/carbon/app/root.tsx
+++ b/apps/carbon/app/root.tsx
@@ -1,3 +1,4 @@
+import { getBrowserEnv } from "@carbon/auth";
import { validator } from "@carbon/form";
import { Button, Heading, toast } from "@carbon/react";
import {
@@ -18,7 +19,6 @@ import type {
} from "@vercel/remix";
import { json } from "@vercel/remix";
import React, { useEffect } from "react";
-import { getBrowserEnv } from "~/config/env";
import { getMode, setMode } from "~/services/mode.server";
import Background from "~/styles/background.css?url";
import NProgress from "~/styles/nprogress.css?url";
diff --git a/apps/carbon/app/routes/_public+/callback.tsx b/apps/carbon/app/routes/_public+/callback.tsx
index fd23b88176..6b5059abf2 100644
--- a/apps/carbon/app/routes/_public+/callback.tsx
+++ b/apps/carbon/app/routes/_public+/callback.tsx
@@ -1,10 +1,9 @@
+import { carbonClient, getCarbonServiceRole } from "@carbon/auth";
import { validator } from "@carbon/form";
import { useFetcher } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { useEffect, useRef } from "react";
-import { getSupabaseServiceRole } from "~/lib/supabase";
-import { supabaseClient } from "~/lib/supabase/client";
import { getUserByEmail } from "~/modules/users/users.server";
import { callbackValidator } from "~/services/auth/auth.models";
import { refreshAccessToken } from "~/services/auth/auth.server";
@@ -41,8 +40,8 @@ export async function action({ request }: ActionFunctionArgs): FormActionData {
}
const { refreshToken, userId } = validation.data;
- const supabaseServiceClient = getSupabaseServiceRole();
- const companies = await supabaseServiceClient
+ const serviceRole = getCarbonServiceRole();
+ const companies = await serviceRole
.from("userToCompany")
.select("companyId")
.eq("userId", userId);
@@ -86,7 +85,7 @@ export default function AuthCallback() {
useEffect(() => {
const {
data: { subscription },
- } = supabaseClient.auth.onAuthStateChange((event, supabaseSession) => {
+ } = carbonClient.auth.onAuthStateChange((event, session) => {
if (
["SIGNED_IN", "INITIAL_SESSION"].includes(event) &&
!isAuthenticating.current
@@ -100,8 +99,8 @@ export default function AuthCallback() {
// we should not trust what's happen client side
// so, we only pick the refresh token, and let's back-end getting user session from it
- const refreshToken = supabaseSession?.refresh_token;
- const userId = supabaseSession?.user.id;
+ const refreshToken = session?.refresh_token;
+ const userId = session?.user.id;
if (!refreshToken || !userId) return;
diff --git a/apps/carbon/app/routes/_public+/healthcheck.tsx b/apps/carbon/app/routes/_public+/healthcheck.tsx
index e7015c1f64..a1f534da90 100644
--- a/apps/carbon/app/routes/_public+/healthcheck.tsx
+++ b/apps/carbon/app/routes/_public+/healthcheck.tsx
@@ -1,8 +1,8 @@
-import { getSupabaseServiceRole } from "~/lib/supabase";
+import { getCarbonServiceRole } from "@carbon/auth";
export async function loader() {
try {
- const client = getSupabaseServiceRole();
+ const client = getCarbonServiceRole();
const test = await client.from("attributeDataType").select("*");
if (test.error !== null) throw test.error;
return new Response("OK");
diff --git a/apps/carbon/app/routes/oauth+/token.tsx b/apps/carbon/app/routes/oauth+/token.tsx
index dd00112688..be43fb3008 100644
--- a/apps/carbon/app/routes/oauth+/token.tsx
+++ b/apps/carbon/app/routes/oauth+/token.tsx
@@ -1,7 +1,7 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validator } from "@carbon/form";
import { json, type ActionFunctionArgs } from "@vercel/remix";
import { z } from "zod";
-import { getSupabaseServiceRole } from "~/lib/supabase";
// export const config = { runtime: "nodejs" };
@@ -15,7 +15,7 @@ const oauthTokenValidator = z.object({
});
export async function action({ request }: ActionFunctionArgs) {
- const client = getSupabaseServiceRole();
+ const client = getCarbonServiceRole();
const validation = await validator(oauthTokenValidator).validate(
await request.formData()
);
diff --git a/apps/carbon/app/routes/onboarding+/company.tsx b/apps/carbon/app/routes/onboarding+/company.tsx
index 644b03b41f..6aaa7a7fde 100644
--- a/apps/carbon/app/routes/onboarding+/company.tsx
+++ b/apps/carbon/app/routes/onboarding+/company.tsx
@@ -1,3 +1,4 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { ValidatedForm, validationError, validator } from "@carbon/form";
import {
Button,
@@ -15,7 +16,6 @@ import { Link, useLoaderData } from "@remix-run/react";
import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";
import { Hidden, Input, Submit } from "~/components/Form";
import { useOnboarding } from "~/hooks";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import { insertEmployeeJob } from "~/modules/people";
import { getLocationsList, upsertLocation } from "~/modules/resources";
import {
@@ -63,7 +63,7 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const supabaseClient = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const { next, ...data } = validation.data;
let companyId: string | undefined;
@@ -76,11 +76,11 @@ export async function action({ request }: ActionFunctionArgs) {
if (company && location) {
const [companyUpdate, locationUpdate] = await Promise.all([
- updateCompany(supabaseClient, company.id!, {
+ updateCompany(serviceRole, company.id!, {
...data,
updatedBy: userId,
}),
- upsertLocation(supabaseClient, {
+ upsertLocation(serviceRole, {
...location,
...data,
timezone: getLocalTimeZone(),
@@ -96,7 +96,7 @@ export async function action({ request }: ActionFunctionArgs) {
throw new Error("Fatal: failed to update location");
}
} else {
- const companyInsert = await insertCompany(supabaseClient, data);
+ const companyInsert = await insertCompany(serviceRole, data);
if (companyInsert.error) {
console.error(companyInsert.error);
throw new Error("Fatal: failed to insert company");
@@ -107,7 +107,7 @@ export async function action({ request }: ActionFunctionArgs) {
throw new Error("Fatal: failed to get company ID");
}
- const seed = await seedCompany(supabaseClient, companyId, userId);
+ const seed = await seedCompany(serviceRole, companyId, userId);
if (seed.error) {
console.error(seed.error);
throw new Error("Fatal: failed to seed company");
@@ -115,7 +115,7 @@ export async function action({ request }: ActionFunctionArgs) {
// TODO: move all of this to transaction
const [locationInsert] = await Promise.all([
- upsertLocation(supabaseClient, {
+ upsertLocation(serviceRole, {
...data,
name: "Headquarters",
companyId,
@@ -135,7 +135,7 @@ export async function action({ request }: ActionFunctionArgs) {
}
const [job] = await Promise.all([
- insertEmployeeJob(supabaseClient, {
+ insertEmployeeJob(serviceRole, {
id: userId,
companyId,
locationId,
diff --git a/apps/carbon/app/routes/onboarding+/user.tsx b/apps/carbon/app/routes/onboarding+/user.tsx
index 92bd73c3c0..9f1a4e4b37 100644
--- a/apps/carbon/app/routes/onboarding+/user.tsx
+++ b/apps/carbon/app/routes/onboarding+/user.tsx
@@ -1,3 +1,4 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { ValidatedForm, validationError, validator } from "@carbon/form";
import {
Button,
@@ -14,7 +15,6 @@ import { redirect, type ActionFunctionArgs } from "@vercel/remix";
import type { z } from "zod";
import { Hidden, Input, Password, Submit } from "~/components/Form";
import { useOnboarding } from "~/hooks";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import {
onboardingUserValidator,
updatePublicAccount,
@@ -53,11 +53,13 @@ export async function action({ request }: ActionFunctionArgs) {
const { firstName, lastName, email, password, next } = validation.data;
- const updatePassword =
- await getSupabaseServiceRole().auth.admin.updateUserById(userId, {
+ const updatePassword = await getCarbonServiceRole().auth.admin.updateUserById(
+ userId,
+ {
email,
password,
- });
+ }
+ );
if (updatePassword.error) {
console.error(updatePassword.error);
diff --git a/apps/carbon/app/routes/x+/_layout.tsx b/apps/carbon/app/routes/x+/_layout.tsx
index c95a89c099..37eef97aa1 100644
--- a/apps/carbon/app/routes/x+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/_layout.tsx
@@ -5,10 +5,10 @@ import { json, redirect } from "@vercel/remix";
import NProgress from "nprogress";
import { useEffect } from "react";
+import { CarbonProvider, getCarbon } from "@carbon/auth";
import { RealtimeDataProvider } from "~/components";
import { PrimaryNavigation, Topbar } from "~/components/Layout";
import { AutodeskProvider } from "~/lib/autodesk";
-import { SupabaseProvider, getSupabase } from "~/lib/supabase";
import { getCompanies, getCompanyIntegrations } from "~/modules/settings";
import { getCustomFieldsSchemas } from "~/modules/shared/shared.server";
import {
@@ -63,7 +63,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
// });
// share a client between requests
- const client = getSupabase(accessToken);
+ const client = getCarbon(accessToken);
// parallelize the requests
const [
@@ -134,7 +134,7 @@ export default function AuthenticatedRoute() {
}, [transition.state]);
return (
- <SupabaseProvider session={session}>
+ <CarbonProvider session={session}>
<RealtimeDataProvider>
<AutodeskProvider token={autodesk}>
<TooltipProvider>
@@ -160,6 +160,6 @@ export default function AuthenticatedRoute() {
</TooltipProvider>
</AutodeskProvider>
</RealtimeDataProvider>
- </SupabaseProvider>
+ </CarbonProvider>
);
}
diff --git a/apps/carbon/app/routes/x+/account+/password.tsx b/apps/carbon/app/routes/x+/account+/password.tsx
index 5790da22fc..e567f78f4c 100644
--- a/apps/carbon/app/routes/x+/account+/password.tsx
+++ b/apps/carbon/app/routes/x+/account+/password.tsx
@@ -1,7 +1,7 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import { PasswordForm, accountPasswordValidator } from "~/modules/account";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
@@ -29,11 +29,10 @@ export async function action({ request }: ActionFunctionArgs) {
const { currentPassword, password } = validation.data;
- const confirmPassword =
- await getSupabaseServiceRole().auth.signInWithPassword({
- email,
- password: currentPassword,
- });
+ const confirmPassword = await getCarbonServiceRole().auth.signInWithPassword({
+ email,
+ password: currentPassword,
+ });
if (confirmPassword.error || !("user" in confirmPassword.data)) {
return json(
@@ -42,10 +41,12 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- const updatePassword =
- await getSupabaseServiceRole().auth.admin.updateUserById(userId, {
+ const updatePassword = await getCarbonServiceRole().auth.admin.updateUserById(
+ userId,
+ {
password,
- });
+ }
+ );
if (updatePassword.error) {
return json(
diff --git a/apps/carbon/app/routes/x+/api+/$lang.intro.tsx b/apps/carbon/app/routes/x+/api+/$lang.intro.tsx
index 2b042fa7e3..8d8c65d525 100644
--- a/apps/carbon/app/routes/x+/api+/$lang.intro.tsx
+++ b/apps/carbon/app/routes/x+/api+/$lang.intro.tsx
@@ -1,7 +1,7 @@
+import { getBrowserEnv, SUPABASE_ANON_PUBLIC } from "@carbon/auth";
import { Alert, AlertDescription, AlertTitle } from "@carbon/react";
import { Link } from "@remix-run/react";
import { LuAlertTriangle } from "react-icons/lu";
-import { getBrowserEnv, SUPABASE_ANON_PUBLIC } from "~/config/env";
import { CodeSnippet, Snippets, useSelectedLang } from "~/modules/api";
import { path } from "~/utils/path";
diff --git a/apps/carbon/app/routes/x+/api+/$lang.table.$id.tsx b/apps/carbon/app/routes/x+/api+/$lang.table.$id.tsx
index acaeffdc3a..55df3c99f4 100644
--- a/apps/carbon/app/routes/x+/api+/$lang.table.$id.tsx
+++ b/apps/carbon/app/routes/x+/api+/$lang.table.$id.tsx
@@ -1,6 +1,6 @@
+import { getBrowserEnv } from "@carbon/auth";
import { swaggerDocsSchema } from "@carbon/database";
import { useParams } from "@remix-run/react";
-import { getBrowserEnv } from "~/config/env";
import { TableDocs, useSelectedLang } from "~/modules/api";
import { snakeToCamel } from "~/utils/string";
diff --git a/apps/carbon/app/routes/x+/customer+/$customerId.contacts.new.tsx b/apps/carbon/app/routes/x+/customer+/$customerId.contacts.new.tsx
index 25486efa50..d1ffb76022 100644
--- a/apps/carbon/app/routes/x+/customer+/$customerId.contacts.new.tsx
+++ b/apps/carbon/app/routes/x+/customer+/$customerId.contacts.new.tsx
@@ -1,8 +1,8 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { useNavigate, useParams } from "@remix-run/react";
import type { ActionFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import {
CustomerContactForm,
customerContactValidator,
@@ -22,7 +22,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
});
// RLS doesn't work for selecting a contact with no customer
- const client = getSupabaseServiceRole();
+ const client = getCarbonServiceRole();
const { customerId } = params;
if (!customerId) throw notFound("customerId not found");
diff --git a/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx b/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx
index 2125bb0ae9..3bd9e44258 100644
--- a/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx
@@ -1,9 +1,9 @@
+import { useCarbon } from "@carbon/auth";
import { useLoaderData } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { useCallback, useState } from "react";
import InfiniteScroll from "~/components/InfiniteScroll";
-import { useSupabase } from "~/lib/supabase";
import { getItemLedger, InventoryActivity } from "~/modules/inventory";
import { getLocationsList } from "~/modules/resources";
import { getUserDefaults } from "~/modules/users/users.server";
@@ -83,7 +83,7 @@ export default function ItemInventoryActivityRoute() {
const { initialItemLedgers, itemId, companyId, locationId } =
useLoaderData<typeof loader>();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const [itemLedgers, setItemLedgers] = useState<any[]>(initialItemLedgers);
const [page, setPage] = useState(1);
@@ -96,7 +96,7 @@ export default function ItemInventoryActivityRoute() {
setIsLoading(true);
const newItemLedgers = await getItemLedger(
- supabase!,
+ carbon!,
itemId,
companyId,
locationId,
@@ -115,7 +115,7 @@ export default function ItemInventoryActivityRoute() {
}
setIsLoading(false);
- }, [page, supabase, companyId, locationId, itemId, isLoading, hasMore]);
+ }, [page, carbon, companyId, locationId, itemId, isLoading, hasMore]);
return (
<>
diff --git a/apps/carbon/app/routes/x+/items+/methods+/get.tsx b/apps/carbon/app/routes/x+/items+/methods+/get.tsx
index 50084e2d55..bec52513fd 100644
--- a/apps/carbon/app/routes/x+/items+/methods+/get.tsx
+++ b/apps/carbon/app/routes/x+/items+/methods+/get.tsx
@@ -1,6 +1,6 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import { copyMakeMethod, getMethodValidator } from "~/modules/items";
import { requirePermissions } from "~/services/auth/auth.server";
import { path, requestReferrer } from "~/utils/path";
@@ -10,7 +10,7 @@ export async function action({ request }: ActionFunctionArgs) {
update: "parts",
});
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const validation = await validator(getMethodValidator).validate(
await request.formData()
diff --git a/apps/carbon/app/routes/x+/items+/methods+/save.tsx b/apps/carbon/app/routes/x+/items+/methods+/save.tsx
index ac9ae5dd86..849771d143 100644
--- a/apps/carbon/app/routes/x+/items+/methods+/save.tsx
+++ b/apps/carbon/app/routes/x+/items+/methods+/save.tsx
@@ -1,6 +1,6 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import { copyMakeMethod, getMethodValidator } from "~/modules/items";
import { requirePermissions } from "~/services/auth/auth.server";
import { path, requestReferrer } from "~/utils/path";
@@ -10,7 +10,7 @@ export async function action({ request }: ActionFunctionArgs) {
update: "parts",
});
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const validation = await validator(getMethodValidator).validate(
await request.formData()
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.details.tsx b/apps/carbon/app/routes/x+/job+/$jobId.details.tsx
index a7c3997419..46a7278d2e 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.details.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.details.tsx
@@ -1,3 +1,4 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import {
Card,
@@ -12,7 +13,6 @@ import { redirect } from "@vercel/remix";
import { Suspense } from "react";
import { CadModel, Documents } from "~/components";
import { usePermissions, useRealtime, useRouteData } from "~/hooks";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import type { Job } from "~/modules/production";
import {
JobForm,
@@ -62,14 +62,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const recalculate = await recalculateJobRequirements(
- getSupabaseServiceRole(),
- {
- id,
- companyId,
- userId,
- }
- );
+ const recalculate = await recalculateJobRequirements(getCarbonServiceRole(), {
+ id,
+ companyId,
+ userId,
+ });
if (recalculate.error) {
throw redirect(
path.to.job(id),
diff --git a/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.$id.tsx b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
index 2f589083b9..0a35f37f28 100644
--- a/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
+++ b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
@@ -1,6 +1,6 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { json, type ActionFunctionArgs } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import {
jobMaterialValidator,
recalculateJobMakeMethodRequirements,
@@ -34,7 +34,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const updateJobMaterial = await upsertJobMaterial(serviceRole, {
jobId,
...validation.data,
diff --git a/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.new.tsx b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.new.tsx
index 93fc8525e7..615f8f5980 100644
--- a/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.new.tsx
+++ b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.new.tsx
@@ -1,6 +1,6 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { json, type ActionFunctionArgs } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import {
jobMaterialValidator,
recalculateJobMakeMethodRequirements,
@@ -33,7 +33,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id, ...data } = validation.data;
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const insertJobMaterial = await upsertJobMaterial(serviceRole, {
...data,
jobId,
diff --git a/apps/carbon/app/routes/x+/job+/methods+/$jobId.operation.new.tsx b/apps/carbon/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
index 9ffcb85aa8..786e8d4dde 100644
--- a/apps/carbon/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
+++ b/apps/carbon/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
@@ -1,6 +1,6 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { json, type ActionFunctionArgs } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import {
jobOperationValidator,
recalculateJobMakeMethodRequirements,
@@ -18,7 +18,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
create: "production",
});
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const { jobId } = params;
if (!jobId) {
throw new Error("jobId not found");
diff --git a/apps/carbon/app/routes/x+/job+/methods+/get.tsx b/apps/carbon/app/routes/x+/job+/methods+/get.tsx
index f4420739b5..4b60cdfb09 100644
--- a/apps/carbon/app/routes/x+/job+/methods+/get.tsx
+++ b/apps/carbon/app/routes/x+/job+/methods+/get.tsx
@@ -1,6 +1,6 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import {
getJobMethodValidator,
recalculateJobRequirements,
@@ -18,7 +18,7 @@ export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const type = formData.get("type") as string;
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const validation = await validator(getJobMethodValidator).validate(formData);
if (validation.error) {
diff --git a/apps/carbon/app/routes/x+/job+/methods+/save.tsx b/apps/carbon/app/routes/x+/job+/methods+/save.tsx
index b9bb3bdb55..a5dd9a4909 100644
--- a/apps/carbon/app/routes/x+/job+/methods+/save.tsx
+++ b/apps/carbon/app/routes/x+/job+/methods+/save.tsx
@@ -1,6 +1,6 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import {
getJobMethodValidator,
upsertMakeMethodFromJob,
@@ -17,7 +17,7 @@ export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const type = formData.get("type") as string;
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const validation = await validator(getJobMethodValidator).validate(formData);
if (validation.error) {
return validationError(validation.error);
diff --git a/apps/carbon/app/routes/x+/job+/new.tsx b/apps/carbon/app/routes/x+/job+/new.tsx
index 95e3ffd933..5c5e691f16 100644
--- a/apps/carbon/app/routes/x+/job+/new.tsx
+++ b/apps/carbon/app/routes/x+/job+/new.tsx
@@ -1,9 +1,9 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { tasks } from "@trigger.dev/sdk/v3";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
import { useUrlParams, useUser } from "~/hooks";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import {
JobForm,
jobValidator,
@@ -33,7 +33,7 @@ export async function action({ request }: ActionFunctionArgs) {
const { companyId, userId } = await requirePermissions(request, {
create: "production",
});
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const formData = await request.formData();
const validation = await validator(jobValidator).validate(formData);
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.convert.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.convert.tsx
index 5de69a5ff5..f70ff6b6d3 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.convert.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.convert.tsx
@@ -1,5 +1,5 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { redirect, type ActionFunctionArgs } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import { convertQuoteToOrder, selectedLinesValidator } from "~/modules/sales";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
@@ -40,7 +40,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const selectedLines = parseResult.data;
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const convert = await convertQuoteToOrder(serviceRole, {
id: quoteId,
companyId,
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
index b53cee50ac..1152c8b61f 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import type { JSONContent } from "@carbon/react";
import {
@@ -18,7 +19,6 @@ import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
import { nanoid } from "nanoid";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type {
Opportunity,
Quotation,
@@ -151,15 +151,13 @@ const QuoteNotes = ({ quote }: { quote: Quotation }) => {
id: userId,
company: { id: companyId },
} = useUser();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const permissions = usePermissions();
const onUploadImage = async (file: File) => {
const fileType = file.name.split(".").pop();
const fileName = `${companyId}/quote/${quote.id}/${nanoid()}.${fileType}`;
- const result = await supabase?.storage
- .from("private")
- .upload(fileName, file);
+ const result = await carbon?.storage.from("private").upload(fileName, file);
if (result?.error) {
toast.error("Failed to upload image");
@@ -174,7 +172,7 @@ const QuoteNotes = ({ quote }: { quote: Quotation }) => {
};
const onUpdateExternalNotes = useThrottle(async (content: JSONContent) => {
- await supabase
+ await carbon
?.from("quote")
.update({
externalNotes: content,
@@ -185,7 +183,7 @@ const QuoteNotes = ({ quote }: { quote: Quotation }) => {
}, 2500);
const onUpdateInternalNotes = useThrottle(async (content: JSONContent) => {
- await supabase
+ await carbon
?.from("quote")
.update({
internalNotes: content,
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.new.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.new.tsx
index 1955188f74..8e2efad5a6 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.new.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.new.tsx
@@ -1,7 +1,7 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import {
quoteLineValidator,
upsertQuoteLine,
@@ -32,7 +32,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id, ...data } = validation.data;
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const createQuotationLine = await upsertQuoteLine(serviceRole, {
...data,
companyId,
diff --git a/apps/carbon/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsx b/apps/carbon/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsx
index df72910cbf..027633ee16 100644
--- a/apps/carbon/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsx
+++ b/apps/carbon/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsx
@@ -1,6 +1,6 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { json, type ActionFunctionArgs } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import { quoteMaterialValidator, upsertQuoteMaterial } from "~/modules/sales";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
@@ -32,7 +32,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const updateQuoteMaterial = await upsertQuoteMaterial(serviceRole, {
quoteId,
quoteLineId: lineId,
diff --git a/apps/carbon/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx b/apps/carbon/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx
index f6306f529e..499999a036 100644
--- a/apps/carbon/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx
+++ b/apps/carbon/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx
@@ -1,6 +1,6 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { json, type ActionFunctionArgs } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import {
quoteMaterialValidator,
upsertQuoteMaterial,
@@ -35,7 +35,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id, ...data } = validation.data;
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const insertQuoteMaterial = await upsertQuoteMaterial(serviceRole, {
...data,
quoteId,
diff --git a/apps/carbon/app/routes/x+/quote+/methods+/get.tsx b/apps/carbon/app/routes/x+/quote+/methods+/get.tsx
index 0d11efdaf2..b29b5589c0 100644
--- a/apps/carbon/app/routes/x+/quote+/methods+/get.tsx
+++ b/apps/carbon/app/routes/x+/quote+/methods+/get.tsx
@@ -1,6 +1,6 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import {
getLineMethodValidator,
getMethodValidator,
@@ -18,7 +18,7 @@ export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const type = formData.get("type") as string;
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
if (type === "line") {
const validation = await validator(getLineMethodValidator).validate(
formData
diff --git a/apps/carbon/app/routes/x+/quote+/methods+/save.tsx b/apps/carbon/app/routes/x+/quote+/methods+/save.tsx
index b16d6646a2..0e5d83677f 100644
--- a/apps/carbon/app/routes/x+/quote+/methods+/save.tsx
+++ b/apps/carbon/app/routes/x+/quote+/methods+/save.tsx
@@ -1,6 +1,6 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import {
getLineMethodValidator,
getMethodValidator,
@@ -18,7 +18,7 @@ export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const type = formData.get("type") as string;
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
if (type === "line") {
const validation = await validator(getLineMethodValidator).validate(
formData
diff --git a/apps/carbon/app/routes/x+/receipt+/$receiptId.details.tsx b/apps/carbon/app/routes/x+/receipt+/$receiptId.details.tsx
index 551017f06c..06944cba88 100644
--- a/apps/carbon/app/routes/x+/receipt+/$receiptId.details.tsx
+++ b/apps/carbon/app/routes/x+/receipt+/$receiptId.details.tsx
@@ -1,9 +1,9 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { useParams } from "@remix-run/react";
import type { ActionFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { useRouteData } from "~/hooks";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import type { Receipt, ReceiptLine } from "~/modules/inventory";
import {
ReceiptForm,
@@ -52,7 +52,7 @@ export async function action({ request }: ActionFunctionArgs) {
currentReceipt.data.locationId !== data.locationId;
if (receiptDataHasChanged) {
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
switch (data.sourceDocument) {
case "Purchase Order":
const purchaseOrderReceipt = await serviceRole.functions.invoke<{
diff --git a/apps/carbon/app/routes/x+/receipt+/new.tsx b/apps/carbon/app/routes/x+/receipt+/new.tsx
index 4ae6730dc8..1bf33ecf76 100644
--- a/apps/carbon/app/routes/x+/receipt+/new.tsx
+++ b/apps/carbon/app/routes/x+/receipt+/new.tsx
@@ -1,5 +1,5 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { redirect, type LoaderFunctionArgs } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import type { ReceiptSourceDocument } from "~/modules/inventory";
import { getUserDefaults } from "~/modules/users/users.server";
import { requirePermissions } from "~/services/auth/auth.server";
@@ -26,7 +26,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
const defaults = await getUserDefaults(client, userId, companyId);
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
switch (sourceDocument) {
case "Purchase Order":
const purchaseOrderReceipt = await serviceRole.functions.invoke<{
diff --git a/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx b/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx
index e28fc8fed1..0270a55607 100644
--- a/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx
+++ b/apps/carbon/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx
@@ -1,8 +1,8 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { tasks } from "@trigger.dev/sdk/v3";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import {
salesOrderToJobValidator,
upsertJob,
@@ -30,7 +30,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { companyId, userId } = await requirePermissions(request, {
create: "production",
});
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const formData = await request.formData();
const validation = await validator(salesOrderToJobValidator).validate(
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.convert.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.convert.tsx
index 822aa9ce13..9dcd4bc5cc 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.convert.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.convert.tsx
@@ -1,5 +1,5 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { redirect, type ActionFunctionArgs } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import { convertSalesRfqToQuote } from "~/modules/sales";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
@@ -16,7 +16,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { rfqId: id } = params;
if (!id) throw new Error("Could not find id");
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const convert = await convertSalesRfqToQuote(serviceRole, {
id,
companyId,
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
index f4ae03da96..780bf73192 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import type { JSONContent } from "@carbon/react";
import {
@@ -19,7 +20,6 @@ import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
import { nanoid } from "nanoid";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import type {
Opportunity,
SalesRFQ,
@@ -131,7 +131,7 @@ const SalesRFQNotes = ({ salesRfq }: { salesRfq: SalesRFQ }) => {
id: userId,
company: { id: companyId },
} = useUser();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const permissions = usePermissions();
const onUploadImage = async (file: File) => {
@@ -140,9 +140,7 @@ const SalesRFQNotes = ({ salesRfq }: { salesRfq: SalesRFQ }) => {
salesRfq.id
}/${nanoid()}.${fileType}`;
- const result = await supabase?.storage
- .from("private")
- .upload(fileName, file);
+ const result = await carbon?.storage.from("private").upload(fileName, file);
if (result?.error) {
toast.error("Failed to upload image");
@@ -157,7 +155,7 @@ const SalesRFQNotes = ({ salesRfq }: { salesRfq: SalesRFQ }) => {
};
const onUpdateExternalNotes = useThrottle(async (content: JSONContent) => {
- await supabase
+ await carbon
?.from("salesRfq")
.update({
externalNotes: content,
@@ -168,7 +166,7 @@ const SalesRFQNotes = ({ salesRfq }: { salesRfq: SalesRFQ }) => {
}, 2500);
const onUpdateInternalNotes = useThrottle(async (content: JSONContent) => {
- await supabase
+ await carbon
?.from("salesRfq")
.update({
internalNotes: content,
diff --git a/apps/carbon/app/routes/x+/settings+/company.new.tsx b/apps/carbon/app/routes/x+/settings+/company.new.tsx
index 4631e472d9..77802ae174 100644
--- a/apps/carbon/app/routes/x+/settings+/company.new.tsx
+++ b/apps/carbon/app/routes/x+/settings+/company.new.tsx
@@ -1,9 +1,9 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { redis } from "@carbon/kv";
import { getLocalTimeZone } from "@internationalized/date";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import { insertEmployeeJob } from "~/modules/people";
import { upsertLocation } from "~/modules/resources";
import {
@@ -28,7 +28,7 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const client = getSupabaseServiceRole();
+ const client = getCarbonServiceRole();
const companyInsert = await insertCompany(client, validation.data);
if (companyInsert.error) {
diff --git a/apps/carbon/app/routes/x+/settings+/terms.tsx b/apps/carbon/app/routes/x+/settings+/terms.tsx
index f2518ff761..e9764bd71f 100644
--- a/apps/carbon/app/routes/x+/settings+/terms.tsx
+++ b/apps/carbon/app/routes/x+/settings+/terms.tsx
@@ -1,3 +1,4 @@
+import { useCarbon } from "@carbon/auth";
import type { JSONContent } from "@carbon/react";
import {
Badge,
@@ -19,7 +20,6 @@ import type { LoaderFunctionArgs } from "@vercel/remix";
import { useState } from "react";
import { LuCheckCircle } from "react-icons/lu";
import { usePermissions, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
import { getTerms } from "~/modules/settings";
import { requirePermissions } from "~/services/auth/auth.server";
@@ -54,7 +54,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
export default function Terms() {
const { terms } = useLoaderData<typeof loader>();
const permissions = usePermissions();
- const { supabase } = useSupabase();
+ const { carbon } = useCarbon();
const {
id: userId,
company: { id: companyId },
@@ -72,8 +72,8 @@ export default function Terms() {
onUpdatePurchasingTerms(content);
};
const onUpdatePurchasingTerms = useThrottle(async (content: JSONContent) => {
- if (!supabase) return;
- const { error } = await supabase
+ if (!carbon) return;
+ const { error } = await carbon
.from("terms")
.update({
purchasingTerms: content,
@@ -90,7 +90,7 @@ export default function Terms() {
};
const onUpdateSalesTerms = useThrottle(async (content: JSONContent) => {
setSalesTermsStatus("draft");
- await supabase
+ await carbon
?.from("terms")
.update({
salesTerms: content,
diff --git a/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.new.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.new.tsx
index 46789b7099..152e98b9d3 100644
--- a/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.new.tsx
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.new.tsx
@@ -1,8 +1,8 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { validationError, validator } from "@carbon/form";
import { useNavigate, useParams } from "@remix-run/react";
import type { ActionFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import {
SupplierContactForm,
insertSupplierContact,
@@ -22,7 +22,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
});
// RLS doesn't work for selecting a contact with no supplier
- const client = getSupabaseServiceRole();
+ const client = getCarbonServiceRole();
const { supplierId } = params;
if (!supplierId) throw notFound("supplierId not found");
diff --git a/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx b/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx
index 8cc54d1f81..17b8a8bfa4 100644
--- a/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx
+++ b/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx
@@ -1,9 +1,9 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import type { Json } from "@carbon/database";
import { validationError, validator } from "@carbon/form";
import { useLoaderData } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import type { CompanyPermission } from "~/modules/users";
import {
EmployeePermissionsForm,
@@ -32,7 +32,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { employeeId } = params;
if (!employeeId) throw notFound("employeeId not found");
- const client = getSupabaseServiceRole();
+ const client = getCarbonServiceRole();
const [rawClaims, employee, employeeTypes] = await Promise.all([
getClaims(client, employeeId, companyId),
getEmployee(client, employeeId, companyId),
diff --git a/apps/carbon/app/services/auth/auth.server.ts b/apps/carbon/app/services/auth/auth.server.ts
index 010d8db59a..040b457d5e 100644
--- a/apps/carbon/app/services/auth/auth.server.ts
+++ b/apps/carbon/app/services/auth/auth.server.ts
@@ -1,11 +1,15 @@
+import {
+ REFRESH_ACCESS_TOKEN_THRESHOLD,
+ VERCEL_URL,
+ getCarbon,
+ getCarbonServiceRole,
+} from "@carbon/auth";
import type { Database } from "@carbon/database";
import type {
AuthSession as SupabaseAuthSession,
SupabaseClient,
} from "@supabase/supabase-js";
import { redirect } from "@vercel/remix";
-import { REFRESH_ACCESS_TOKEN_THRESHOLD, VERCEL_URL } from "~/config/env";
-import { getSupabase, getSupabaseServiceRole } from "~/lib/supabase";
import { getCompaniesForUser } from "~/modules/users";
import { getUserClaims } from "~/modules/users/users.server";
import { flash, requireAuthSession } from "~/services/session.server";
@@ -18,7 +22,7 @@ export async function createEmailAuthAccount(
password: string,
meta?: Record<string, unknown>
) {
- const { data, error } = await getSupabaseServiceRole().auth.admin.createUser({
+ const { data, error } = await getCarbonServiceRole().auth.admin.createUser({
email,
password,
email_confirm: true,
@@ -33,9 +37,7 @@ export async function createEmailAuthAccount(
}
export async function deleteAuthAccount(userId: string) {
- const { error } = await getSupabaseServiceRole().auth.admin.deleteUser(
- userId
- );
+ const { error } = await getCarbonServiceRole().auth.admin.deleteUser(userId);
if (error) return null;
@@ -43,7 +45,7 @@ export async function deleteAuthAccount(userId: string) {
}
export async function getAuthAccountByAccessToken(accessToken: string) {
- const { data, error } = await getSupabaseServiceRole().auth.getUser(
+ const { data, error } = await getCarbonServiceRole().auth.getUser(
accessToken
);
@@ -53,26 +55,24 @@ export async function getAuthAccountByAccessToken(accessToken: string) {
}
function makeAuthSession(
- supabaseSession: SupabaseAuthSession | null,
+ session: SupabaseAuthSession | null,
companyId: string
): AuthSession | null {
- if (!supabaseSession) return null;
+ if (!session) return null;
- if (!supabaseSession.refresh_token)
+ if (!session.refresh_token)
throw new Error("User should have a refresh token");
- if (!supabaseSession.user?.email)
- throw new Error("User should have an email");
+ if (!session.user?.email) throw new Error("User should have an email");
return {
- accessToken: supabaseSession.access_token,
+ accessToken: session.access_token,
companyId,
- refreshToken: supabaseSession.refresh_token,
- userId: supabaseSession.user.id,
- email: supabaseSession.user.email,
- expiresIn:
- (supabaseSession.expires_in ?? 3000) - REFRESH_ACCESS_TOKEN_THRESHOLD,
- expiresAt: supabaseSession.expires_at ?? -1,
+ refreshToken: session.refresh_token,
+ userId: session.user.id,
+ email: session.user.email,
+ expiresIn: (session.expires_in ?? 3000) - REFRESH_ACCESS_TOKEN_THRESHOLD,
+ expiresAt: session.expires_at ?? -1,
};
}
@@ -95,7 +95,7 @@ export async function requirePermissions(
request
);
- const client = getSupabase(accessToken);
+ const client = getCarbon(accessToken);
// early exit if no requiredPermissions are required
if (Object.keys(requiredPermissions).length === 0)
return { client, companyId, email, userId };
@@ -148,7 +148,7 @@ export async function requirePermissions(
}
export async function resetPassword(accessToken: string, password: string) {
- const { error } = await getSupabase(accessToken).auth.updateUser({
+ const { error } = await getCarbon(accessToken).auth.updateUser({
password,
});
@@ -161,14 +161,14 @@ export async function sendInviteByEmail(
email: string,
data?: Record<string, unknown>
) {
- return getSupabaseServiceRole().auth.admin.inviteUserByEmail(email, {
+ return getCarbonServiceRole().auth.admin.inviteUserByEmail(email, {
redirectTo: `${VERCEL_URL}/callback`,
data,
});
}
export async function sendMagicLink(email: string) {
- return getSupabaseServiceRole().auth.signInWithOtp({
+ return getCarbonServiceRole().auth.signInWithOtp({
email,
options: {
emailRedirectTo: `${VERCEL_URL}/callback`,
@@ -177,7 +177,7 @@ export async function sendMagicLink(email: string) {
}
export async function signInWithEmail(email: string, password: string) {
- const client = getSupabaseServiceRole();
+ const client = getCarbonServiceRole();
const { data, error } = await client.auth.signInWithPassword({
email,
password,
@@ -195,7 +195,7 @@ export async function refreshAccessToken(
): Promise<AuthSession | null> {
if (!refreshToken) return null;
- const client = getSupabaseServiceRole();
+ const client = getCarbonServiceRole();
const { data, error } = await client.auth.refreshSession({
refresh_token: refreshToken,
diff --git a/apps/carbon/app/services/session.server.ts b/apps/carbon/app/services/session.server.ts
index fab4f693fc..b5345d03f9 100644
--- a/apps/carbon/app/services/session.server.ts
+++ b/apps/carbon/app/services/session.server.ts
@@ -9,7 +9,7 @@ import {
SESSION_MAX_AGE,
SESSION_SECRET,
VERCEL_ENV,
-} from "~/config/env";
+} from "@carbon/auth";
import { redis } from "@carbon/kv";
import { getPermissionCacheKey } from "~/modules/users/users.server";
diff --git a/apps/carbon/app/trigger/autodesk-poll.ts b/apps/carbon/app/trigger/autodesk-poll.ts
index 41f04e9683..1a40b907a8 100644
--- a/apps/carbon/app/trigger/autodesk-poll.ts
+++ b/apps/carbon/app/trigger/autodesk-poll.ts
@@ -1,9 +1,9 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { task } from "@trigger.dev/sdk/v3";
import { getAutodeskToken, getManifest } from "~/lib/autodesk/autodesk.server";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import { upsertModelUpload } from "~/modules/shared";
-const supabaseClient = getSupabaseServiceRole();
+const serviceRole = getCarbonServiceRole();
export const autodeskPollTask = task({
id: "autodesk-poll",
@@ -32,7 +32,7 @@ export const autodeskPollTask = task({
throw new Error("Failed to get manifest: " + manifest.error.message);
}
- const modelRecord = await upsertModelUpload(supabaseClient, {
+ const modelRecord = await upsertModelUpload(serviceRole, {
id,
name,
size,
diff --git a/apps/carbon/app/trigger/autodesk-upload.ts b/apps/carbon/app/trigger/autodesk-upload.ts
index f8cae0297e..a9825f8889 100644
--- a/apps/carbon/app/trigger/autodesk-upload.ts
+++ b/apps/carbon/app/trigger/autodesk-upload.ts
@@ -1,3 +1,4 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { task } from "@trigger.dev/sdk/v3";
import {
finalizeAutodeskUpload,
@@ -6,7 +7,6 @@ import {
translateFile,
uploadToAutodesk,
} from "~/lib/autodesk/autodesk.server";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import { autodeskPollTask } from "./autodesk-poll";
export const autodeskUploadTask = task({
@@ -49,10 +49,10 @@ export const autodeskUploadTask = task({
console.log("Encoded filename", { encodedFilename });
console.log("Getting signed URL and downloading blob");
- const supabaseClient = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
const [signedUrl, blob] = await Promise.all([
getAutodeskSignedUrl(encodedFilename, token),
- supabaseClient.storage.from("private").download(modelPath),
+ serviceRole.storage.from("private").download(modelPath),
]);
if (signedUrl.error) {
console.error("Failed to get signed URL");
@@ -121,7 +121,7 @@ export const autodeskUploadTask = task({
error: JSON.stringify(err, null, 2),
});
- const client = getSupabaseServiceRole();
+ const client = getCarbonServiceRole();
console.log("Resetting modelUploadId");
if (itemId) {
diff --git a/apps/carbon/app/trigger/post-transaction.ts b/apps/carbon/app/trigger/post-transaction.ts
index 664cfe27d7..314d2b4c2c 100644
--- a/apps/carbon/app/trigger/post-transaction.ts
+++ b/apps/carbon/app/trigger/post-transaction.ts
@@ -1,10 +1,10 @@
import { task } from "@trigger.dev/sdk/v3";
import { z } from "zod";
-import { getSupabaseServiceRole } from "~/lib/supabase";
+import { getCarbonServiceRole } from "@carbon/auth";
import type { Result } from "~/types";
-const supabaseClient = getSupabaseServiceRole();
+const serviceRole = getCarbonServiceRole();
const postTransactionSchema = z.object({
documentId: z.string(),
@@ -24,15 +24,12 @@ export const postTransactionTask = task({
switch (payload.type) {
case "receipt":
console.info(`📫 Posting receipt ${payload.documentId}`);
- const postReceipt = await supabaseClient.functions.invoke(
- "post-receipt",
- {
- body: {
- receiptId: payload.documentId,
- userId: payload.userId,
- },
- }
- );
+ const postReceipt = await serviceRole.functions.invoke("post-receipt", {
+ body: {
+ receiptId: payload.documentId,
+ userId: payload.userId,
+ },
+ });
result = {
success: postReceipt.error === null,
@@ -42,7 +39,7 @@ export const postTransactionTask = task({
break;
case "purchase-invoice":
console.info(`📫 Posting purchase invoice ${payload.documentId}`);
- const postPurchaseInvoice = await supabaseClient.functions.invoke(
+ const postPurchaseInvoice = await serviceRole.functions.invoke(
"post-purchase-invoice",
{
body: {
@@ -61,7 +58,7 @@ export const postTransactionTask = task({
console.info(
`💵 Updating pricing from invoice ${payload.documentId}`
);
- const priceUpdate = await supabaseClient.functions.invoke(
+ const priceUpdate = await serviceRole.functions.invoke(
"update-purchased-prices",
{
body: {
diff --git a/apps/carbon/app/trigger/recalculate.ts b/apps/carbon/app/trigger/recalculate.ts
index 26ec11f6b8..615666f3ab 100644
--- a/apps/carbon/app/trigger/recalculate.ts
+++ b/apps/carbon/app/trigger/recalculate.ts
@@ -1,7 +1,7 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import type { FunctionsResponse } from "@supabase/functions-js";
import { task } from "@trigger.dev/sdk/v3";
import { z } from "zod";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import type { Result } from "~/types";
import {
recalculateJobMakeMethodRequirements,
@@ -20,7 +20,7 @@ export const recalculateTask = task({
run: async (payload: z.infer<typeof recalculateSchema>) => {
console.info(`🔰 Type: ${payload.type}, id: ${payload.id}`);
- const serviceRole = getSupabaseServiceRole();
+ const serviceRole = getCarbonServiceRole();
let result: Result;
let calculateQuantities: FunctionsResponse<{ success: boolean }>;
diff --git a/apps/carbon/app/trigger/send-email-resend.ts b/apps/carbon/app/trigger/send-email-resend.ts
index a753ba7455..fcc07944b8 100644
--- a/apps/carbon/app/trigger/send-email-resend.ts
+++ b/apps/carbon/app/trigger/send-email-resend.ts
@@ -2,10 +2,10 @@ import { task } from "@trigger.dev/sdk/v3";
import { nanoid } from "nanoid";
import { Resend } from "resend";
-import { getSupabaseServiceRole } from "~/lib/supabase";
+import { getCarbonServiceRole } from "@carbon/auth";
import { resendFormValidator } from "~/modules/settings";
-const supabaseClient = getSupabaseServiceRole();
+const serviceRole = getCarbonServiceRole();
export const sendEmailResendTask = task({
id: "send-email-resend",
@@ -20,12 +20,12 @@ export const sendEmailResendTask = task({
companyId: string;
}) => {
const [company, integration] = await Promise.all([
- supabaseClient
+ serviceRole
.from("company")
.select("name")
.eq("id", payload.companyId)
.single(),
- supabaseClient
+ serviceRole
.from("companyIntegration")
.select("active, metadata")
.eq("companyId", payload.companyId)
diff --git a/apps/carbon/app/trigger/update-exchange-rates.ts b/apps/carbon/app/trigger/update-exchange-rates.ts
index 3e548ac495..67c609ccf8 100644
--- a/apps/carbon/app/trigger/update-exchange-rates.ts
+++ b/apps/carbon/app/trigger/update-exchange-rates.ts
@@ -1,11 +1,11 @@
+import { getCarbonServiceRole } from "@carbon/auth";
import { task, wait } from "@trigger.dev/sdk/v3";
import type { ExchangeRatesClient, Rates } from "~/lib/exchange-rates.server";
import { getExchangeRatesClient } from "~/lib/exchange-rates.server";
-import { getSupabaseServiceRole } from "~/lib/supabase";
import type { CurrencyCode } from "~/modules/accounting";
import { exchangeRatesFormValidator } from "~/modules/settings";
-const supabaseClient = getSupabaseServiceRole();
+const serviceRole = getCarbonServiceRole();
export const updateExchangeRates = task({
id: "update-exchange-rates",
@@ -14,7 +14,7 @@ export const updateExchangeRates = task({
let hasRates = false;
let exchangeRatesClient: ExchangeRatesClient | undefined;
- const integrations = await supabaseClient
+ const integrations = await serviceRole
.from("companyIntegration")
.select("active, metadata, companyId")
.eq("id", "exchange-rates-v1");
@@ -50,7 +50,7 @@ export const updateExchangeRates = task({
const updatedAt = new Date().toISOString();
- const { data } = await supabaseClient
+ const { data } = await serviceRole
.from("currency")
.select("*")
.eq("companyId", integration.companyId);
@@ -71,7 +71,7 @@ export const updateExchangeRates = task({
if (updates?.length === 0) continue;
- const { error } = await supabaseClient.from("currency").upsert(updates);
+ const { error } = await serviceRole.from("currency").upsert(updates);
if (error) {
console.error(JSON.stringify(error));
continue;
diff --git a/apps/carbon/app/trigger/update-permissions.ts b/apps/carbon/app/trigger/update-permissions.ts
index 296be56ed2..7fc958b301 100644
--- a/apps/carbon/app/trigger/update-permissions.ts
+++ b/apps/carbon/app/trigger/update-permissions.ts
@@ -1,10 +1,10 @@
import { task } from "@trigger.dev/sdk/v3";
import { z } from "zod";
-import { getSupabaseServiceRole } from "~/lib/supabase";
+import { getCarbonServiceRole } from "@carbon/auth";
import { updatePermissions } from "~/modules/users/users.server";
-const supabaseClient = getSupabaseServiceRole();
+const serviceRole = getCarbonServiceRole();
export const permissionsUpdateSchema = z.object({
id: z.string(),
addOnly: z.boolean(),
@@ -24,10 +24,7 @@ export const updatePermissionsTask = task({
id: "update-permissions",
run: async (payload: z.infer<typeof permissionsUpdateSchema>) => {
console.info(`🔰 Permission Update for ${payload.id}`);
- const { success, message } = await updatePermissions(
- supabaseClient,
- payload
- );
+ const { success, message } = await updatePermissions(serviceRole, payload);
if (success) {
console.info(`✅ Permission Update for ${payload.id}`);
} else {
diff --git a/apps/carbon/app/trigger/user-admin.ts b/apps/carbon/app/trigger/user-admin.ts
index 6e761b8279..b7db0b1b50 100644
--- a/apps/carbon/app/trigger/user-admin.ts
+++ b/apps/carbon/app/trigger/user-admin.ts
@@ -1,11 +1,11 @@
import { task } from "@trigger.dev/sdk/v3";
import { z } from "zod";
-import { getSupabaseServiceRole } from "~/lib/supabase";
+import { getCarbonServiceRole } from "@carbon/auth";
import { deactivateUser, resendInvite } from "~/modules/users/users.server";
import type { Result } from "~/types";
-const supabaseClient = getSupabaseServiceRole();
+const serviceRole = getCarbonServiceRole();
export const userAdminSchema = z.object({
id: z.string(),
type: z.enum(["resend", "deactivate"]),
@@ -21,11 +21,11 @@ export const userAdminTask = task({
switch (payload.type) {
case "resend":
console.log(`📫 Resending invite for ${payload.id}`);
- result = await resendInvite(supabaseClient, payload.id);
+ result = await resendInvite(serviceRole, payload.id);
break;
case "deactivate":
console.log(`🚭 Deactivating ${payload.id}`);
- result = await deactivateUser(supabaseClient, payload.id);
+ result = await deactivateUser(serviceRole, payload.id);
break;
default:
result = {
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 0d53fe7251..04d151d7bc 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -1,5 +1,5 @@
+import { SUPABASE_API_URL } from "@carbon/auth";
import { generatePath } from "@remix-run/react";
-import { SUPABASE_API_URL } from "~/config/env";
const x = "/x"; // from ~/routes/x+ folder
const api = "/api"; // from ~/routes/api+ folder
diff --git a/apps/carbon/package.json b/apps/carbon/package.json
index c611233a62..f6052a8c4f 100644
--- a/apps/carbon/package.json
+++ b/apps/carbon/package.json
@@ -2,6 +2,7 @@
"name": "carbon",
"type": "module",
"dependencies": {
+ "@carbon/auth": "*",
"@carbon/database": "*",
"@carbon/documents": "*",
"@carbon/form": "*",
diff --git a/package-lock.json b/package-lock.json
index 0339d822f9..cd6f91b0df 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -33,6 +33,7 @@
},
"apps/carbon": {
"dependencies": {
+ "@carbon/auth": "*",
"@carbon/database": "*",
"@carbon/documents": "*",
"@carbon/form": "*",