Skip to content

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

Rename components

François Zaninotto75256cd6b79f
diff --git a/src/components/atomic-crm/layout/Header.tsx b/src/components/atomic-crm/layout/Header.tsx
index e9cd4a9d..146e159b 100644
--- a/src/components/atomic-crm/layout/Header.tsx
+++ b/src/components/atomic-crm/layout/Header.tsx
@@ -76,12 +76,12 @@ const Header = () => {
<ThemeModeToggle />
<RefreshButton />
<UserMenu>
- <ConfigurationMenu />
+ <ProfileMenu />
<CanAccess resource="sales" action="list">
<UsersMenu />
</CanAccess>
<CanAccess resource="configuration" action="edit">
- <AppSettingsMenu />
+ <SettingsMenu />
</CanAccess>
<ImportFromJsonMenuItem />
</UserMenu>
@@ -129,14 +129,14 @@ const UsersMenu = () => {
);
};
-const ConfigurationMenu = () => {
+const ProfileMenu = () => {
const userMenuContext = useUserMenu();
if (!userMenuContext) {
- throw new Error("<ConfigurationMenu> must be used inside <UserMenu?");
+ throw new Error("<ProfileMenu> must be used inside <UserMenu?");
}
return (
<DropdownMenuItem asChild onClick={userMenuContext.onClose}>
- <Link to="/settings" className="flex items-center gap-2">
+ <Link to="/profile" className="flex items-center gap-2">
<User />
Profile
</Link>
@@ -144,14 +144,14 @@ const ConfigurationMenu = () => {
);
};
-const AppSettingsMenu = () => {
+const SettingsMenu = () => {
const userMenuContext = useUserMenu();
if (!userMenuContext) {
- throw new Error("<AppSettingsMenu> must be used inside <UserMenu>");
+ throw new Error("<SettingsMenu> must be used inside <UserMenu>");
}
return (
<DropdownMenuItem asChild onClick={userMenuContext.onClose}>
- <Link to="/app-settings" className="flex items-center gap-2">
+ <Link to="/settings" className="flex items-center gap-2">
<Settings /> Settings
</Link>
</DropdownMenuItem>
diff --git a/src/components/atomic-crm/root/CRM.tsx b/src/components/atomic-crm/root/CRM.tsx
index 26d4e190..00896fa6 100644
--- a/src/components/atomic-crm/root/CRM.tsx
+++ b/src/components/atomic-crm/root/CRM.tsx
@@ -30,7 +30,7 @@ import {
dataProvider as defaultDataProvider,
} from "../providers/supabase";
import sales from "../sales";
-import { AppConfigPage } from "../settings/AppConfigPage";
+import { ProfilePage } from "../settings/ProfilePage";
import { SettingsPage } from "../settings/SettingsPage";
import {
CONFIGURATION_STORE_KEY,
@@ -238,8 +238,8 @@ const DesktopAdmin = (props: CoreAdminProps) => {
</CustomRoutes>
<CustomRoutes>
+ <Route path={ProfilePage.path} element={<ProfilePage />} />
<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/settings/AppConfigPage.tsx b/src/components/atomic-crm/settings/AppConfigPage.tsx
deleted file mode 100644
index 6a09ec9e..00000000
--- a/src/components/atomic-crm/settings/AppConfigPage.tsx
+++ /dev/null
@@ -1,398 +0,0 @@
-import { RotateCcw, Save } from "lucide-react";
-import { EditBase, Form, useGetList, useInput, useNotify } from "ra-core";
-import { useCallback, useMemo } from "react";
-import { useFormContext } from "react-hook-form";
-import { Button } from "@/components/ui/button";
-import { Card, CardContent } from "@/components/ui/card";
-import { Separator } from "@/components/ui/separator";
-import { ArrayInput } from "@/components/admin/array-input";
-import { SimpleFormIterator } from "@/components/admin/simple-form-iterator";
-import { TextInput } from "@/components/admin/text-input";
-
-import ImageEditorField from "../misc/ImageEditorField";
-import {
- useConfigurationContext,
- useConfigurationUpdater,
- type ConfigurationContextValue,
-} from "../root/ConfigurationContext";
-import { defaultConfiguration } from "../root/defaultConfiguration";
-
-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" },
-];
-
-/**
- * Derive a stable slug value from a display label.
- * e.g. "Communication Services" → "communication-services"
- */
-const toSlug = (label: string): string =>
- label
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-|-$/g, "");
-
-/** Ensure every item in a { value, label } array has a value (slug from label). */
-const ensureValues = (items: { value?: string; label: string }[] | undefined) =>
- items?.map((item) => ({ ...item, value: item.value || toSlug(item.label) }));
-
-const transformFormValues = (data: Record<string, any>) => ({
- config: {
- title: data.title,
- lightModeLogo: data.lightModeLogo,
- darkModeLogo: data.darkModeLogo,
- companySectors: ensureValues(data.companySectors),
- dealCategories: ensureValues(data.dealCategories),
- taskTypes: ensureValues(data.taskTypes),
- dealStages: ensureValues(data.dealStages),
- dealPipelineStatuses: data.dealPipelineStatuses,
- noteStatuses: ensureValues(data.noteStatuses),
- } as ConfigurationContextValue,
-});
-
-export const AppConfigPage = () => {
- const updateConfiguration = useConfigurationUpdater();
- const notify = useNotify();
-
- return (
- <EditBase
- resource="configuration"
- id={1}
- mutationMode="pessimistic"
- redirect={false}
- transform={transformFormValues}
- mutationOptions={{
- onSuccess: (data: any) => {
- updateConfiguration(data.config);
- notify("Configuration saved successfully");
- },
- onError: () => {
- notify("Failed to save configuration", { type: "error" });
- },
- }}
- >
- <AppConfigForm />
- </EditBase>
- );
-};
-
-AppConfigPage.path = "/app-settings";
-
-const AppConfigForm = () => {
- const config = useConfigurationContext();
-
- const defaultValues = useMemo(
- () => ({
- title: config.title,
- lightModeLogo: { src: config.lightModeLogo },
- darkModeLogo: { src: config.darkModeLogo },
- companySectors: config.companySectors,
- dealCategories: config.dealCategories,
- taskTypes: config.taskTypes,
- dealStages: config.dealStages,
- dealPipelineStatuses: config.dealPipelineStatuses,
- noteStatuses: config.noteStatuses,
- }),
- [config],
- );
-
- return (
- <Form defaultValues={defaultValues}>
- <AppConfigFormFields />
- </Form>
- );
-};
-
-const AppConfigFormFields = () => {
- const {
- watch,
- setValue,
- reset,
- formState: { isSubmitting },
- } = useFormContext();
-
- const dealStages = watch("dealStages");
- const dealPipelineStatuses: string[] = watch("dealPipelineStatuses") ?? [];
-
- const { data: deals } = useGetList("deals", {
- pagination: { page: 1, perPage: 1000 },
- });
-
- const validateDealStages = useCallback(
- (stages: { value: string; label: string }[] | undefined) => {
- if (!deals || !stages) return undefined;
- const stageValues = new Set(
- stages.map((s) => s.value || toSlug(s.label)),
- );
- const inUse = deals
- .filter((deal) => deal.stage && !stageValues.has(deal.stage))
- .map((deal) => deal.stage);
- const uniqueInUse = [...new Set(inUse)];
- if (uniqueInUse.length > 0) {
- return `Cannot remove stages that are still used by deals: ${uniqueInUse.join(", ")}`;
- }
- return undefined;
- },
- [deals],
- );
-
- const validateDealCategories = useCallback(
- (categories: { value: string; label: string }[] | undefined) => {
- if (!deals || !categories) return undefined;
- const categoryValues = new Set(
- categories.map((c) => c.value || toSlug(c.label)),
- );
- const inUse = deals
- .filter((deal) => deal.category && !categoryValues.has(deal.category))
- .map((deal) => deal.category);
- const uniqueInUse = [...new Set(inUse)];
- if (uniqueInUse.length > 0) {
- return `Cannot remove categories that are still used by deals: ${uniqueInUse.join(", ")}`;
- }
- return undefined;
- },
- [deals],
- );
-
- return (
- <div className="flex gap-8 mt-4 pb-20">
- {/* Left navigation */}
- <nav className="hidden md:block w-48 shrink-0">
- <div className="sticky top-4 space-y-1">
- <h1 className="text-2xl font-semibold px-3 mb-2">Settings</h1>
- {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 text-sm rounded-md 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">
- {/* Branding */}
- <Card id="branding">
- <CardContent className="space-y-4">
- <h2 className="text-xl font-semibold text-muted-foreground">
- Branding
- </h2>
- <TextInput source="title" label="App Title" />
- <div className="flex gap-8">
- <div className="flex flex-col items-center gap-1">
- <p className="text-sm text-muted-foreground">Light Mode Logo</p>
- <ImageEditorField
- source="lightModeLogo"
- width={100}
- height={100}
- linkPosition="bottom"
- backgroundImageColor="#f5f5f5"
- />
- </div>
- <div className="flex flex-col items-center gap-1">
- <p className="text-sm text-muted-foreground">Dark Mode Logo</p>
- <ImageEditorField
- source="darkModeLogo"
- width={100}
- height={100}
- linkPosition="bottom"
- backgroundImageColor="#1a1a1a"
- />
- </div>
- </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>
- <ArrayInput
- source="companySectors"
- label={false}
- helperText={false}
- >
- <SimpleFormIterator disableReordering disableClear>
- <TextInput source="label" label={false} />
- </SimpleFormIterator>
- </ArrayInput>
- </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>
- <ArrayInput
- source="dealStages"
- label={false}
- helperText={false}
- validate={validateDealStages}
- >
- <SimpleFormIterator disableClear>
- <TextInput source="label" label={false} />
- </SimpleFormIterator>
- </ArrayInput>
-
- <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 &quot;pipeline&quot; (completed)
- deals.
- </p>
- <div className="flex flex-wrap gap-2">
- {dealStages?.map(
- (stage: { value: string; label: string }, idx: number) => {
- const isSelected = dealPipelineStatuses.includes(stage.value);
- return (
- <Button
- key={idx}
- type="button"
- variant={isSelected ? "default" : "outline"}
- size="sm"
- onClick={() => {
- if (isSelected) {
- setValue(
- "dealPipelineStatuses",
- dealPipelineStatuses.filter(
- (s) => s !== stage.value,
- ),
- );
- } else {
- setValue("dealPipelineStatuses", [
- ...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>
- <ArrayInput
- source="dealCategories"
- label={false}
- helperText={false}
- validate={validateDealCategories}
- >
- <SimpleFormIterator disableReordering disableClear>
- <TextInput source="label" label={false} />
- </SimpleFormIterator>
- </ArrayInput>
- </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>
- <ArrayInput source="noteStatuses" label={false} helperText={false}>
- <SimpleFormIterator inline disableReordering disableClear>
- <TextInput source="label" label={false} className="flex-1" />
- <ColorInput source="color" />
- </SimpleFormIterator>
- </ArrayInput>
- </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>
- <ArrayInput source="taskTypes" label={false} helperText={false}>
- <SimpleFormIterator disableReordering disableClear>
- <TextInput source="label" label={false} />
- </SimpleFormIterator>
- </ArrayInput>
- </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-between">
- <Button
- type="button"
- variant="ghost"
- onClick={() =>
- reset({
- ...defaultConfiguration,
- lightModeLogo: {
- src: defaultConfiguration.lightModeLogo,
- },
- darkModeLogo: { src: defaultConfiguration.darkModeLogo },
- })
- }
- >
- <RotateCcw className="h-4 w-4 mr-1" />
- Reset to Defaults
- </Button>
- <div className="flex gap-2">
- <Button
- type="button"
- variant="outline"
- onClick={() => window.history.back()}
- >
- Cancel
- </Button>
- <Button type="submit" disabled={isSubmitting}>
- <Save className="h-4 w-4 mr-1" />
- {isSubmitting ? "Saving..." : "Save Configuration"}
- </Button>
- </div>
- </div>
- </div>
- </div>
- </div>
- );
-};
-
-/** A minimal color picker input compatible with ra-core's useInput. */
-const ColorInput = ({ source }: { source: string }) => {
- const { field } = useInput({ source });
- return (
- <input
- type="color"
- {...field}
- value={field.value || "#000000"}
- className="w-9 h-9 shrink-0 cursor-pointer appearance-none rounded border bg-transparent p-0.5 [&::-webkit-color-swatch-wrapper]:cursor-pointer [&::-webkit-color-swatch-wrapper]:p-0 [&::-webkit-color-swatch]:cursor-pointer [&::-webkit-color-swatch]:rounded-sm [&::-webkit-color-swatch]:border-none [&::-moz-color-swatch]:cursor-pointer [&::-moz-color-swatch]:rounded-sm [&::-moz-color-swatch]:border-none"
- />
- );
-};
diff --git a/src/components/atomic-crm/settings/ProfilePage.tsx b/src/components/atomic-crm/settings/ProfilePage.tsx
new file mode 100644
index 00000000..e5c1a280
--- /dev/null
+++ b/src/components/atomic-crm/settings/ProfilePage.tsx
@@ -0,0 +1,256 @@
+import { useMutation } from "@tanstack/react-query";
+import { CircleX, Copy, Pencil, Save } from "lucide-react";
+import {
+ Form,
+ useDataProvider,
+ useGetIdentity,
+ useGetOne,
+ useNotify,
+ useRecordContext,
+} from "ra-core";
+import { useState } from "react";
+import { useFormState } from "react-hook-form";
+import { RecordField } from "@/components/admin/record-field";
+import { TextInput } from "@/components/admin/text-input";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent } from "@/components/ui/card";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+
+import ImageEditorField from "../misc/ImageEditorField";
+import type { CrmDataProvider } from "../providers/types";
+import type { Sale, SalesFormData } from "../types";
+
+export const ProfilePage = () => {
+ const [isEditMode, setEditMode] = useState(false);
+ const { identity, refetch: refetchIdentity } = useGetIdentity();
+ const { data, refetch: refetchUser } = useGetOne("sales", {
+ id: identity?.id,
+ });
+ const notify = useNotify();
+ const dataProvider = useDataProvider<CrmDataProvider>();
+
+ const { mutate } = useMutation({
+ mutationKey: ["signup"],
+ mutationFn: async (data: SalesFormData) => {
+ if (!identity) {
+ throw new Error("Record not found");
+ }
+ return dataProvider.salesUpdate(identity.id, data);
+ },
+ onSuccess: () => {
+ refetchIdentity();
+ refetchUser();
+ setEditMode(false);
+ notify("Your profile has been updated");
+ },
+ onError: (_) => {
+ notify("An error occurred. Please try again", {
+ type: "error",
+ });
+ },
+ });
+
+ if (!identity) return null;
+
+ const handleOnSubmit = async (values: any) => {
+ mutate(values);
+ };
+
+ return (
+ <div className="max-w-lg mx-auto mt-8">
+ <Form onSubmit={handleOnSubmit} record={data}>
+ <SettingsForm isEditMode={isEditMode} setEditMode={setEditMode} />
+ </Form>
+ </div>
+ );
+};
+
+const SettingsForm = ({
+ isEditMode,
+ setEditMode,
+}: {
+ isEditMode: boolean;
+ setEditMode: (value: boolean) => void;
+}) => {
+ const notify = useNotify();
+ const record = useRecordContext<Sale>();
+ const { identity, refetch } = useGetIdentity();
+ const { isDirty } = useFormState();
+ const dataProvider = useDataProvider<CrmDataProvider>();
+
+ const { mutate: updatePassword } = useMutation({
+ mutationKey: ["updatePassword"],
+ mutationFn: async () => {
+ if (!identity) {
+ throw new Error("Record not found");
+ }
+ return dataProvider.updatePassword(identity.id);
+ },
+ onSuccess: () => {
+ notify("A reset password email has been sent to your email address");
+ },
+ onError: (e) => {
+ notify(`${e}`, {
+ type: "error",
+ });
+ },
+ });
+
+ const { mutate: mutateSale } = useMutation({
+ mutationKey: ["signup"],
+ mutationFn: async (data: SalesFormData) => {
+ if (!record) {
+ throw new Error("Record not found");
+ }
+ return dataProvider.salesUpdate(record.id, data);
+ },
+ onSuccess: () => {
+ refetch();
+ notify("Your profile has been updated");
+ },
+ onError: () => {
+ notify("An error occurred. Please try again.");
+ },
+ });
+ if (!identity) return null;
+
+ const handleClickOpenPasswordChange = () => {
+ updatePassword();
+ };
+
+ const handleAvatarUpdate = async (values: any) => {
+ mutateSale(values);
+ };
+
+ return (
+ <div className="space-y-4">
+ <Card>
+ <CardContent>
+ <div className="mb-4 flex flex-row justify-between">
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ My info
+ </h2>
+ </div>
+
+ <div className="space-y-4 mb-4">
+ <ImageEditorField
+ source="avatar"
+ type="avatar"
+ onSave={handleAvatarUpdate}
+ linkPosition="right"
+ />
+ <TextRender source="first_name" isEditMode={isEditMode} />
+ <TextRender source="last_name" isEditMode={isEditMode} />
+ <TextRender source="email" isEditMode={isEditMode} />
+ </div>
+
+ <div className="flex flex-row justify-end gap-2">
+ {!isEditMode && (
+ <>
+ <Button
+ variant="outline"
+ type="button"
+ onClick={handleClickOpenPasswordChange}
+ >
+ Change password
+ </Button>
+ </>
+ )}
+
+ <Button
+ type="button"
+ variant={isEditMode ? "ghost" : "outline"}
+ onClick={() => setEditMode(!isEditMode)}
+ className="flex items-center"
+ >
+ {isEditMode ? <CircleX /> : <Pencil />}
+ {isEditMode ? "Cancel" : "Edit"}
+ </Button>
+
+ {isEditMode && (
+ <Button type="submit" disabled={!isDirty} variant="outline">
+ <Save />
+ Save
+ </Button>
+ )}
+ </div>
+ </CardContent>
+ </Card>
+ {import.meta.env.VITE_INBOUND_EMAIL && (
+ <Card>
+ <CardContent>
+ <div className="space-y-4 justify-between">
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ Inbound email
+ </h2>
+ <p className="text-sm text-muted-foreground">
+ You can start sending emails to your server's inbound email
+ address, e.g. by adding it to the
+ <b> Cc: </b> field. Atomic CRM will process the emails and add
+ notes to the corresponding contacts.
+ </p>
+ <CopyPaste />
+ </div>
+ </CardContent>
+ </Card>
+ )}
+ </div>
+ );
+};
+
+const TextRender = ({
+ source,
+ isEditMode,
+}: {
+ source: string;
+ isEditMode: boolean;
+}) => {
+ if (isEditMode) {
+ return <TextInput source={source} helperText={false} />;
+ }
+ return (
+ <div className="m-2">
+ <RecordField source={source} />
+ </div>
+ );
+};
+
+const CopyPaste = () => {
+ const [copied, setCopied] = useState(false);
+ const handleCopy = () => {
+ setCopied(true);
+ navigator.clipboard.writeText(import.meta.env.VITE_INBOUND_EMAIL);
+ setTimeout(() => {
+ setCopied(false);
+ }, 1500);
+ };
+ return (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ onClick={handleCopy}
+ variant="ghost"
+ className="normal-case justify-between w-full"
+ >
+ <span className="overflow-hidden text-ellipsis">
+ {import.meta.env.VITE_INBOUND_EMAIL}
+ </span>
+ <Copy className="h-4 w-4 ml-2" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{copied ? "Copied!" : "Copy"}</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+};
+
+ProfilePage.path = "/profile";
diff --git a/src/components/atomic-crm/settings/SettingsPage.tsx b/src/components/atomic-crm/settings/SettingsPage.tsx
index accc0cca..72e103e6 100644
--- a/src/components/atomic-crm/settings/SettingsPage.tsx
+++ b/src/components/atomic-crm/settings/SettingsPage.tsx
@@ -1,256 +1,398 @@
-import { useMutation } from "@tanstack/react-query";
-import { CircleX, Copy, Pencil, Save } from "lucide-react";
-import {
- Form,
- useDataProvider,
- useGetIdentity,
- useGetOne,
- useNotify,
- useRecordContext,
-} from "ra-core";
-import { useState } from "react";
-import { useFormState } from "react-hook-form";
-import { RecordField } from "@/components/admin/record-field";
-import { TextInput } from "@/components/admin/text-input";
+import { RotateCcw, Save } from "lucide-react";
+import { EditBase, Form, useGetList, useInput, useNotify } from "ra-core";
+import { useCallback, useMemo } from "react";
+import { useFormContext } from "react-hook-form";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/components/ui/tooltip";
+import { Separator } from "@/components/ui/separator";
+import { ArrayInput } from "@/components/admin/array-input";
+import { SimpleFormIterator } from "@/components/admin/simple-form-iterator";
+import { TextInput } from "@/components/admin/text-input";
import ImageEditorField from "../misc/ImageEditorField";
-import type { CrmDataProvider } from "../providers/types";
-import type { Sale, SalesFormData } from "../types";
+import {
+ useConfigurationContext,
+ useConfigurationUpdater,
+ type ConfigurationContextValue,
+} from "../root/ConfigurationContext";
+import { defaultConfiguration } from "../root/defaultConfiguration";
+
+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" },
+];
+
+/**
+ * Derive a stable slug value from a display label.
+ * e.g. "Communication Services" → "communication-services"
+ */
+const toSlug = (label: string): string =>
+ label
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-|-$/g, "");
+
+/** Ensure every item in a { value, label } array has a value (slug from label). */
+const ensureValues = (items: { value?: string; label: string }[] | undefined) =>
+ items?.map((item) => ({ ...item, value: item.value || toSlug(item.label) }));
+
+const transformFormValues = (data: Record<string, any>) => ({
+ config: {
+ title: data.title,
+ lightModeLogo: data.lightModeLogo,
+ darkModeLogo: data.darkModeLogo,
+ companySectors: ensureValues(data.companySectors),
+ dealCategories: ensureValues(data.dealCategories),
+ taskTypes: ensureValues(data.taskTypes),
+ dealStages: ensureValues(data.dealStages),
+ dealPipelineStatuses: data.dealPipelineStatuses,
+ noteStatuses: ensureValues(data.noteStatuses),
+ } as ConfigurationContextValue,
+});
export const SettingsPage = () => {
- const [isEditMode, setEditMode] = useState(false);
- const { identity, refetch: refetchIdentity } = useGetIdentity();
- const { data, refetch: refetchUser } = useGetOne("sales", {
- id: identity?.id,
- });
+ const updateConfiguration = useConfigurationUpdater();
const notify = useNotify();
- const dataProvider = useDataProvider<CrmDataProvider>();
- const { mutate } = useMutation({
- mutationKey: ["signup"],
- mutationFn: async (data: SalesFormData) => {
- if (!identity) {
- throw new Error("Record not found");
- }
- return dataProvider.salesUpdate(identity.id, data);
- },
- onSuccess: () => {
- refetchIdentity();
- refetchUser();
- setEditMode(false);
- notify("Your profile has been updated");
- },
- onError: (_) => {
- notify("An error occurred. Please try again", {
- type: "error",
- });
- },
- });
+ return (
+ <EditBase
+ resource="configuration"
+ id={1}
+ mutationMode="pessimistic"
+ redirect={false}
+ transform={transformFormValues}
+ mutationOptions={{
+ onSuccess: (data: any) => {
+ updateConfiguration(data.config);
+ notify("Configuration saved successfully");
+ },
+ onError: () => {
+ notify("Failed to save configuration", { type: "error" });
+ },
+ }}
+ >
+ <SettingsForm />
+ </EditBase>
+ );
+};
- if (!identity) return null;
+SettingsPage.path = "/settings";
- const handleOnSubmit = async (values: any) => {
- mutate(values);
- };
+const SettingsForm = () => {
+ const config = useConfigurationContext();
+
+ const defaultValues = useMemo(
+ () => ({
+ title: config.title,
+ lightModeLogo: { src: config.lightModeLogo },
+ darkModeLogo: { src: config.darkModeLogo },
+ companySectors: config.companySectors,
+ dealCategories: config.dealCategories,
+ taskTypes: config.taskTypes,
+ dealStages: config.dealStages,
+ dealPipelineStatuses: config.dealPipelineStatuses,
+ noteStatuses: config.noteStatuses,
+ }),
+ [config],
+ );
return (
- <div className="max-w-lg mx-auto mt-8">
- <Form onSubmit={handleOnSubmit} record={data}>
- <SettingsForm isEditMode={isEditMode} setEditMode={setEditMode} />
- </Form>
- </div>
+ <Form defaultValues={defaultValues}>
+ <SettingsFormFields />
+ </Form>
);
};
-const SettingsForm = ({
- isEditMode,
- setEditMode,
-}: {
- isEditMode: boolean;
- setEditMode: (value: boolean) => void;
-}) => {
- const notify = useNotify();
- const record = useRecordContext<Sale>();
- const { identity, refetch } = useGetIdentity();
- const { isDirty } = useFormState();
- const dataProvider = useDataProvider<CrmDataProvider>();
+const SettingsFormFields = () => {
+ const {
+ watch,
+ setValue,
+ reset,
+ formState: { isSubmitting },
+ } = useFormContext();
- const { mutate: updatePassword } = useMutation({
- mutationKey: ["updatePassword"],
- mutationFn: async () => {
- if (!identity) {
- throw new Error("Record not found");
- }
- return dataProvider.updatePassword(identity.id);
- },
- onSuccess: () => {
- notify("A reset password email has been sent to your email address");
- },
- onError: (e) => {
- notify(`${e}`, {
- type: "error",
- });
- },
+ const dealStages = watch("dealStages");
+ const dealPipelineStatuses: string[] = watch("dealPipelineStatuses") ?? [];
+
+ const { data: deals } = useGetList("deals", {
+ pagination: { page: 1, perPage: 1000 },
});
- const { mutate: mutateSale } = useMutation({
- mutationKey: ["signup"],
- mutationFn: async (data: SalesFormData) => {
- if (!record) {
- throw new Error("Record not found");
+ const validateDealStages = useCallback(
+ (stages: { value: string; label: string }[] | undefined) => {
+ if (!deals || !stages) return undefined;
+ const stageValues = new Set(
+ stages.map((s) => s.value || toSlug(s.label)),
+ );
+ const inUse = deals
+ .filter((deal) => deal.stage && !stageValues.has(deal.stage))
+ .map((deal) => deal.stage);
+ const uniqueInUse = [...new Set(inUse)];
+ if (uniqueInUse.length > 0) {
+ return `Cannot remove stages that are still used by deals: ${uniqueInUse.join(", ")}`;
}
- return dataProvider.salesUpdate(record.id, data);
- },
- onSuccess: () => {
- refetch();
- notify("Your profile has been updated");
+ return undefined;
},
- onError: () => {
- notify("An error occurred. Please try again.");
+ [deals],
+ );
+
+ const validateDealCategories = useCallback(
+ (categories: { value: string; label: string }[] | undefined) => {
+ if (!deals || !categories) return undefined;
+ const categoryValues = new Set(
+ categories.map((c) => c.value || toSlug(c.label)),
+ );
+ const inUse = deals
+ .filter((deal) => deal.category && !categoryValues.has(deal.category))
+ .map((deal) => deal.category);
+ const uniqueInUse = [...new Set(inUse)];
+ if (uniqueInUse.length > 0) {
+ return `Cannot remove categories that are still used by deals: ${uniqueInUse.join(", ")}`;
+ }
+ return undefined;
},
- });
- if (!identity) return null;
+ [deals],
+ );
+
+ return (
+ <div className="flex gap-8 mt-4 pb-20">
+ {/* Left navigation */}
+ <nav className="hidden md:block w-48 shrink-0">
+ <div className="sticky top-4 space-y-1">
+ <h1 className="text-2xl font-semibold px-3 mb-2">Settings</h1>
+ {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 text-sm rounded-md 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">
+ {/* Branding */}
+ <Card id="branding">
+ <CardContent className="space-y-4">
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ Branding
+ </h2>
+ <TextInput source="title" label="App Title" />
+ <div className="flex gap-8">
+ <div className="flex flex-col items-center gap-1">
+ <p className="text-sm text-muted-foreground">Light Mode Logo</p>
+ <ImageEditorField
+ source="lightModeLogo"
+ width={100}
+ height={100}
+ linkPosition="bottom"
+ backgroundImageColor="#f5f5f5"
+ />
+ </div>
+ <div className="flex flex-col items-center gap-1">
+ <p className="text-sm text-muted-foreground">Dark Mode Logo</p>
+ <ImageEditorField
+ source="darkModeLogo"
+ width={100}
+ height={100}
+ linkPosition="bottom"
+ backgroundImageColor="#1a1a1a"
+ />
+ </div>
+ </div>
+ </CardContent>
+ </Card>
- const handleClickOpenPasswordChange = () => {
- updatePassword();
- };
+ {/* Company Sectors */}
+ <Card id="company-sectors">
+ <CardContent className="space-y-4">
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ Company Sectors
+ </h2>
+ <ArrayInput
+ source="companySectors"
+ label={false}
+ helperText={false}
+ >
+ <SimpleFormIterator disableReordering disableClear>
+ <TextInput source="label" label={false} />
+ </SimpleFormIterator>
+ </ArrayInput>
+ </CardContent>
+ </Card>
- const handleAvatarUpdate = async (values: any) => {
- mutateSale(values);
- };
+ {/* Deal Stages */}
+ <Card id="deal-stages">
+ <CardContent className="space-y-4">
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ Deal Stages
+ </h2>
+ <ArrayInput
+ source="dealStages"
+ label={false}
+ helperText={false}
+ validate={validateDealStages}
+ >
+ <SimpleFormIterator disableClear>
+ <TextInput source="label" label={false} />
+ </SimpleFormIterator>
+ </ArrayInput>
- return (
- <div className="space-y-4">
- <Card>
- <CardContent>
- <div className="mb-4 flex flex-row justify-between">
+ <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 &quot;pipeline&quot; (completed)
+ deals.
+ </p>
+ <div className="flex flex-wrap gap-2">
+ {dealStages?.map(
+ (stage: { value: string; label: string }, idx: number) => {
+ const isSelected = dealPipelineStatuses.includes(stage.value);
+ return (
+ <Button
+ key={idx}
+ type="button"
+ variant={isSelected ? "default" : "outline"}
+ size="sm"
+ onClick={() => {
+ if (isSelected) {
+ setValue(
+ "dealPipelineStatuses",
+ dealPipelineStatuses.filter(
+ (s) => s !== stage.value,
+ ),
+ );
+ } else {
+ setValue("dealPipelineStatuses", [
+ ...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">
- My info
+ Deal Categories
</h2>
- </div>
+ <ArrayInput
+ source="dealCategories"
+ label={false}
+ helperText={false}
+ validate={validateDealCategories}
+ >
+ <SimpleFormIterator disableReordering disableClear>
+ <TextInput source="label" label={false} />
+ </SimpleFormIterator>
+ </ArrayInput>
+ </CardContent>
+ </Card>
- <div className="space-y-4 mb-4">
- <ImageEditorField
- source="avatar"
- type="avatar"
- onSave={handleAvatarUpdate}
- linkPosition="right"
- />
- <TextRender source="first_name" isEditMode={isEditMode} />
- <TextRender source="last_name" isEditMode={isEditMode} />
- <TextRender source="email" isEditMode={isEditMode} />
- </div>
+ {/* Note Statuses */}
+ <Card id="note-statuses">
+ <CardContent className="space-y-4">
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ Note Statuses
+ </h2>
+ <ArrayInput source="noteStatuses" label={false} helperText={false}>
+ <SimpleFormIterator inline disableReordering disableClear>
+ <TextInput source="label" label={false} className="flex-1" />
+ <ColorInput source="color" />
+ </SimpleFormIterator>
+ </ArrayInput>
+ </CardContent>
+ </Card>
- <div className="flex flex-row justify-end gap-2">
- {!isEditMode && (
- <>
- <Button
- variant="outline"
- type="button"
- onClick={handleClickOpenPasswordChange}
- >
- Change password
- </Button>
- </>
- )}
+ {/* Task Types */}
+ <Card id="task-types">
+ <CardContent className="space-y-4">
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ Task Types
+ </h2>
+ <ArrayInput source="taskTypes" label={false} helperText={false}>
+ <SimpleFormIterator disableReordering disableClear>
+ <TextInput source="label" label={false} />
+ </SimpleFormIterator>
+ </ArrayInput>
+ </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-between">
<Button
type="button"
- variant={isEditMode ? "ghost" : "outline"}
- onClick={() => setEditMode(!isEditMode)}
- className="flex items-center"
+ variant="ghost"
+ onClick={() =>
+ reset({
+ ...defaultConfiguration,
+ lightModeLogo: {
+ src: defaultConfiguration.lightModeLogo,
+ },
+ darkModeLogo: { src: defaultConfiguration.darkModeLogo },
+ })
+ }
>
- {isEditMode ? <CircleX /> : <Pencil />}
- {isEditMode ? "Cancel" : "Edit"}
+ <RotateCcw className="h-4 w-4 mr-1" />
+ Reset to Defaults
</Button>
-
- {isEditMode && (
- <Button type="submit" disabled={!isDirty} variant="outline">
- <Save />
- Save
+ <div className="flex gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => window.history.back()}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" disabled={isSubmitting}>
+ <Save className="h-4 w-4 mr-1" />
+ {isSubmitting ? "Saving..." : "Save Configuration"}
</Button>
- )}
- </div>
- </CardContent>
- </Card>
- {import.meta.env.VITE_INBOUND_EMAIL && (
- <Card>
- <CardContent>
- <div className="space-y-4 justify-between">
- <h2 className="text-xl font-semibold text-muted-foreground">
- Inbound email
- </h2>
- <p className="text-sm text-muted-foreground">
- You can start sending emails to your server's inbound email
- address, e.g. by adding it to the
- <b> Cc: </b> field. Atomic CRM will process the emails and add
- notes to the corresponding contacts.
- </p>
- <CopyPaste />
</div>
- </CardContent>
- </Card>
- )}
- </div>
- );
-};
-
-const TextRender = ({
- source,
- isEditMode,
-}: {
- source: string;
- isEditMode: boolean;
-}) => {
- if (isEditMode) {
- return <TextInput source={source} helperText={false} />;
- }
- return (
- <div className="m-2">
- <RecordField source={source} />
+ </div>
+ </div>
+ </div>
</div>
);
};
-const CopyPaste = () => {
- const [copied, setCopied] = useState(false);
- const handleCopy = () => {
- setCopied(true);
- navigator.clipboard.writeText(import.meta.env.VITE_INBOUND_EMAIL);
- setTimeout(() => {
- setCopied(false);
- }, 1500);
- };
+/** A minimal color picker input compatible with ra-core's useInput. */
+const ColorInput = ({ source }: { source: string }) => {
+ const { field } = useInput({ source });
return (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- type="button"
- onClick={handleCopy}
- variant="ghost"
- className="normal-case justify-between w-full"
- >
- <span className="overflow-hidden text-ellipsis">
- {import.meta.env.VITE_INBOUND_EMAIL}
- </span>
- <Copy className="h-4 w-4 ml-2" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>{copied ? "Copied!" : "Copy"}</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
+ <input
+ type="color"
+ {...field}
+ value={field.value || "#000000"}
+ className="w-9 h-9 shrink-0 cursor-pointer appearance-none rounded border bg-transparent p-0.5 [&::-webkit-color-swatch-wrapper]:cursor-pointer [&::-webkit-color-swatch-wrapper]:p-0 [&::-webkit-color-swatch]:cursor-pointer [&::-webkit-color-swatch]:rounded-sm [&::-webkit-color-swatch]:border-none [&::-moz-color-swatch]:cursor-pointer [&::-moz-color-swatch]:rounded-sm [&::-moz-color-swatch]:border-none"
+ />
);
};
-
-SettingsPage.path = "/settings";