Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

Add Settings page

François Zaninotto4b9c52ada302
diff --git a/src/components/atomic-crm/layout/Header.tsx b/src/components/atomic-crm/layout/Header.tsx
index ae68c82b..8f5db3f2 100644
--- a/src/components/atomic-crm/layout/Header.tsx
+++ b/src/components/atomic-crm/layout/Header.tsx
@@ -1,4 +1,4 @@
-import { Import, Settings, User } from "lucide-react";
+import { Cog, Import, Settings, User } from "lucide-react";
import { CanAccess, useUserMenu } from "ra-core";
import { Link, matchPath, useLocation } from "react-router";
import { RefreshButton } from "@/components/admin/refresh-button";
@@ -80,6 +80,9 @@ const Header = () => {
<CanAccess resource="sales" action="list">
<UsersMenu />
</CanAccess>
+ <CanAccess resource="configuration" action="edit">
+ <AppSettingsMenu />
+ </CanAccess>
<ImportFromJsonMenuItem />
</UserMenu>
</div>
@@ -141,6 +144,20 @@ const ConfigurationMenu = () => {
);
};
+const AppSettingsMenu = () => {
+ const userMenuContext = useUserMenu();
+ if (!userMenuContext) {
+ throw new Error("<AppSettingsMenu> must be used inside <UserMenu>");
+ }
+ return (
+ <DropdownMenuItem asChild onClick={userMenuContext.onClose}>
+ <Link to="/app-settings" className="flex items-center gap-2">
+ <Cog /> App Settings
+ </Link>
+ </DropdownMenuItem>
+ );
+};
+
const ImportFromJsonMenuItem = () => {
const userMenuContext = useUserMenu();
if (!userMenuContext) {
diff --git a/src/components/atomic-crm/layout/Layout.tsx b/src/components/atomic-crm/layout/Layout.tsx
index ef6ad33f..41981658 100644
--- a/src/components/atomic-crm/layout/Layout.tsx
+++ b/src/components/atomic-crm/layout/Layout.tsx
@@ -4,18 +4,22 @@ import { Notification } from "@/components/admin/notification";
import { Error } from "@/components/admin/error";
import { Skeleton } from "@/components/ui/skeleton";
+import { useConfigurationLoader } from "../root/useConfigurationLoader";
import Header from "./Header";
-export const Layout = ({ children }: { children: ReactNode }) => (
- <>
- <Header />
- <main className="max-w-screen-xl mx-auto pt-4 px-4" id="main-content">
- <ErrorBoundary FallbackComponent={Error}>
- <Suspense fallback={<Skeleton className="h-12 w-12 rounded-full" />}>
- {children}
- </Suspense>
- </ErrorBoundary>
- </main>
- <Notification />
- </>
-);
+export const Layout = ({ children }: { children: ReactNode }) => {
+ useConfigurationLoader();
+ return (
+ <>
+ <Header />
+ <main className="max-w-screen-xl mx-auto pt-4 px-4" id="main-content">
+ <ErrorBoundary FallbackComponent={Error}>
+ <Suspense fallback={<Skeleton className="h-12 w-12 rounded-full" />}>
+ {children}
+ </Suspense>
+ </ErrorBoundary>
+ </main>
+ <Notification />
+ </>
+ );
+};
diff --git a/src/components/atomic-crm/layout/MobileLayout.tsx b/src/components/atomic-crm/layout/MobileLayout.tsx
index 5512d297..334ae0e8 100644
--- a/src/components/atomic-crm/layout/MobileLayout.tsx
+++ b/src/components/atomic-crm/layout/MobileLayout.tsx
@@ -4,16 +4,20 @@ import { Skeleton } from "@/components/ui/skeleton";
import { Suspense, type ReactNode } from "react";
import { ErrorBoundary } from "react-error-boundary";
+import { useConfigurationLoader } from "../root/useConfigurationLoader";
import { MobileNavigation } from "./MobileNavigation";
-export const MobileLayout = ({ children }: { children: ReactNode }) => (
- <>
- <ErrorBoundary FallbackComponent={Error}>
- <Suspense fallback={<Skeleton className="h-12 w-12 rounded-full" />}>
- {children}
- </Suspense>
- </ErrorBoundary>
- <MobileNavigation />
- <Notification mobileOffset={{ bottom: "72px" }} />
- </>
-);
+export const MobileLayout = ({ children }: { children: ReactNode }) => {
+ useConfigurationLoader();
+ return (
+ <>
+ <ErrorBoundary FallbackComponent={Error}>
+ <Suspense fallback={<Skeleton className="h-12 w-12 rounded-full" />}>
+ {children}
+ </Suspense>
+ </ErrorBoundary>
+ <MobileNavigation />
+ <Notification mobileOffset={{ bottom: "72px" }} />
+ </>
+ );
+};
diff --git a/src/components/atomic-crm/providers/commons/canAccess.ts b/src/components/atomic-crm/providers/commons/canAccess.ts
index 152e1fe2..baeaf1a6 100644
--- a/src/components/atomic-crm/providers/commons/canAccess.ts
+++ b/src/components/atomic-crm/providers/commons/canAccess.ts
@@ -22,5 +22,10 @@ export const canAccess = <
return false;
}
+ // Non admins can't access the configuration resource
+ if (params.resource === "configuration") {
+ return false;
+ }
+
return true;
};
diff --git a/src/components/atomic-crm/providers/fakerest/dataGenerator/index.ts b/src/components/atomic-crm/providers/fakerest/dataGenerator/index.ts
index b1c23719..373d36e0 100644
--- a/src/components/atomic-crm/providers/fakerest/dataGenerator/index.ts
+++ b/src/components/atomic-crm/providers/fakerest/dataGenerator/index.ts
@@ -19,6 +19,7 @@ export default (): Db => {
db.deals = generateDeals(db);
db.deal_notes = generateDealNotes(db);
db.tasks = generateTasks(db);
+ db.configuration = [{ id: 1, config: {} }];
finalize(db);
return db;
diff --git a/src/components/atomic-crm/providers/fakerest/dataGenerator/types.ts b/src/components/atomic-crm/providers/fakerest/dataGenerator/types.ts
index c9203fa6..bfa88617 100644
--- a/src/components/atomic-crm/providers/fakerest/dataGenerator/types.ts
+++ b/src/components/atomic-crm/providers/fakerest/dataGenerator/types.ts
@@ -8,6 +8,7 @@ import type {
Tag,
Task,
} from "../../../types";
+import type { StoredConfiguration } from "../../../root/storedConfiguration";
export interface Db {
companies: Required<Company>[];
@@ -18,4 +19,5 @@ export interface Db {
sales: Sale[];
tags: Tag[];
tasks: Task[];
+ configuration: Array<{ id: number; config: StoredConfiguration }>;
}
diff --git a/src/components/atomic-crm/providers/fakerest/dataProvider.ts b/src/components/atomic-crm/providers/fakerest/dataProvider.ts
index 7f103e4b..7481208e 100644
--- a/src/components/atomic-crm/providers/fakerest/dataProvider.ts
+++ b/src/components/atomic-crm/providers/fakerest/dataProvider.ts
@@ -17,6 +17,7 @@ import type {
SignUpData,
Task,
} from "../../types";
+import type { StoredConfiguration } from "../../root/storedConfiguration";
import { getActivityLog } from "../commons/activity";
import { getCompanyAvatar } from "../commons/getCompanyAvatar";
import { getContactAvatar } from "../commons/getContactAvatar";
@@ -224,6 +225,23 @@ const dataProviderWithCustomMethod: CrmDataProvider = {
mergeContacts: async (sourceId: Identifier, targetId: Identifier) => {
return mergeContacts(sourceId, targetId, baseDataProvider);
},
+ getConfiguration: async (): Promise<StoredConfiguration> => {
+ const { data } = await baseDataProvider.getOne("configuration", { id: 1 });
+ return (data?.config as StoredConfiguration) ?? {};
+ },
+ updateConfiguration: async (
+ config: StoredConfiguration,
+ ): Promise<StoredConfiguration> => {
+ const { data: prev } = await baseDataProvider.getOne("configuration", {
+ id: 1,
+ });
+ await baseDataProvider.update("configuration", {
+ id: 1,
+ data: { config },
+ previousData: prev,
+ });
+ return config;
+ },
};
async function updateCompany(
diff --git a/src/components/atomic-crm/providers/supabase/dataProvider.ts b/src/components/atomic-crm/providers/supabase/dataProvider.ts
index 98fae965..1f6e5f63 100644
--- a/src/components/atomic-crm/providers/supabase/dataProvider.ts
+++ b/src/components/atomic-crm/providers/supabase/dataProvider.ts
@@ -15,6 +15,7 @@ import type {
SalesFormData,
SignUpData,
} from "../../types";
+import type { StoredConfiguration } from "../../root/storedConfiguration";
import { getActivityLog } from "../commons/activity";
import { getIsInitialized } from "./authProvider";
import { supabase } from "./supabase";
@@ -212,6 +213,20 @@ const dataProviderWithCustomMethods = {
return data;
},
+ async getConfiguration(): Promise<StoredConfiguration> {
+ const { data } = await baseDataProvider.getOne("configuration", { id: 1 });
+ return (data?.config as StoredConfiguration) ?? {};
+ },
+ async updateConfiguration(
+ config: StoredConfiguration,
+ ): Promise<StoredConfiguration> {
+ const { data } = await baseDataProvider.update("configuration", {
+ id: 1,
+ data: { config },
+ previousData: { id: 1 },
+ });
+ return data.config as StoredConfiguration;
+ },
} satisfies DataProvider;
export type CrmDataProvider = typeof dataProviderWithCustomMethods;
@@ -306,7 +321,7 @@ const lifeCycleCallbacks: ResourceCallbacks[] = [
export const dataProvider = withLifecycleCallbacks(
dataProviderWithCustomMethods,
lifeCycleCallbacks,
-);
+) as CrmDataProvider;
const applyFullTextSearch = (columns: string[]) => (params: GetListParams) => {
if (!params.filter?.q) {
diff --git a/src/components/atomic-crm/root/CRM.tsx b/src/components/atomic-crm/root/CRM.tsx
index 4985e036..101c21c8 100644
--- a/src/components/atomic-crm/root/CRM.tsx
+++ b/src/components/atomic-crm/root/CRM.tsx
@@ -4,9 +4,8 @@ import {
localStorageStore,
Resource,
type AuthProvider,
- type DataProvider,
} from "ra-core";
-import { useEffect } from "react";
+import { useEffect, useMemo } from "react";
import { Route } from "react-router";
import { QueryClient } from "@tanstack/react-query";
import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client";
@@ -31,9 +30,12 @@ import {
dataProvider as defaultDataProvider,
} from "../providers/supabase";
import sales from "../sales";
+import { AppConfigPage } from "../settings/AppConfigPage";
import { SettingsPage } from "../settings/SettingsPage";
import type { ConfigurationContextValue } from "./ConfigurationContext";
import { ConfigurationProvider } from "./ConfigurationContext";
+import type { CrmDataProvider } from "../providers/types";
+import { CONFIGURATION_STORE_KEY } from "./storedConfiguration";
import {
defaultCompanySectors,
defaultContactGender,
@@ -55,10 +57,13 @@ import { ContactShow } from "../contacts/ContactShow.tsx";
import { CompanyShow } from "../companies/CompanyShow.tsx";
import { NoteShowPage } from "../notes/NoteShowPage.tsx";
+const defaultStore = localStorageStore(undefined, "CRM");
+
export type CRMProps = {
- dataProvider?: DataProvider;
+ dataProvider?: CrmDataProvider;
authProvider?: AuthProvider;
disableTelemetry?: boolean;
+ store?: CoreAdminProps["store"];
} & Partial<ConfigurationContextValue>;
/**
@@ -114,6 +119,7 @@ export const CRM = ({
title = defaultTitle,
dataProvider = defaultDataProvider,
authProvider = defaultAuthProvider,
+ store = defaultStore,
googleWorkplaceDomain = import.meta.env.VITE_GOOGLE_WORKPLACE_DOMAIN,
disableEmailPasswordAuthentication = import.meta.env
.VITE_DISABLE_EMAIL_PASSWORD_AUTHENTICATION === "true",
@@ -136,10 +142,38 @@ export const CRM = ({
const isMobile = useIsMobile();
+ // on login, pre-fetch the configuration to avoid a flickering
+ // when accessing the app for the first time
+ const wrappedAuthProvider = useMemo<AuthProvider>(
+ () => ({
+ ...authProvider,
+ login: async (params: any) => {
+ const result = await authProvider.login(params);
+ try {
+ const config = await dataProvider.getConfiguration();
+ store.setItem(CONFIGURATION_STORE_KEY, config);
+ } catch {
+ // Non-critical: config will load via useConfigurationLoader
+ }
+ return result;
+ },
+ logout: async (params: any) => {
+ try {
+ store.removeItem(CONFIGURATION_STORE_KEY);
+ } catch {
+ // Ignore
+ }
+ return authProvider.logout(params);
+ },
+ }),
+ [authProvider, dataProvider, store],
+ );
+
const ResponsiveAdmin = isMobile ? MobileAdmin : DesktopAdmin;
return (
<ConfigurationProvider
+ store={store}
contactGender={contactGender}
companySectors={companySectors}
dealCategories={dealCategories}
@@ -155,9 +189,9 @@ export const CRM = ({
>
<ResponsiveAdmin
dataProvider={dataProvider}
- authProvider={authProvider}
+ authProvider={wrappedAuthProvider}
i18nProvider={i18nProvider}
- store={localStorageStore(undefined, "CRM")}
+ store={store}
loginPage={StartPage}
requireAuth
disableTelemetry
@@ -186,6 +220,7 @@ const DesktopAdmin = (props: CoreAdminProps) => {
<CustomRoutes>
<Route path={SettingsPage.path} element={<SettingsPage />} />
+ <Route path={AppConfigPage.path} element={<AppConfigPage />} />
<Route path={ImportPage.path} element={<ImportPage />} />
</CustomRoutes>
<Resource name="deals" {...deals} />
diff --git a/src/components/atomic-crm/root/ConfigurationContext.tsx b/src/components/atomic-crm/root/ConfigurationContext.tsx
index e2532291..083f6fd3 100644
--- a/src/components/atomic-crm/root/ConfigurationContext.tsx
+++ b/src/components/atomic-crm/root/ConfigurationContext.tsx
@@ -1,4 +1,13 @@
-import { createContext, useContext, type ReactNode } from "react";
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+ type ReactNode,
+} from "react";
+import type { Store } from "ra-core";
import type { ContactGender, DealStage, NoteStatus } from "../types";
import {
@@ -13,6 +22,11 @@ import {
defaultTaskTypes,
defaultTitle,
} from "./defaultConfiguration";
+import {
+ CONFIGURATION_STORE_KEY,
+ mergeConfiguration,
+ type StoredConfiguration,
+} from "./storedConfiguration";
// Define types for the context value
export interface ConfigurationContextValue {
@@ -32,6 +46,7 @@ export interface ConfigurationContextValue {
export interface ConfigurationProviderProps extends ConfigurationContextValue {
children: ReactNode;
+ store: Store;
}
// Create context with default value
@@ -50,40 +65,55 @@ export const ConfigurationContext = createContext<ConfigurationContextValue>({
disableEmailPasswordAuthentication: false,
});
+const ConfigurationUpdaterContext = createContext<
+ (config: StoredConfiguration) => void
+>(() => {});
+
export const ConfigurationProvider = ({
children,
- companySectors,
- dealCategories,
- dealPipelineStatuses,
- dealStages,
- darkModeLogo,
- lightModeLogo,
- noteStatuses,
- taskTypes,
- title,
- contactGender,
- googleWorkplaceDomain,
- disableEmailPasswordAuthentication,
-}: ConfigurationProviderProps) => (
- <ConfigurationContext.Provider
- value={{
- companySectors,
- dealCategories,
- dealPipelineStatuses,
- dealStages,
- darkModeLogo,
- lightModeLogo,
- noteStatuses,
- title,
- taskTypes,
- contactGender,
- googleWorkplaceDomain,
- disableEmailPasswordAuthentication,
- }}
- >
- {children}
- </ConfigurationContext.Provider>
-);
+ store,
+ ...codeDefaults
+}: ConfigurationProviderProps) => {
+ const [localConfig, setLocalConfig] = useState<StoredConfiguration | null>(
+ () => store.getItem<StoredConfiguration>(CONFIGURATION_STORE_KEY) ?? null,
+ );
+
+ // Subscribe to external store changes (e.g. config written during login)
+ useEffect(() => {
+ const unsubscribe = store.subscribe(
+ CONFIGURATION_STORE_KEY,
+ (value: StoredConfiguration) => {
+ setLocalConfig(value);
+ },
+ );
+ return unsubscribe;
+ }, [store]);
+
+ const value = useMemo(
+ () => mergeConfiguration(codeDefaults, localConfig),
+ [codeDefaults, localConfig],
+ );
+
+ const updateLocalConfig = useCallback(
+ (config: StoredConfiguration) => {
+ setLocalConfig(config);
+ store.setItem(CONFIGURATION_STORE_KEY, config);
+ },
+ [store],
+ );
+
+ return (
+ <ConfigurationUpdaterContext.Provider value={updateLocalConfig}>
+ <ConfigurationContext.Provider value={value}>
+ {children}
+ </ConfigurationContext.Provider>
+ </ConfigurationUpdaterContext.Provider>
+ );
+};
// eslint-disable-next-line react-refresh/only-export-components
export const useConfigurationContext = () => useContext(ConfigurationContext);
+
+// eslint-disable-next-line react-refresh/only-export-components
+export const useConfigurationUpdater = () =>
+ useContext(ConfigurationUpdaterContext);
diff --git a/src/components/atomic-crm/root/iconRegistry.ts b/src/components/atomic-crm/root/iconRegistry.ts
new file mode 100644
index 00000000..0a708c06
--- /dev/null
+++ b/src/components/atomic-crm/root/iconRegistry.ts
@@ -0,0 +1,13 @@
+import type { ComponentType } from "react";
+import { Mars, Venus, NonBinary, User, CircleOff } from "lucide-react";
+
+export const genderIconRegistry: Record<
+ string,
+ ComponentType<{ className?: string }>
+> = {
+ Mars,
+ Venus,
+ NonBinary,
+ User,
+ CircleOff,
+};
diff --git a/src/components/atomic-crm/root/storedConfiguration.ts b/src/components/atomic-crm/root/storedConfiguration.ts
new file mode 100644
index 00000000..2db31683
--- /dev/null
+++ b/src/components/atomic-crm/root/storedConfiguration.ts
@@ -0,0 +1,74 @@
+import type { ContactGender, DealStage, NoteStatus } from "../types";
+import type { ConfigurationContextValue } from "./ConfigurationContext";
+import { genderIconRegistry } from "./iconRegistry";
+
+export const CONFIGURATION_STORE_KEY = "app.configuration";
+
+export interface StoredContactGender {
+ value: string;
+ label: string;
+ icon: string;
+}
+
+export interface StoredConfiguration {
+ companySectors?: string[];
+ dealCategories?: string[];
+ dealPipelineStatuses?: string[];
+ dealStages?: DealStage[];
+ noteStatuses?: NoteStatus[];
+ taskTypes?: string[];
+ title?: string;
+ darkModeLogo?: string;
+ lightModeLogo?: string;
+ contactGender?: StoredContactGender[];
+}
+
+export const hydrateContactGender = (
+ stored: StoredContactGender[],
+): ContactGender[] =>
+ stored.map((g) => ({
+ value: g.value,
+ label: g.label,
+ icon: genderIconRegistry[g.icon] ?? genderIconRegistry.User,
+ }));
+
+export const dehydrateContactGender = (
+ genders: ContactGender[],
+): StoredContactGender[] =>
+ genders.map((g) => ({
+ value: g.value,
+ label: g.label,
+ icon:
+ Object.entries(genderIconRegistry).find(
+ ([, component]) => component === g.icon,
+ )?.[0] ?? "User",
+ }));
+
+export const mergeConfiguration = (
+ codeDefaults: ConfigurationContextValue,
+ dbConfig: StoredConfiguration | null,
+): ConfigurationContextValue => {
+ if (!dbConfig) return codeDefaults;
+
+ return {
+ ...codeDefaults,
+ ...(dbConfig.companySectors && {
+ companySectors: dbConfig.companySectors,
+ }),
+ ...(dbConfig.dealCategories && {
+ dealCategories: dbConfig.dealCategories,
+ }),
+ ...(dbConfig.dealPipelineStatuses && {
+ dealPipelineStatuses: dbConfig.dealPipelineStatuses,
+ }),
+ ...(dbConfig.dealStages && { dealStages: dbConfig.dealStages }),
+ ...(dbConfig.noteStatuses && { noteStatuses: dbConfig.noteStatuses }),
+ ...(dbConfig.taskTypes && { taskTypes: dbConfig.taskTypes }),
+ ...(dbConfig.title && { title: dbConfig.title }),
+ ...(dbConfig.darkModeLogo && { darkModeLogo: dbConfig.darkModeLogo }),
+ ...(dbConfig.lightModeLogo && { lightModeLogo: dbConfig.lightModeLogo }),
+ ...(dbConfig.contactGender && {
+ contactGender: hydrateContactGender(dbConfig.contactGender),
+ }),
+ };
+};
diff --git a/src/components/atomic-crm/root/useConfigurationLoader.ts b/src/components/atomic-crm/root/useConfigurationLoader.ts
new file mode 100644
index 00000000..bd95eb4e
--- /dev/null
+++ b/src/components/atomic-crm/root/useConfigurationLoader.ts
@@ -0,0 +1,25 @@
+import { useQuery } from "@tanstack/react-query";
+import { useEffect } from "react";
+import { useDataProvider } from "ra-core";
+
+import type { CrmDataProvider } from "../providers/types";
+import { useConfigurationUpdater } from "./ConfigurationContext";
+import type { StoredConfiguration } from "./storedConfiguration";
+
+export const useConfigurationLoader = () => {
+ const dataProvider = useDataProvider<CrmDataProvider>();
+ const updateConfiguration = useConfigurationUpdater();
+
+ const { data } = useQuery<StoredConfiguration>({
+ queryKey: ["configuration"],
+ queryFn: () => dataProvider.getConfiguration(),
+ staleTime: 1000 * 60 * 5, // 5 minutes
+ retry: false,
+ });
+
+ useEffect(() => {
+ if (data) {
+ updateConfiguration(data);
+ }
+ }, [data, updateConfiguration]);
+};
diff --git a/src/components/atomic-crm/settings/AppConfigPage.tsx b/src/components/atomic-crm/settings/AppConfigPage.tsx
new file mode 100644
index 00000000..a959c695
--- /dev/null
+++ b/src/components/atomic-crm/settings/AppConfigPage.tsx
@@ -0,0 +1,483 @@
+import { Plus, Save, Trash2 } from "lucide-react";
+import { useDataProvider, useNotify } from "ra-core";
+import { useCallback, useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Separator } from "@/components/ui/separator";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Textarea } from "@/components/ui/textarea";
+
+import type { CrmDataProvider } from "../providers/types";
+import {
+ useConfigurationContext,
+ useConfigurationUpdater,
+} from "../root/ConfigurationContext";
+import { genderIconRegistry } from "../root/iconRegistry";
+import {
+ dehydrateContactGender,
+ type StoredConfiguration,
+} from "../root/storedConfiguration";
+
+const SECTIONS = [
+ { id: "branding", label: "Branding" },
+ { id: "company-sectors", label: "Company Sectors" },
+ { id: "deal-stages", label: "Deal Stages" },
+ { id: "deal-categories", label: "Deal Categories" },
+ { id: "note-statuses", label: "Note Statuses" },
+ { id: "task-types", label: "Task Types" },
+ { id: "contact-gender", label: "Contact Gender" },
+];
+
+export const AppConfigPage = () => {
+ const config = useConfigurationContext();
+ const dataProvider = useDataProvider<CrmDataProvider>();
+ const updateConfiguration = useConfigurationUpdater();
+ const notify = useNotify();
+
+ // Local form state
+ const [title, setTitle] = useState(config.title);
+ const [lightModeLogo, setLightModeLogo] = useState(config.lightModeLogo);
+ const [darkModeLogo, setDarkModeLogo] = useState(config.darkModeLogo);
+ const [companySectors, setCompanySectors] = useState(
+ config.companySectors.join("\n"),
+ );
+ const [dealCategories, setDealCategories] = useState(
+ config.dealCategories.join("\n"),
+ );
+ const [taskTypes, setTaskTypes] = useState(config.taskTypes.join("\n"));
+ const [dealStages, setDealStages] = useState(config.dealStages);
+ const [dealPipelineStatuses, setDealPipelineStatuses] = useState(
+ config.dealPipelineStatuses,
+ );
+ const [noteStatuses, setNoteStatuses] = useState(config.noteStatuses);
+ const [contactGender, setContactGender] = useState(
+ dehydrateContactGender(config.contactGender),
+ );
+ const [saving, setSaving] = useState(false);
+
+ // Sync form state when config changes (e.g. after DB load)
+ useEffect(() => {
+ setTitle(config.title);
+ setLightModeLogo(config.lightModeLogo);
+ setDarkModeLogo(config.darkModeLogo);
+ setCompanySectors(config.companySectors.join("\n"));
+ setDealCategories(config.dealCategories.join("\n"));
+ setTaskTypes(config.taskTypes.join("\n"));
+ setDealStages(config.dealStages);
+ setDealPipelineStatuses(config.dealPipelineStatuses);
+ setNoteStatuses(config.noteStatuses);
+ setContactGender(dehydrateContactGender(config.contactGender));
+ }, [config]);
+
+ const handleSave = useCallback(async () => {
+ setSaving(true);
+ try {
+ const storedConfig: StoredConfiguration = {
+ title,
+ lightModeLogo,
+ darkModeLogo,
+ companySectors: companySectors
+ .split("\n")
+ .map((s) => s.trim())
+ .filter(Boolean),
+ dealCategories: dealCategories
+ .split("\n")
+ .map((s) => s.trim())
+ .filter(Boolean),
+ taskTypes: taskTypes
+ .split("\n")
+ .map((s) => s.trim())
+ .filter(Boolean),
+ dealStages,
+ dealPipelineStatuses,
+ noteStatuses,
+ contactGender,
+ };
+ const saved = await dataProvider.updateConfiguration(storedConfig);
+ updateConfiguration(saved);
+ notify("Configuration saved successfully");
+ } catch {
+ notify("Failed to save configuration", { type: "error" });
+ } finally {
+ setSaving(false);
+ }
+ }, [
+ title,
+ lightModeLogo,
+ darkModeLogo,
+ companySectors,
+ dealCategories,
+ taskTypes,
+ dealStages,
+ dealPipelineStatuses,
+ noteStatuses,
+ contactGender,
+ dataProvider,
+ updateConfiguration,
+ notify,
+ ]);
+
+ return (
+ <div className="flex gap-8 mt-8 pb-20">
+ {/* Left navigation */}
+ <nav className="hidden md:block w-48 shrink-0">
+ <div className="sticky top-4 space-y-1">
+ {SECTIONS.map((section) => (
+ <button
+ key={section.id}
+ type="button"
+ onClick={() => {
+ document
+ .getElementById(section.id)
+ ?.scrollIntoView({ behavior: "smooth" });
+ }}
+ className="block w-full text-left px-3 py-1.5 text-sm rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
+ >
+ {section.label}
+ </button>
+ ))}
+ </div>
+ </nav>
+
+ {/* Main content */}
+ <div className="flex-1 min-w-0 max-w-2xl space-y-6">
+ <h1 className="text-2xl font-semibold">App Configuration</h1>
+
+ {/* Branding */}
+ <Card id="branding">
+ <CardContent className="space-y-4">
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ Branding
+ </h2>
+ <div className="space-y-2">
+ <Label htmlFor="title">App Title</Label>
+ <Input
+ id="title"
+ value={title}
+ onChange={(e) => setTitle(e.target.value)}
+ />
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="lightModeLogo">Light Mode Logo URL</Label>
+ <Input
+ id="lightModeLogo"
+ value={lightModeLogo}
+ onChange={(e) => setLightModeLogo(e.target.value)}
+ />
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="darkModeLogo">Dark Mode Logo URL</Label>
+ <Input
+ id="darkModeLogo"
+ value={darkModeLogo}
+ onChange={(e) => setDarkModeLogo(e.target.value)}
+ />
+ </div>
+ </CardContent>
+ </Card>
+
+ {/* Company Sectors */}
+ <Card id="company-sectors">
+ <CardContent className="space-y-4">
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ Company Sectors
+ </h2>
+ <p className="text-sm text-muted-foreground">One sector per line</p>
+ <Textarea
+ value={companySectors}
+ onChange={(e) => setCompanySectors(e.target.value)}
+ rows={8}
+ />
+ </CardContent>
+ </Card>
+
+ {/* Deal Stages */}
+ <Card id="deal-stages">
+ <CardContent className="space-y-4">
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ Deal Stages
+ </h2>
+ {dealStages.map((stage, index) => (
+ <div key={index} className="flex items-center gap-2">
+ <Input
+ placeholder="Value"
+ value={stage.value}
+ onChange={(e) => {
+ const updated = [...dealStages];
+ updated[index] = { ...stage, value: e.target.value };
+ setDealStages(updated);
+ }}
+ className="flex-1"
+ />
+ <Input
+ placeholder="Label"
+ value={stage.label}
+ onChange={(e) => {
+ const updated = [...dealStages];
+ updated[index] = { ...stage, label: e.target.value };
+ setDealStages(updated);
+ }}
+ className="flex-1"
+ />
+ <Button
+ variant="ghost"
+ size="icon"
+ type="button"
+ onClick={() =>
+ setDealStages(dealStages.filter((_, i) => i !== index))
+ }
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </div>
+ ))}
+ <Button
+ variant="outline"
+ size="sm"
+ type="button"
+ onClick={() =>
+ setDealStages([...dealStages, { value: "", label: "" }])
+ }
+ >
+ <Plus className="h-4 w-4 mr-1" /> Add Stage
+ </Button>
+
+ <Separator />
+
+ <h3 className="text-lg font-medium text-muted-foreground">
+ Pipeline Statuses
+ </h3>
+ <p className="text-sm text-muted-foreground">
+ Select which deal stages count as "pipeline" (completed) deals.
+ </p>
+ <div className="flex flex-wrap gap-2">
+ {dealStages.map((stage) => {
+ const isSelected = dealPipelineStatuses.includes(stage.value);
+ return (
+ <Button
+ key={stage.value}
+ type="button"
+ variant={isSelected ? "default" : "outline"}
+ size="sm"
+ onClick={() => {
+ if (isSelected) {
+ setDealPipelineStatuses(
+ dealPipelineStatuses.filter((s) => s !== stage.value),
+ );
+ } else {
+ setDealPipelineStatuses([
+ ...dealPipelineStatuses,
+ stage.value,
+ ]);
+ }
+ }}
+ >
+ {stage.label || stage.value}
+ </Button>
+ );
+ })}
+ </div>
+ </CardContent>
+ </Card>
+
+ {/* Deal Categories */}
+ <Card id="deal-categories">
+ <CardContent className="space-y-4">
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ Deal Categories
+ </h2>
+ <p className="text-sm text-muted-foreground">
+ One category per line
+ </p>
+ <Textarea
+ value={dealCategories}
+ onChange={(e) => setDealCategories(e.target.value)}
+ rows={6}
+ />
+ </CardContent>
+ </Card>
+
+ {/* Note Statuses */}
+ <Card id="note-statuses">
+ <CardContent className="space-y-4">
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ Note Statuses
+ </h2>
+ {noteStatuses.map((status, index) => (
+ <div key={index} className="flex items-center gap-2">
+ <Input
+ placeholder="Value"
+ value={status.value}
+ onChange={(e) => {
+ const updated = [...noteStatuses];
+ updated[index] = { ...status, value: e.target.value };
+ setNoteStatuses(updated);
+ }}
+ className="flex-1"
+ />
+ <Input
+ placeholder="Label"
+ value={status.label}
+ onChange={(e) => {
+ const updated = [...noteStatuses];
+ updated[index] = { ...status, label: e.target.value };
+ setNoteStatuses(updated);
+ }}
+ className="flex-1"
+ />
+ <Input
+ type="color"
+ value={status.color}
+ onChange={(e) => {
+ const updated = [...noteStatuses];
+ updated[index] = { ...status, color: e.target.value };
+ setNoteStatuses(updated);
+ }}
+ className="w-16 p-1 h-9"
+ />
+ <Button
+ variant="ghost"
+ size="icon"
+ type="button"
+ onClick={() =>
+ setNoteStatuses(noteStatuses.filter((_, i) => i !== index))
+ }
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </div>
+ ))}
+ <Button
+ variant="outline"
+ size="sm"
+ type="button"
+ onClick={() =>
+ setNoteStatuses([
+ ...noteStatuses,
+ { value: "", label: "", color: "#808080" },
+ ])
+ }
+ >
+ <Plus className="h-4 w-4 mr-1" /> Add Status
+ </Button>
+ </CardContent>
+ </Card>
+
+ {/* Task Types */}
+ <Card id="task-types">
+ <CardContent className="space-y-4">
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ Task Types
+ </h2>
+ <p className="text-sm text-muted-foreground">One type per line</p>
+ <Textarea
+ value={taskTypes}
+ onChange={(e) => setTaskTypes(e.target.value)}
+ rows={6}
+ />
+ </CardContent>
+ </Card>
+
+ {/* Contact Gender */}
+ <Card id="contact-gender">
+ <CardContent className="space-y-4">
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ Contact Gender Options
+ </h2>
+ {contactGender.map((gender, index) => (
+ <div key={index} className="flex items-center gap-2">
+ <Input
+ placeholder="Value"
+ value={gender.value}
+ onChange={(e) => {
+ const updated = [...contactGender];
+ updated[index] = { ...gender, value: e.target.value };
+ setContactGender(updated);
+ }}
+ className="flex-1"
+ />
+ <Input
+ placeholder="Label"
+ value={gender.label}
+ onChange={(e) => {
+ const updated = [...contactGender];
+ updated[index] = { ...gender, label: e.target.value };
+ setContactGender(updated);
+ }}
+ className="flex-1"
+ />
+ <Select
+ value={gender.icon}
+ onValueChange={(val) => {
+ const updated = [...contactGender];
+ updated[index] = { ...gender, icon: val };
+ setContactGender(updated);
+ }}
+ >
+ <SelectTrigger className="w-36">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {Object.keys(genderIconRegistry).map((name) => (
+ <SelectItem key={name} value={name}>
+ {name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Button
+ variant="ghost"
+ size="icon"
+ type="button"
+ onClick={() =>
+ setContactGender(
+ contactGender.filter((_, i) => i !== index),
+ )
+ }
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </div>
+ ))}
+ <Button
+ variant="outline"
+ size="sm"
+ type="button"
+ onClick={() =>
+ setContactGender([
+ ...contactGender,
+ { value: "", label: "", icon: "User" },
+ ])
+ }
+ >
+ <Plus className="h-4 w-4 mr-1" /> Add Gender Option
+ </Button>
+ </CardContent>
+ </Card>
+ </div>
+
+ {/* Sticky save button */}
+ <div className="fixed bottom-0 left-0 right-0 border-t bg-background p-4">
+ <div className="max-w-screen-xl mx-auto flex gap-8 px-4">
+ <div className="hidden md:block w-48 shrink-0" />
+ <div className="flex-1 min-w-0 max-w-2xl flex justify-end">
+ <Button onClick={handleSave} disabled={saving}>
+ <Save className="h-4 w-4 mr-1" />
+ {saving ? "Saving..." : "Save Configuration"}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+AppConfigPage.path = "/app-settings";
diff --git a/supabase/migrations/20260211194545_app_configuration.sql b/supabase/migrations/20260211194545_app_configuration.sql
new file mode 100644
index 00000000..457028b1
--- /dev/null
+++ b/supabase/migrations/20260211194545_app_configuration.sql
@@ -0,0 +1,36 @@
+create table "public"."configuration" (
+ "id" integer not null default 1,
+ "config" jsonb not null default '{}'::jsonb,
+ constraint "configuration_pkey" primary key ("id"),
+ constraint "configuration_singleton" check ("id" = 1)
+);
+
+alter table "public"."configuration" enable row level security;
+
+-- Helper to check admin status in RLS policies
+create or replace function public.is_admin()
+returns boolean language plpgsql security definer set search_path = '' as $$
+begin
+ return exists (
+ select 1 from public.sales where user_id = auth.uid() and administrator = true
+ );
+end;
+$$;
+
+-- All authenticated users can read
+create policy "Enable read for authenticated" on "public"."configuration"
+ as permissive for select to authenticated using (true);
+
+-- Only admins can insert/update
+create policy "Enable insert for admins" on "public"."configuration"
+ as permissive for insert to authenticated with check (public.is_admin());
+create policy "Enable update for admins" on "public"."configuration"
+ as permissive for update to authenticated
+ using (public.is_admin()) with check (public.is_admin());
+
+-- Grants
+grant select, insert, update on "public"."configuration" to "authenticated";
+grant select, insert, update on "public"."configuration" to "service_role";
+
+-- Seed empty config (code defaults apply)
+insert into "public"."configuration" ("id", "config") values (1, '{}'::jsonb);