A full-featured CRM built with React, shadcn/ui, and Supabase.
Do not start SupabaseClient by default
fzaninotto61cdfe1da5ad
diff --git a/src/components/atomic-crm/providers/supabase/authProvider.ts b/src/components/atomic-crm/providers/supabase/authProvider.tsindex 1ea62700..722aadc0 100644--- a/src/components/atomic-crm/providers/supabase/authProvider.ts+++ b/src/components/atomic-crm/providers/supabase/authProvider.ts@@ -2,23 +2,24 @@ import type { AuthProvider } from "ra-core";import { supabaseAuthProvider } from "ra-supabase-core";import { canAccess } from "../commons/canAccess";-import { supabase } from "./supabase";+import { getSupabaseClient } from "./supabase";-const baseAuthProvider = supabaseAuthProvider(supabase, {- getIdentity: async () => {- const sale = await getSale();+const getBaseAuthProvider = () =>+ supabaseAuthProvider(getSupabaseClient(), {+ getIdentity: async () => {+ const sale = await getSale();- if (sale == null) {- throw new Error();- }+ if (sale == null) {+ throw new Error();+ }- return {- id: sale.id,- fullName: `${sale.first_name} ${sale.last_name}`,- avatar: sale.avatar?.src,- };- },-});+ return {+ id: sale.id,+ fullName: `${sale.first_name} ${sale.last_name}`,+ avatar: sale.avatar?.src,+ };+ },+ });// To speed up checks, we cache the initialization state// and the current sale in the local storage. They are cleared on logout.@@ -39,7 +40,9 @@ export async function getIsInitialized() {return cachedValue === "true";}- const { data } = await supabase.from("init_state").select("is_initialized");+ const { data } = await getSupabaseClient()+ .from("init_state")+ .select("is_initialized");const isInitialized = data?.at(0)?.is_initialized > 0;if (isInitialized) {@@ -57,14 +60,14 @@ const getSale = async () => {}const { data: dataSession, error: errorSession } =- await supabase.auth.getSession();+ await getSupabaseClient().auth.getSession();// Shouldn't happen after login but just in caseif (dataSession?.session?.user == null || errorSession) {return undefined;}- const { data: dataSale, error: errorSale } = await supabase+ const { data: dataSale, error: errorSale } = await getSupabaseClient().from("sales").select("id, first_name, last_name, avatar, administrator").match({ user_id: dataSession?.session?.user.id })@@ -85,78 +88,85 @@ function clearCache() {storage?.removeItem(CURRENT_SALE_CACHE_KEY);}-export const authProvider: AuthProvider = {- ...baseAuthProvider,- login: async (params) => {- if (params.ssoDomain) {- const { error } = await supabase.auth.signInWithSSO({- domain: params.ssoDomain,- });- if (error) {- throw error;+export const getAuthProvider = (): AuthProvider => {+ const baseAuthProvider = getBaseAuthProvider();+ return {+ ...baseAuthProvider,+ login: async (params) => {+ if (params.ssoDomain) {+ const { error } = await getSupabaseClient().auth.signInWithSSO({+ domain: params.ssoDomain,+ });+ if (error) {+ throw error;+ }+ return;}- return;- }- return baseAuthProvider.login(params);- },- logout: async (params) => {- clearCache();- return baseAuthProvider.logout(params);- },- checkAuth: async (params) => {- // Users are on the set-password page, nothing to do- if (- window.location.pathname === "/set-password" ||- window.location.hash.includes("#/set-password")- ) {- return;- }- // Users are on the forgot-password page, nothing to do- if (- window.location.pathname === "/forgot-password" ||- window.location.hash.includes("#/forgot-password")- ) {- return;- }- // Users are on the sign-up page, nothing to do- if (- window.location.pathname === "/sign-up" ||- window.location.hash.includes("#/sign-up")- ) {- return;- }-- const isInitialized = await getIsInitialized();-- if (!isInitialized) {- await supabase.auth.signOut();- throw {- redirectTo: "/sign-up",- message: false,- };- }-- return baseAuthProvider.checkAuth(params);- },- canAccess: async (params) => {- const isInitialized = await getIsInitialized();- if (!isInitialized) return false;-- // Get the current user- const sale = await getSale();- if (sale == null) return false;-- // Compute access rights from the sale role- const role = sale.administrator ? "admin" : "user";- return canAccess(role, params);- },- getAuthorizationDetails(authorizationId: string) {- return supabase.auth.oauth.getAuthorizationDetails(authorizationId);- },- approveAuthorization(authorizationId: string) {- return supabase.auth.oauth.approveAuthorization(authorizationId);- },- denyAuthorization(authorizationId: string) {- return supabase.auth.oauth.denyAuthorization(authorizationId);- },+ return baseAuthProvider.login(params);+ },+ logout: async (params) => {+ clearCache();+ return baseAuthProvider.logout(params);+ },+ checkAuth: async (params) => {+ // Users are on the set-password page, nothing to do+ if (+ window.location.pathname === "/set-password" ||+ window.location.hash.includes("#/set-password")+ ) {+ return;+ }+ // Users are on the forgot-password page, nothing to do+ if (+ window.location.pathname === "/forgot-password" ||+ window.location.hash.includes("#/forgot-password")+ ) {+ return;+ }+ // Users are on the sign-up page, nothing to do+ if (+ window.location.pathname === "/sign-up" ||+ window.location.hash.includes("#/sign-up")+ ) {+ return;+ }++ const isInitialized = await getIsInitialized();++ if (!isInitialized) {+ await getSupabaseClient().auth.signOut();+ throw {+ redirectTo: "/sign-up",+ message: false,+ };+ }++ return baseAuthProvider.checkAuth(params);+ },+ canAccess: async (params) => {+ const isInitialized = await getIsInitialized();+ if (!isInitialized) return false;++ // Get the current user+ const sale = await getSale();+ if (sale == null) return false;++ // Compute access rights from the sale role+ const role = sale.administrator ? "admin" : "user";+ return canAccess(role, params);+ },+ getAuthorizationDetails(authorizationId: string) {+ return getSupabaseClient().auth.oauth.getAuthorizationDetails(+ authorizationId,+ );+ },+ approveAuthorization(authorizationId: string) {+ return getSupabaseClient().auth.oauth.approveAuthorization(+ authorizationId,+ );+ },+ denyAuthorization(authorizationId: string) {+ return getSupabaseClient().auth.oauth.denyAuthorization(authorizationId);+ },+ };};diff --git a/src/components/atomic-crm/providers/supabase/dataProvider.ts b/src/components/atomic-crm/providers/supabase/dataProvider.tsindex 0fc6ba7d..26b4e749 100644--- a/src/components/atomic-crm/providers/supabase/dataProvider.ts+++ b/src/components/atomic-crm/providers/supabase/dataProvider.ts@@ -18,23 +18,15 @@ import type {import type { ConfigurationContextValue } from "../../root/ConfigurationContext";import { ATTACHMENTS_BUCKET } from "../commons/attachments";import { getIsInitialized } from "./authProvider";-import { supabase } from "./supabase";--if (import.meta.env.VITE_SUPABASE_URL === undefined) {- throw new Error("Please set the VITE_SUPABASE_URL environment variable");-}-if (import.meta.env.VITE_SB_PUBLISHABLE_KEY === undefined) {- throw new Error(- "Please set the VITE_SB_PUBLISHABLE_KEY environment variable",- );-}--const baseDataProvider = supabaseDataProvider({- instanceUrl: import.meta.env.VITE_SUPABASE_URL,- apiKey: import.meta.env.VITE_SB_PUBLISHABLE_KEY,- supabaseClient: supabase,- sortOrder: "asc,desc.nullslast" as any,-});+import { getSupabaseClient } from "./supabase";++const getBaseDataProvider = () =>+ supabaseDataProvider({+ instanceUrl: import.meta.env.VITE_SUPABASE_URL,+ apiKey: import.meta.env.VITE_SB_PUBLISHABLE_KEY,+ supabaseClient: getSupabaseClient(),+ sortOrder: "asc,desc.nullslast" as any,+ });const processCompanyLogo = async (params: any) => {const logo = params.data.logo;@@ -52,198 +44,209 @@ const processCompanyLogo = async (params: any) => {};};-const dataProviderWithCustomMethods = {- ...baseDataProvider,- async getList(resource: string, params: GetListParams) {- if (resource === "companies") {- return baseDataProvider.getList("companies_summary", params);- }- if (resource === "contacts") {- return baseDataProvider.getList("contacts_summary", params);- }- if (resource === "activity_log") {- const { data, total } = await baseDataProvider.getList(- "activity_log",- params,- );- // Rename snake_case view columns to camelCase to match Activity type- return {- data: data.map((row: any) => ({- ...row,- contactNote: row.contact_note ?? undefined,- dealNote: row.deal_note ?? undefined,- contact_note: undefined,- deal_note: undefined,- })),- total,- };- }+const getDataProviderWithCustomMethods = () => {+ const baseDataProvider = getBaseDataProvider();- return baseDataProvider.getList(resource, params);- },- async getOne(resource: string, params: any) {- if (resource === "companies") {- return baseDataProvider.getOne("companies_summary", params);- }- if (resource === "contacts") {- return baseDataProvider.getOne("contacts_summary", params);- }+ return {+ ...baseDataProvider,+ async getList(resource: string, params: GetListParams) {+ if (resource === "companies") {+ return baseDataProvider.getList("companies_summary", params);+ }+ if (resource === "contacts") {+ return baseDataProvider.getList("contacts_summary", params);+ }+ if (resource === "activity_log") {+ const { data, total } = await baseDataProvider.getList(+ "activity_log",+ params,+ );+ // Rename snake_case view columns to camelCase to match Activity type+ return {+ data: data.map((row: any) => ({+ ...row,+ contactNote: row.contact_note ?? undefined,+ dealNote: row.deal_note ?? undefined,+ contact_note: undefined,+ deal_note: undefined,+ })),+ total,+ };+ }- return baseDataProvider.getOne(resource, params);- },+ return baseDataProvider.getList(resource, params);+ },+ async getOne(resource: string, params: any) {+ if (resource === "companies") {+ return baseDataProvider.getOne("companies_summary", params);+ }+ if (resource === "contacts") {+ return baseDataProvider.getOne("contacts_summary", params);+ }- async signUp({ email, password, first_name, last_name }: SignUpData) {- const response = await supabase.auth.signUp({- email,- password,- options: {- data: {- first_name,- last_name,+ return baseDataProvider.getOne(resource, params);+ },++ async signUp({ email, password, first_name, last_name }: SignUpData) {+ const response = await getSupabaseClient().auth.signUp({+ email,+ password,+ options: {+ data: {+ first_name,+ last_name,+ },},- },- });+ });- if (!response.data?.user || response.error) {- console.error("signUp.error", response.error);- throw new Error(response?.error?.message || "Failed to create account");- }+ if (!response.data?.user || response.error) {+ console.error("signUp.error", response.error);+ throw new Error(response?.error?.message || "Failed to create account");+ }- // Update the is initialized cache- getIsInitialized._is_initialized_cache = true;+ // Update the is initialized cache+ getIsInitialized._is_initialized_cache = true;- return {- id: response.data.user.id,- email,- password,- };- },- async salesCreate(body: SalesFormData) {- const { data, error } = await supabase.functions.invoke<{ data: Sale }>(- "users",- {+ return {+ id: response.data.user.id,+ email,+ password,+ };+ },+ async salesCreate(body: SalesFormData) {+ const { data, error } = await getSupabaseClient().functions.invoke<{+ data: Sale;+ }>("users", {method: "POST",body,- },- );+ });- if (!data || error) {- console.error("salesCreate.error", error);- const errorDetails = await (async () => {- try {- return (await error?.context?.json()) ?? {};- } catch {- return {};- }- })();- throw new Error(errorDetails?.message || "Failed to create the user");- }+ if (!data || error) {+ console.error("salesCreate.error", error);+ const errorDetails = await (async () => {+ try {+ return (await error?.context?.json()) ?? {};+ } catch {+ return {};+ }+ })();+ throw new Error(errorDetails?.message || "Failed to create the user");+ }- return data.data;- },- async salesUpdate(- id: Identifier,- data: Partial<Omit<SalesFormData, "password">>,- ) {- const { email, first_name, last_name, administrator, avatar, disabled } =- data;-- const { data: updatedData, error } = await supabase.functions.invoke<{- data: Sale;- }>("users", {- method: "PATCH",- body: {- sales_id: id,- email,- first_name,- last_name,- administrator,- disabled,- avatar,- },- });-- if (!updatedData || error) {- console.error("salesCreate.error", error);- throw new Error("Failed to update account manager");- }+ return data.data;+ },+ async salesUpdate(+ id: Identifier,+ data: Partial<Omit<SalesFormData, "password">>,+ ) {+ const { email, first_name, last_name, administrator, avatar, disabled } =+ data;++ const { data: updatedData, error } =+ await getSupabaseClient().functions.invoke<{+ data: Sale;+ }>("users", {+ method: "PATCH",+ body: {+ sales_id: id,+ email,+ first_name,+ last_name,+ administrator,+ disabled,+ avatar,+ },+ });++ if (!updatedData || error) {+ console.error("salesCreate.error", error);+ throw new Error("Failed to update account manager");+ }- return updatedData.data;- },- async updatePassword(id: Identifier) {- const { data: passwordUpdated, error } =- await supabase.functions.invoke<boolean>("update_password", {- method: "PATCH",- body: {- sales_id: id,- },+ return updatedData.data;+ },+ async updatePassword(id: Identifier) {+ const { data: passwordUpdated, error } =+ await getSupabaseClient().functions.invoke<boolean>("update_password", {+ method: "PATCH",+ body: {+ sales_id: id,+ },+ });++ if (!passwordUpdated || error) {+ console.error("update_password.error", error);+ throw new Error("Failed to update password");+ }++ return passwordUpdated;+ },+ async unarchiveDeal(deal: Deal) {+ // get all deals where stage is the same as the deal to unarchive+ const { data: deals } = await baseDataProvider.getList<Deal>("deals", {+ filter: { stage: deal.stage },+ pagination: { page: 1, perPage: 1000 },+ sort: { field: "index", order: "ASC" },});- if (!passwordUpdated || error) {- console.error("update_password.error", error);- throw new Error("Failed to update password");- }+ // set index for each deal starting from 1, if the deal to unarchive is found, set its index to the last one+ const updatedDeals = deals.map((d, index) => ({+ ...d,+ index: d.id === deal.id ? 0 : index + 1,+ archived_at: d.id === deal.id ? null : d.archived_at,+ }));++ return await Promise.all(+ updatedDeals.map((updatedDeal) =>+ baseDataProvider.update("deals", {+ id: updatedDeal.id,+ data: updatedDeal,+ previousData: deals.find((d) => d.id === updatedDeal.id),+ }),+ ),+ );+ },+ async isInitialized() {+ return getIsInitialized();+ },+ async mergeContacts(sourceId: Identifier, targetId: Identifier) {+ const { data, error } = await getSupabaseClient().functions.invoke(+ "merge_contacts",+ {+ method: "POST",+ body: { loserId: sourceId, winnerId: targetId },+ },+ );- return passwordUpdated;- },- async unarchiveDeal(deal: Deal) {- // get all deals where stage is the same as the deal to unarchive- const { data: deals } = await baseDataProvider.getList<Deal>("deals", {- filter: { stage: deal.stage },- pagination: { page: 1, perPage: 1000 },- sort: { field: "index", order: "ASC" },- });-- // set index for each deal starting from 1, if the deal to unarchive is found, set its index to the last one- const updatedDeals = deals.map((d, index) => ({- ...d,- index: d.id === deal.id ? 0 : index + 1,- archived_at: d.id === deal.id ? null : d.archived_at,- }));-- return await Promise.all(- updatedDeals.map((updatedDeal) =>- baseDataProvider.update("deals", {- id: updatedDeal.id,- data: updatedDeal,- previousData: deals.find((d) => d.id === updatedDeal.id),- }),- ),- );- },- async isInitialized() {- return getIsInitialized();- },- async mergeContacts(sourceId: Identifier, targetId: Identifier) {- const { data, error } = await supabase.functions.invoke("merge_contacts", {- method: "POST",- body: { loserId: sourceId, winnerId: targetId },- });-- if (error) {- console.error("merge_contacts.error", error);- throw new Error("Failed to merge contacts");- }+ if (error) {+ console.error("merge_contacts.error", error);+ throw new Error("Failed to merge contacts");+ }- return data;- },- async getConfiguration(): Promise<ConfigurationContextValue> {- const { data } = await baseDataProvider.getOne("configuration", { id: 1 });- return (data?.config as ConfigurationContextValue) ?? {};- },- async updateConfiguration(- config: ConfigurationContextValue,- ): Promise<ConfigurationContextValue> {- const { data } = await baseDataProvider.update("configuration", {- id: 1,- data: { config },- previousData: { id: 1 },- });- return data.config as ConfigurationContextValue;- },-} satisfies DataProvider;+ return data;+ },+ async getConfiguration(): Promise<ConfigurationContextValue> {+ const { data } = await baseDataProvider.getOne("configuration", {+ id: 1,+ });+ return (data?.config as ConfigurationContextValue) ?? {};+ },+ async updateConfiguration(+ config: ConfigurationContextValue,+ ): Promise<ConfigurationContextValue> {+ const { data } = await baseDataProvider.update("configuration", {+ id: 1,+ data: { config },+ previousData: { id: 1 },+ });+ return data.config as ConfigurationContextValue;+ },+ } satisfies DataProvider;+};-export type CrmDataProvider = typeof dataProviderWithCustomMethods;+export type CrmDataProvider = ReturnType<+ typeof getDataProviderWithCustomMethods+>;const processConfigLogo = async (logo: any): Promise<string> => {if (typeof logo === "string") return logo;@@ -352,10 +355,20 @@ const lifeCycleCallbacks: ResourceCallbacks[] = [},];-export const dataProvider = withLifecycleCallbacks(- dataProviderWithCustomMethods,- lifeCycleCallbacks,-) as CrmDataProvider;+export const getDataProvider = () => {+ if (import.meta.env.VITE_SUPABASE_URL === undefined) {+ throw new Error("Please set the VITE_SUPABASE_URL environment variable");+ }+ if (import.meta.env.VITE_SB_PUBLISHABLE_KEY === undefined) {+ throw new Error(+ "Please set the VITE_SB_PUBLISHABLE_KEY environment variable",+ );+ }+ return withLifecycleCallbacks(+ getDataProviderWithCustomMethods(),+ lifeCycleCallbacks,+ ) as CrmDataProvider;+};const applyFullTextSearch = (columns: string[]) => (params: GetListParams) => {if (!params.filter?.q) {diff --git a/src/components/atomic-crm/providers/supabase/index.ts b/src/components/atomic-crm/providers/supabase/index.tsindex 75a08a19..4e938159 100644--- a/src/components/atomic-crm/providers/supabase/index.ts+++ b/src/components/atomic-crm/providers/supabase/index.ts@@ -1,2 +1,2 @@-export { authProvider } from "./authProvider";-export { dataProvider } from "./dataProvider";+export { getAuthProvider } from "./authProvider";+export { getDataProvider } from "./dataProvider";diff --git a/src/components/atomic-crm/providers/supabase/supabase.ts b/src/components/atomic-crm/providers/supabase/supabase.tsindex 26146103..e5eb7928 100644--- a/src/components/atomic-crm/providers/supabase/supabase.ts+++ b/src/components/atomic-crm/providers/supabase/supabase.ts@@ -1,6 +1,14 @@+import type { SupabaseClient } from "@supabase/supabase-js";import { createClient } from "@supabase/supabase-js";-export const supabase = createClient(- import.meta.env.VITE_SUPABASE_URL,- import.meta.env.VITE_SB_PUBLISHABLE_KEY,-);+let supabaseClient: SupabaseClient | null = null;++export const getSupabaseClient = () => {+ if (!supabaseClient) {+ supabaseClient = createClient(+ import.meta.env.VITE_SUPABASE_URL,+ import.meta.env.VITE_SB_PUBLISHABLE_KEY,+ );+ }+ return supabaseClient;+};diff --git a/src/components/atomic-crm/root/CRM.tsx b/src/components/atomic-crm/root/CRM.tsxindex b6f8a53a..218a21bb 100644--- a/src/components/atomic-crm/root/CRM.tsx+++ b/src/components/atomic-crm/root/CRM.tsx@@ -1,10 +1,10 @@-import {- type CoreAdminProps,- CustomRoutes,- localStorageStore,- Resource,- type AuthProvider,+import type {+ CoreAdminProps,+ AuthProvider,+ DashboardComponent,+ LayoutComponent,} from "ra-core";+import { CustomRoutes, localStorageStore, Resource } from "ra-core";import { useEffect, useMemo } from "react";import { Route } from "react-router";import { QueryClient } from "@tanstack/react-query";@@ -26,8 +26,8 @@ import { SignupPage } from "../login/SignupPage";import { ConfirmationRequired } from "../login/ConfirmationRequired";import { ImportPage } from "../misc/ImportPage";import {- authProvider as defaultAuthProvider,- dataProvider as defaultDataProvider,+ getAuthProvider as defaultAuthProviderBuilder,+ getDataProvider as defaultDataProviderBuilder,} from "../providers/supabase";import sales from "../sales";import { SettingsPageMobile } from "../settings/SettingsPageMobile";@@ -66,6 +66,8 @@ export type CRMProps = {authProvider?: AuthProvider;disableTelemetry?: boolean;store?: CoreAdminProps["store"];+ dashboard?: DashboardComponent;+ layout?: LayoutComponent;} & Partial<ConfigurationContextValue>;/**@@ -119,8 +121,8 @@ export const CRM = ({noteStatuses = defaultNoteStatuses,taskTypes = defaultTaskTypes,title = defaultTitle,- dataProvider = defaultDataProvider,- authProvider = defaultAuthProvider,+ dataProvider = defaultDataProviderBuilder(),+ authProvider = defaultAuthProviderBuilder(),store = defaultStore,googleWorkplaceDomain = import.meta.env.VITE_GOOGLE_WORKPLACE_DOMAIN,disableEmailPasswordAuthentication = import.meta.env@@ -225,9 +227,18 @@ export const CRM = ({);};-const DesktopAdmin = (props: CoreAdminProps) => {+const DesktopAdmin = (+ props: CoreAdminProps & {+ dashboard?: DashboardComponent;+ layout?: LayoutComponent;+ },+) => {return (- <Admin layout={Layout} dashboard={Dashboard} {...props}>+ <Admin+ layout={props.layout ?? Layout}+ dashboard={props.dashboard ?? Dashboard}+ {...props}+ ><CustomRoutes noLayout><Route path={SignupPage.path} element={<SignupPage />} /><Route@@ -259,7 +270,12 @@ const DesktopAdmin = (props: CoreAdminProps) => {);};-const MobileAdmin = (props: CoreAdminProps) => {+const MobileAdmin = (+ props: CoreAdminProps & {+ dashboard?: DashboardComponent;+ layout?: LayoutComponent;+ },+) => {const queryClient = new QueryClient({defaultOptions: {queries: {@@ -282,8 +298,8 @@ const MobileAdmin = (props: CoreAdminProps) => {><AdminqueryClient={queryClient}- layout={MobileLayout}- dashboard={MobileDashboard}+ layout={props.layout ?? MobileLayout}+ dashboard={props.dashboard ?? MobileDashboard}{...props}><CustomRoutes noLayout>